Compare commits
8 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d253bd44e6 | ||
|
|
1ab2ef42a5 | ||
|
|
3ca9eb60c3 | ||
|
|
504d2926a4 | ||
|
|
64dcce3d0e | ||
|
|
6694a5e44d | ||
|
|
6528c8a53a | ||
|
|
d3d75b4752 |
65
.github/workflows/api-sync-check.yml
vendored
65
.github/workflows/api-sync-check.yml
vendored
@@ -1,65 +0,0 @@
|
|||||||
name: VirtFusion API Change Detection
|
|
||||||
|
|
||||||
on:
|
|
||||||
schedule:
|
|
||||||
- cron: '0 9 * * 1' # Monday 9am UTC
|
|
||||||
workflow_dispatch:
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
check-api:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
permissions:
|
|
||||||
contents: write
|
|
||||||
issues: write
|
|
||||||
pull-requests: write
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
|
|
||||||
- name: Download current API spec
|
|
||||||
run: curl -sSL -o /tmp/openapi-current.yaml https://docs.virtfusion.com/api/openapi.yaml
|
|
||||||
|
|
||||||
- name: Compare with baseline
|
|
||||||
id: diff
|
|
||||||
run: |
|
|
||||||
if [ ! -f docs/openapi-baseline.yaml ]; then
|
|
||||||
echo "No baseline found — creating initial baseline"
|
|
||||||
cp /tmp/openapi-current.yaml docs/openapi-baseline.yaml
|
|
||||||
echo "changed=initial" >> "$GITHUB_OUTPUT"
|
|
||||||
elif ! diff -q docs/openapi-baseline.yaml /tmp/openapi-current.yaml > /dev/null 2>&1; then
|
|
||||||
echo "API spec has changed"
|
|
||||||
diff docs/openapi-baseline.yaml /tmp/openapi-current.yaml > /tmp/api-diff.txt || true
|
|
||||||
echo "changed=true" >> "$GITHUB_OUTPUT"
|
|
||||||
else
|
|
||||||
echo "No changes detected"
|
|
||||||
echo "changed=false" >> "$GITHUB_OUTPUT"
|
|
||||||
fi
|
|
||||||
|
|
||||||
- name: Create issue on change
|
|
||||||
if: steps.diff.outputs.changed == 'true'
|
|
||||||
uses: actions/github-script@v7
|
|
||||||
with:
|
|
||||||
script: |
|
|
||||||
const fs = require('fs');
|
|
||||||
const diff = fs.readFileSync('/tmp/api-diff.txt', 'utf8').substring(0, 60000);
|
|
||||||
await github.rest.issues.create({
|
|
||||||
owner: context.repo.owner,
|
|
||||||
repo: context.repo.repo,
|
|
||||||
title: `VirtFusion API spec changed (${new Date().toISOString().split('T')[0]})`,
|
|
||||||
body: `The VirtFusion OpenAPI spec has been updated.\n\n<details><summary>Diff</summary>\n\n\`\`\`diff\n${diff}\n\`\`\`\n</details>\n\nReview the changes and update the module if needed.`,
|
|
||||||
labels: ['api-sync']
|
|
||||||
});
|
|
||||||
|
|
||||||
- name: Update baseline and create PR
|
|
||||||
if: steps.diff.outputs.changed == 'true' || steps.diff.outputs.changed == 'initial'
|
|
||||||
run: |
|
|
||||||
cp /tmp/openapi-current.yaml docs/openapi-baseline.yaml
|
|
||||||
git config user.name "github-actions[bot]"
|
|
||||||
git config user.email "github-actions[bot]@users.noreply.github.com"
|
|
||||||
BRANCH="api-sync/$(date +%Y-%m-%d)"
|
|
||||||
git checkout -b "$BRANCH"
|
|
||||||
git add docs/openapi-baseline.yaml
|
|
||||||
git commit -m "chore: update VirtFusion API baseline spec"
|
|
||||||
git push origin "$BRANCH"
|
|
||||||
gh pr create --title "chore: update VirtFusion API baseline" --body "Automated update of the VirtFusion OpenAPI baseline spec." --base main
|
|
||||||
env:
|
|
||||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
65
.github/workflows/publish-release.yml
vendored
65
.github/workflows/publish-release.yml
vendored
@@ -1,52 +1,43 @@
|
|||||||
# .github/workflows/semantic-versioning-release.yml
|
name: Publish Release
|
||||||
name: Automated Semantic Versioning Release
|
|
||||||
|
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
branches:
|
tags:
|
||||||
- main
|
- 'v*'
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
release:
|
release:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
permissions:
|
permissions:
|
||||||
contents: write # for creating tags and releases
|
contents: write
|
||||||
issues: write # for commenting on issues
|
|
||||||
pull-requests: write # for commenting on PRs
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout code
|
- name: Checkout code
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
with:
|
|
||||||
# This is required to analyze the full commit history
|
|
||||||
fetch-depth: 0
|
|
||||||
|
|
||||||
- name: Automated Semantic Release
|
- name: Extract tag name
|
||||||
# This action wraps the popular semantic-release tool
|
id: tag
|
||||||
uses: cycjimmy/semantic-release-action@v4
|
run: echo "version=${GITHUB_REF#refs/tags/}" >> "$GITHUB_OUTPUT"
|
||||||
with:
|
|
||||||
# You can specify the branches to release from
|
|
||||||
branch: main
|
|
||||||
extra_plugins: |
|
|
||||||
@semantic-release/changelog
|
|
||||||
@semantic-release/git
|
|
||||||
env:
|
|
||||||
# GITHUB_TOKEN is required for authentication
|
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
|
|
||||||
- name: Generate cache busting version hashes
|
- name: Generate release notes
|
||||||
|
id: notes
|
||||||
run: |
|
run: |
|
||||||
CSS_HASH=$(md5sum modules/servers/VirtFusionDirect/templates/css/module.css | cut -c1-8)
|
# Get previous tag
|
||||||
JS_HASH=$(md5sum modules/servers/VirtFusionDirect/templates/js/module.js | cut -c1-8)
|
PREV_TAG=$(git describe --tags --abbrev=0 HEAD^ 2>/dev/null || echo "")
|
||||||
echo "{\"css\":\"$CSS_HASH\",\"js\":\"$JS_HASH\"}" > modules/servers/VirtFusionDirect/templates/version.json
|
if [ -n "$PREV_TAG" ]; then
|
||||||
git config user.name "github-actions[bot]"
|
NOTES=$(git log --pretty=format:"- %s" "$PREV_TAG"..HEAD)
|
||||||
git config user.email "github-actions[bot]@users.noreply.github.com"
|
else
|
||||||
git add modules/servers/VirtFusionDirect/templates/version.json
|
NOTES=$(git log --pretty=format:"- %s")
|
||||||
git diff --cached --quiet || git commit -m "chore: update asset version hashes [skip ci]"
|
fi
|
||||||
git push || true
|
# Write to file for the release body
|
||||||
|
echo "$NOTES" > /tmp/release-notes.txt
|
||||||
|
|
||||||
# To make this work, you must follow the Conventional Commits specification.
|
- name: Create release
|
||||||
# Examples:
|
uses: softprops/action-gh-release@v2
|
||||||
# - fix: correct a typo in the documentation
|
with:
|
||||||
# - feat: add a new user authentication endpoint
|
tag_name: ${{ steps.tag.outputs.version }}
|
||||||
# - feat(api): add rate limiting
|
name: ${{ steps.tag.outputs.version }}
|
||||||
# BREAKING CHANGE: The API now returns 429 when rate limit is exceeded.
|
body_path: /tmp/release-notes.txt
|
||||||
|
draft: false
|
||||||
|
prerelease: false
|
||||||
|
env:
|
||||||
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
|||||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -1,2 +1,3 @@
|
|||||||
/.idea/
|
/.idea/
|
||||||
/.superpowers/
|
/.superpowers/
|
||||||
|
/vendor/
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
{
|
|
||||||
"branches": ["main"],
|
|
||||||
"plugins": [
|
|
||||||
"@semantic-release/commit-analyzer",
|
|
||||||
"@semantic-release/release-notes-generator",
|
|
||||||
["@semantic-release/changelog", { "changelogFile": "CHANGELOG.md" }],
|
|
||||||
"@semantic-release/github",
|
|
||||||
["@semantic-release/git", {
|
|
||||||
"assets": ["CHANGELOG.md"],
|
|
||||||
"message": "chore(release): ${nextRelease.version} [skip ci]\n\n${nextRelease.notes}"
|
|
||||||
}]
|
|
||||||
]
|
|
||||||
}
|
|
||||||
69
CHANGELOG.md
69
CHANGELOG.md
@@ -1,42 +1,39 @@
|
|||||||
# 1.0.0 (2026-03-19)
|
|
||||||
|
|
||||||
|
|
||||||
### Bug Fixes
|
|
||||||
|
|
||||||
* add null/false guards, proper error handling, and VNC popup fix ([49fdd9e](https://git.ezscale.cloud/EZSCALE/virtfusion-whmcs-module/commit/49fdd9e49ba87bfb4b72dd741e15f790c1050033))
|
|
||||||
* OS gallery accordion auto-collapses other sections when one opens ([a9565ff](https://git.ezscale.cloud/EZSCALE/virtfusion-whmcs-module/commit/a9565ff6f920ab480a9298c055b8f4581786f3a4))
|
|
||||||
* OS gallery accordion layout and remove broken remote icon fetching ([9cd737c](https://git.ezscale.cloud/EZSCALE/virtfusion-whmcs-module/commit/9cd737c5d5d26587bea8fa40bf75f5e25544ff18))
|
|
||||||
* TestConnection for unsaved servers, traffic display, and cache-busting ([e8d2eb0](https://git.ezscale.cloud/EZSCALE/virtfusion-whmcs-module/commit/e8d2eb0aa1f173f13bb0b8d7dfca0acebb821ac7))
|
|
||||||
* XSS escaping, null guards, JS bug fixes, and documentation updates ([6c7cdc6](https://git.ezscale.cloud/EZSCALE/virtfusion-whmcs-module/commit/6c7cdc6421678390746adcee4877a7ade8f2a061))
|
|
||||||
|
|
||||||
|
|
||||||
### Features
|
|
||||||
|
|
||||||
* add client-side SSH Ed25519 key generator on order page ([209e01d](https://git.ezscale.cloud/EZSCALE/virtfusion-whmcs-module/commit/209e01deb6832dce76a307410fbab28b1e420093))
|
|
||||||
* add VNC check, SSH key paste, resources panel, sliders, and self-service billing ([1e471af](https://git.ezscale.cloud/EZSCALE/virtfusion-whmcs-module/commit/1e471affd0ae9a68358afa5704523bce9bb413d0))
|
|
||||||
* major enhancement — OS gallery, server rename, traffic chart, backups, VNC toggle, password reset, Redis caching, UX improvements ([90a97c4](https://git.ezscale.cloud/EZSCALE/virtfusion-whmcs-module/commit/90a97c4afb61a179eda40e23b97637dd90507b55))
|
|
||||||
* streamline network panel, conditional self-service, remove IP add endpoints ([e73e85c](https://git.ezscale.cloud/EZSCALE/virtfusion-whmcs-module/commit/e73e85c5a9faa79b50e4949328c1d2a3cbc49ddf))
|
|
||||||
|
|
||||||
# 1.0.0 (2026-02-07)
|
|
||||||
|
|
||||||
|
|
||||||
### Bug Fixes
|
|
||||||
|
|
||||||
* add null/false guards, proper error handling, and VNC popup fix ([49fdd9e](https://github.com/EZSCALE/virtfusion-whmcs-module/commit/49fdd9e49ba87bfb4b72dd741e15f790c1050033))
|
|
||||||
* TestConnection for unsaved servers, traffic display, and cache-busting ([e8d2eb0](https://github.com/EZSCALE/virtfusion-whmcs-module/commit/e8d2eb0aa1f173f13bb0b8d7dfca0acebb821ac7))
|
|
||||||
* XSS escaping, null guards, JS bug fixes, and documentation updates ([6c7cdc6](https://github.com/EZSCALE/virtfusion-whmcs-module/commit/6c7cdc6421678390746adcee4877a7ade8f2a061))
|
|
||||||
|
|
||||||
|
|
||||||
### Features
|
|
||||||
|
|
||||||
* add client-side SSH Ed25519 key generator on order page ([209e01d](https://github.com/EZSCALE/virtfusion-whmcs-module/commit/209e01deb6832dce76a307410fbab28b1e420093))
|
|
||||||
* add VNC check, SSH key paste, resources panel, sliders, and self-service billing ([1e471af](https://github.com/EZSCALE/virtfusion-whmcs-module/commit/1e471affd0ae9a68358afa5704523bce9bb413d0))
|
|
||||||
* streamline network panel, conditional self-service, remove IP add endpoints ([e73e85c](https://github.com/EZSCALE/virtfusion-whmcs-module/commit/e73e85c5a9faa79b50e4949328c1d2a3cbc49ddf))
|
|
||||||
|
|
||||||
# Changelog
|
# Changelog
|
||||||
|
|
||||||
All notable changes to the VirtFusion Direct Provisioning Module for WHMCS.
|
All notable changes to the VirtFusion Direct Provisioning Module for WHMCS.
|
||||||
|
|
||||||
|
## [1.0.0] - 2026-03-19
|
||||||
|
|
||||||
|
### Features
|
||||||
|
- OS template tile gallery with accordion categories, brand icons, and search
|
||||||
|
- Inline server rename with friendly name generator
|
||||||
|
- Traffic statistics canvas chart in resources panel
|
||||||
|
- Backup listing timeline in manage panel
|
||||||
|
- VNC enable/disable toggle with connection details and password copy
|
||||||
|
- Server root password reset with auto-clipboard copy
|
||||||
|
- Redis-backed API response caching with filesystem fallback
|
||||||
|
- Skeleton loading, action cooldowns, progress indicators
|
||||||
|
- Copy-to-clipboard buttons for IP addresses
|
||||||
|
- Client-side SSH Ed25519 key generator on checkout page
|
||||||
|
- VNC console support, resources panel, self-service billing
|
||||||
|
- Configurable option sliders on checkout page
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
- XSS escaping, null guards, and proper error handling
|
||||||
|
- All state-mutating operations use POST instead of GET
|
||||||
|
- Explicit break after all output() calls in client.php
|
||||||
|
- Server-side regex validation on rename endpoint
|
||||||
|
- Error messages sanitized (no raw API errors exposed to clients)
|
||||||
|
|
||||||
|
### Removed
|
||||||
|
- Client IP removal capability (IPs managed by VirtFusion)
|
||||||
|
- IP add buttons (managed by VirtFusion during provisioning)
|
||||||
|
- Firewall panel (non-functional; managed in VirtFusion admin)
|
||||||
|
|
||||||
|
### Infrastructure
|
||||||
|
- Tag-based release workflow (compatible with Gitea and GitHub)
|
||||||
|
- Codebase consolidation: resolveServiceContext(), groupOsTemplates(), vfUrl(), vfShowAlert()
|
||||||
|
|
||||||
## [0.0.18] - 2025-10-01
|
## [0.0.18] - 2025-10-01
|
||||||
|
|
||||||
### Changed
|
### Changed
|
||||||
@@ -93,6 +90,6 @@ All notable changes to the VirtFusion Direct Provisioning Module for WHMCS.
|
|||||||
- Admin services tab with server ID management
|
- Admin services tab with server ID management
|
||||||
- Package change (upgrade/downgrade) support
|
- Package change (upgrade/downgrade) support
|
||||||
- Configurable option mapping for dynamic resource allocation
|
- Configurable option mapping for dynamic resource allocation
|
||||||
- GitHub Actions CI/CD with semantic-release
|
- GitHub Actions CI/CD
|
||||||
- Security policy (SECURITY.md)
|
- Security policy (SECURITY.md)
|
||||||
- License (GPL v3)
|
- License (GPL v3)
|
||||||
|
|||||||
51
CLAUDE.md
51
CLAUDE.md
@@ -15,12 +15,27 @@ There is no automated test suite, linter, or build step. Testing is manual:
|
|||||||
- **Module logging:** WHMCS Admin → Utilities → Logs → Module Log captures all API calls and responses
|
- **Module logging:** WHMCS Admin → Utilities → Logs → Module Log captures all API calls and responses
|
||||||
- **Server object viewer:** Admin services tab shows full JSON response from VirtFusion API
|
- **Server object viewer:** Admin services tab shows full JSON response from VirtFusion API
|
||||||
|
|
||||||
|
## Development Rules
|
||||||
|
|
||||||
|
- **Error handling:** Always use try...catch blocks around API calls, database operations, and any code that may throw exceptions. Never let exceptions bubble up unhandled to the user. Log caught exceptions via `Log::insert()`.
|
||||||
|
- **Ownership validation:** Every client-facing action MUST verify service ownership via `validateUserOwnsService()` before performing any operation. Server IDs must be cross-referenced against the authenticated client to prevent cross-customer data access.
|
||||||
|
- **Security:** All input must be validated server-side. Never trust client-side validation alone. Cast IDs to `(int)`, validate strings with regex, escape output with `htmlspecialchars()`.
|
||||||
|
- **Control flow:** Every `$vf->output()` call in switch cases must be followed by `break`. Do not rely on `exit()` inside `output()` for flow control.
|
||||||
|
- **HTTP methods:** Read-only operations use GET. State-mutating operations (power, rebuild, rename, password reset, credit, VNC toggle) use POST with data in the request body.
|
||||||
|
- **Caching:** Use the `Cache` class for slow-changing API responses. Never cache real-time data (server status, VNC sessions, login tokens) or mutation responses.
|
||||||
|
|
||||||
## Release Process
|
## Release Process
|
||||||
|
|
||||||
Releases are automated via GitHub Actions using semantic-release on pushes to `main`. Use **conventional commits**:
|
Releases are triggered by pushing a git tag:
|
||||||
- `fix:` → patch release
|
```bash
|
||||||
- `feat:` → minor release
|
git tag v1.1.0
|
||||||
- `BREAKING CHANGE:` in commit body → major release
|
git push origin v1.1.0
|
||||||
|
```
|
||||||
|
|
||||||
|
The `publish-release.yml` workflow creates a GitHub/Gitea release with auto-generated notes from the commit log. Use **conventional commits** for clear changelogs:
|
||||||
|
- `fix:` → patch-level change
|
||||||
|
- `feat:` → feature addition
|
||||||
|
- `refactor:` → code improvement without behavior change
|
||||||
|
|
||||||
## Architecture
|
## Architecture
|
||||||
|
|
||||||
@@ -31,38 +46,39 @@ Releases are automated via GitHub Actions using semantic-release on pushes to `m
|
|||||||
| File | Purpose |
|
| File | Purpose |
|
||||||
|------|---------|
|
|------|---------|
|
||||||
| `VirtFusionDirect.php` | WHMCS module interface — non-namespaced functions (`VirtFusionDirect_CreateAccount()`, etc.) that delegate to library classes |
|
| `VirtFusionDirect.php` | WHMCS module interface — non-namespaced functions (`VirtFusionDirect_CreateAccount()`, etc.) that delegate to library classes |
|
||||||
| `client.php` | Client-facing AJAX API — authenticated by WHMCS session + service ownership validation |
|
| `client.php` | Client-facing AJAX API — authenticated by WHMCS session + service ownership validation. POST for mutations, GET for reads. |
|
||||||
| `admin.php` | Admin-facing AJAX API — requires WHMCS admin authentication |
|
| `admin.php` | Admin-facing AJAX API — requires WHMCS admin authentication |
|
||||||
| `hooks.php` | WHMCS hooks — checkout validation (OS selection), dynamic dropdown/slider injection, SSH key paste |
|
| `hooks.php` | WHMCS hooks — checkout validation (OS selection), OS gallery + SSH key UI injection, slider UI for configurable options |
|
||||||
|
|
||||||
### Core Classes (in `lib/`)
|
### Core Classes (in `lib/`)
|
||||||
|
|
||||||
| Class | Role |
|
| Class | Role |
|
||||||
|-------|------|
|
|-------|------|
|
||||||
| `Module` | Base class with API integration, auth checks, power/network/VNC/backup/resource/self-service methods. All client/admin actions route through here. |
|
| `Module` | Base class with API integration, auth checks, and all feature methods (power, network, VNC, backup, resource, self-service, traffic, rename, password reset). Contains `resolveServiceContext()` for DRY service lookups and `groupOsTemplates()` for shared OS category logic. |
|
||||||
| `ModuleFunctions` | Extends `Module`. Service lifecycle: create, suspend, unsuspend, terminate, change package, usage updates, client area rendering. |
|
| `ModuleFunctions` | Extends `Module`. Service lifecycle: create, suspend, unsuspend, terminate, change package, usage updates, client area rendering. |
|
||||||
| `ConfigureService` | Extends `Module`. Order-time operations: package discovery, OS template fetching, server build initialization, SSH key retrieval and creation. |
|
| `ConfigureService` | Extends `Module`. Order-time operations: package discovery, OS template fetching, server build initialization, SSH key retrieval and creation. |
|
||||||
| `Database` | Static methods for `mod_virtfusion_direct` table operations and WHMCS DB queries. Auto-creates/migrates schema on first use. |
|
| `Database` | Static methods for `mod_virtfusion_direct` table operations and WHMCS DB queries. Auto-creates/migrates schema on first use. |
|
||||||
| `Curl` | HTTP client wrapper with Bearer token auth, SSL verification, 30s timeout. Methods: `get`, `post`, `put`, `patch`, `delete`. |
|
| `Curl` | HTTP client wrapper with Bearer token auth, SSL verification, 30s timeout. Methods: `get`, `post`, `put`, `patch`, `delete`. Single-use — each instance makes one request. |
|
||||||
|
| `Cache` | Two-tier caching: Redis (if `ext-redis` available) with atomic filesystem fallback. TTLs: OS templates 10min, traffic/backups 2min, packages 10min. |
|
||||||
| `ServerResource` | Transforms VirtFusion API response into flat key-value format for Smarty templates. |
|
| `ServerResource` | Transforms VirtFusion API response into flat key-value format for Smarty templates. |
|
||||||
| `AdminHTML` | Static methods generating admin services tab HTML (server ID editor, JSON viewer, action buttons). |
|
| `AdminHTML` | Static methods generating admin services tab HTML (server ID editor, JSON viewer, action buttons). |
|
||||||
| `Log` | Thin wrapper around WHMCS module logging. |
|
| `Log` | Thin wrapper around WHMCS module logging. |
|
||||||
|
|
||||||
### Class Hierarchy
|
### Class Hierarchy
|
||||||
|
|
||||||
`ModuleFunctions` and `ConfigureService` both extend `Module`. Most business logic lives in `Module` — it handles API calls, auth, validation, and all feature-specific operations (power, network, VNC, backup, resource modification). `ModuleFunctions` orchestrates the WHMCS service lifecycle (provisioning flow, suspension, termination).
|
`ModuleFunctions` and `ConfigureService` both extend `Module`. Most business logic lives in `Module` — it handles API calls, auth, validation, and all feature-specific operations. The `resolveServiceContext()` method provides a standardized way to look up service → WHMCS service → control panel → curl client in a single call, eliminating boilerplate across all API methods.
|
||||||
|
|
||||||
### Client-Side
|
### Client-Side
|
||||||
|
|
||||||
- **`templates/overview.tpl`** — Smarty template for client area (server info, power, network, rebuild, resources, VNC, self-service billing, billing overview)
|
- **`templates/overview.tpl`** — Smarty template for client area (server info, power, network, rebuild with OS gallery, resources with traffic chart, VNC toggle, self-service billing, billing overview, backups timeline, server rename, password reset)
|
||||||
- **`templates/js/module.js`** — Vanilla JS (1000+ lines) handling AJAX calls to `client.php`, DOM updates, status badges, power actions, all management UIs
|
- **`templates/js/module.js`** — Vanilla JS + jQuery handling AJAX calls, DOM updates, status badges, power actions, all management UIs. Key helpers: `vfUrl()` (URL builder), `vfShowAlert()` (alert display), `vfRenderOsGallery()` (accordion gallery), `vfDrawTrafficChart()` (canvas chart)
|
||||||
- **`templates/js/keygen.js`** — Client-side SSH Ed25519 key generator using Web Crypto API (loaded on checkout page)
|
- **`templates/js/keygen.js`** — Client-side SSH Ed25519 key generator using Web Crypto API (loaded on checkout page)
|
||||||
- **`templates/css/module.css`** — Cross-theme styles with Bootstrap 3/4/5 dual class support (`panel card`, `panel-body card-body`)
|
- **`templates/css/module.css`** — Cross-theme styles with Bootstrap 3/4/5 dual class support (`panel card`, `panel-body card-body`)
|
||||||
|
|
||||||
### Removed Features
|
### Removed Features
|
||||||
|
|
||||||
- **Firewall** — Removed (non-functional; rulesets must be created in VirtFusion admin panel)
|
- **Firewall** — Removed (non-functional; rulesets must be created in VirtFusion admin panel)
|
||||||
- **IP add buttons** — Removed (`addIPv4`, `addIPv6` endpoints and UI); IPs are managed by VirtFusion during provisioning
|
- **IP add/remove buttons** — Removed; IPs are managed by VirtFusion during provisioning
|
||||||
- **Upgrade/Downgrade link** — Removed from resources panel
|
- **Upgrade/Downgrade link** — Removed from resources panel
|
||||||
|
|
||||||
### Data Flow: Server Creation
|
### Data Flow: Server Creation
|
||||||
@@ -75,18 +91,21 @@ Releases are automated via GitHub Actions using semantic-release on pushes to `m
|
|||||||
6. Updates WHMCS hosting record (IP, username, password, domain)
|
6. Updates WHMCS hosting record (IP, username, password, domain)
|
||||||
7. Calls `ConfigureService::initServerBuild()` with selected OS + SSH key
|
7. Calls `ConfigureService::initServerBuild()` with selected OS + SSH key
|
||||||
|
|
||||||
|
Custom fields (`Initial Operating System`, `Initial SSH Key`) are auto-created by `Database::ensureCustomFields()` on module load for all products using this module. No manual SQL setup required.
|
||||||
|
|
||||||
### Configurable Option Mapping
|
### Configurable Option Mapping
|
||||||
|
|
||||||
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`.
|
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`.
|
||||||
|
|
||||||
## Security Patterns
|
## Security Patterns
|
||||||
|
|
||||||
- All PHP files start with `if (!defined("WHMCS")) die()` to prevent direct access
|
- All PHP files start with `if (!defined("WHMCS")) die()` to prevent direct access (except entry points using `init.php`)
|
||||||
- Client endpoints validate WHMCS session AND service ownership before any operation
|
- Client endpoints validate WHMCS session AND service ownership before any operation
|
||||||
- API tokens stored encrypted in WHMCS server password field (decrypted via `localAPI('DecryptPassword')`)
|
- API tokens stored encrypted in WHMCS server password field (decrypted via `localAPI('DecryptPassword')`)
|
||||||
- Input validation: type casting, regex filtering, `filter_var()` for IP addresses
|
- Input validation: type casting (`(int)`), regex filtering, `filter_var()` for IP addresses
|
||||||
- Output escaping: `htmlspecialchars()` in Smarty, `encodeURIComponent()` / `.text()` in JS
|
- Output escaping: `htmlspecialchars()` in PHP, `$('<span>').text()` in jQuery, `{escape:'htmlall'}` in Smarty
|
||||||
- SSL verification enabled on all API calls (`CURLOPT_SSL_VERIFYPEER` + `CURLOPT_SSL_VERIFYHOST = 2`)
|
- SSL verification enabled on all API calls (`CURLOPT_SSL_VERIFYPEER` + `CURLOPT_SSL_VERIFYHOST = 2`)
|
||||||
|
- Server rename validated both client-side and server-side with RFC 1123 regex
|
||||||
|
|
||||||
## VirtFusion API Compatibility
|
## VirtFusion API Compatibility
|
||||||
|
|
||||||
@@ -95,6 +114,7 @@ Custom option names can be mapped in `config/ConfigOptionMapping.php` (copy from
|
|||||||
- **VNC console:** v6.1.0+
|
- **VNC console:** v6.1.0+
|
||||||
- **Resource modification:** v6.2.0+
|
- **Resource modification:** v6.2.0+
|
||||||
- **Self-service billing:** Requires self-service feature enabled in VirtFusion
|
- **Self-service billing:** Requires self-service feature enabled in VirtFusion
|
||||||
|
- **OS icon path:** `{baseUrl}/img/logo/{icon_filename}` (public, no auth required)
|
||||||
|
|
||||||
## Product Config Options
|
## Product Config Options
|
||||||
|
|
||||||
@@ -111,4 +131,5 @@ Custom option names can be mapped in `config/ConfigOptionMapping.php` (copy from
|
|||||||
|
|
||||||
- WHMCS 8.x+ (tested 8.0–8.10)
|
- WHMCS 8.x+ (tested 8.0–8.10)
|
||||||
- PHP 8.0+ with cURL extension
|
- PHP 8.0+ with cURL extension
|
||||||
|
- Redis extension optional (improves caching performance, falls back to filesystem)
|
||||||
- All WHMCS themes supported (Six, Twenty-One, Lagom, custom) via Bootstrap 3/4/5 dual classes
|
- All WHMCS themes supported (Six, Twenty-One, Lagom, custom) via Bootstrap 3/4/5 dual classes
|
||||||
|
|||||||
123
README.md
123
README.md
@@ -62,7 +62,7 @@ You also need a VirtFusion API token with the following permissions:
|
|||||||
- **Control Panel SSO** - One-click login to VirtFusion panel
|
- **Control Panel SSO** - One-click login to VirtFusion panel
|
||||||
- **Server Rebuild** - Reinstall with any available OS template
|
- **Server Rebuild** - Reinstall with any available OS template
|
||||||
- **Password Reset** - Reset VirtFusion panel login credentials
|
- **Password Reset** - Reset VirtFusion panel login credentials
|
||||||
- **Network Management** - View and remove IPv4 addresses; view IPv6 subnets
|
- **Network Management** - View IPv4 addresses and IPv6 subnets with copy-to-clipboard
|
||||||
- **Resources Panel** - Current memory, CPU, storage, traffic allocation with usage bars
|
- **Resources Panel** - Current memory, CPU, storage, traffic allocation with usage bars
|
||||||
- **VNC Console** - Browser-based console access (panel auto-hides when VNC is disabled on the server)
|
- **VNC Console** - Browser-based console access (panel auto-hides when VNC is disabled on the server)
|
||||||
- **Self-Service Billing** - Credit balance display, usage breakdown, and credit top-up (when enabled)
|
- **Self-Service Billing** - Credit balance display, usage breakdown, and credit top-up (when enabled)
|
||||||
@@ -79,7 +79,7 @@ You also need a VirtFusion API token with the following permissions:
|
|||||||
- **Update Server Object** - Refresh cached server data from VirtFusion
|
- **Update Server Object** - Refresh cached server data from VirtFusion
|
||||||
|
|
||||||
### Ordering Process
|
### Ordering Process
|
||||||
- Dynamic OS template dropdown populated from VirtFusion API
|
- OS template tile gallery with accordion categories, search, and brand icons
|
||||||
- SSH key selection dropdown for users with saved keys, with option to paste a new public key
|
- SSH key selection dropdown for users with saved keys, with option to paste a new public key
|
||||||
- **SSH Ed25519 key generator** — Client-side keypair generation using Web Crypto API
|
- **SSH Ed25519 key generator** — Client-side keypair generation using Web Crypto API
|
||||||
- Checkout validation ensuring OS selection before order placement
|
- Checkout validation ensuring OS selection before order placement
|
||||||
@@ -108,95 +108,28 @@ You also need a VirtFusion API token with the following permissions:
|
|||||||
|
|
||||||
## Installation
|
## Installation
|
||||||
|
|
||||||
### Step 1: Download & Install
|
|
||||||
|
|
||||||
Download the latest release from the [releases](https://github.com/EZSCALE/virtfusion-whmcs-module/releases) page, or install directly via the command line:
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
cd /tmp
|
git clone https://github.com/EZSCALE/virtfusion-whmcs-module.git /tmp/vf && rsync -ahP --delete /tmp/vf/modules/servers/VirtFusionDirect/ /path/to/whmcs/modules/servers/VirtFusionDirect/ && rm -rf /tmp/vf
|
||||||
git clone https://github.com/EZSCALE/virtfusion-whmcs-module.git
|
|
||||||
rsync -ahP --delete /tmp/virtfusion-whmcs-module/modules/servers/VirtFusionDirect/ /path/to/whmcs/modules/servers/VirtFusionDirect/
|
|
||||||
rm -rf /tmp/virtfusion-whmcs-module
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Replace `/path/to/whmcs` with your actual WHMCS installation root.
|
Replace `/path/to/whmcs` with your actual WHMCS installation root. The database table, schema migrations, and custom fields are all created automatically on first load.
|
||||||
|
|
||||||
The resulting file structure should be:
|
Then configure in WHMCS Admin:
|
||||||
|
|
||||||
```
|
1. **Add Server** — Configuration > System Settings > Servers > Add New Server. Set hostname to your VirtFusion panel (e.g. `cp.example.com`), type to "VirtFusion Direct Provisioning", and paste your API token in the Password field. Click **Test Connection** to verify.
|
||||||
modules/servers/VirtFusionDirect/
|
2. **Create Product** — Configuration > System Settings > Products/Services. On the Module Settings tab, select "VirtFusion Direct Provisioning", choose your server, and set the Hypervisor Group ID, Package ID, and Default IPv4 count.
|
||||||
VirtFusionDirect.php # Main module file
|
|
||||||
client.php # Client AJAX API
|
|
||||||
admin.php # Admin AJAX API
|
|
||||||
hooks.php # WHMCS hooks
|
|
||||||
modify.sql # Custom field setup SQL
|
|
||||||
lib/
|
|
||||||
Module.php # Core module class
|
|
||||||
ModuleFunctions.php # Provisioning functions
|
|
||||||
ConfigureService.php # OS/SSH config service
|
|
||||||
Database.php # Database operations
|
|
||||||
Curl.php # HTTP client
|
|
||||||
ServerResource.php # Data transformer
|
|
||||||
AdminHTML.php # Admin interface HTML
|
|
||||||
Log.php # Logging
|
|
||||||
templates/
|
|
||||||
overview.tpl # Client area template
|
|
||||||
error.tpl # Error template
|
|
||||||
css/module.css # Styles
|
|
||||||
js/module.js # Client JavaScript
|
|
||||||
js/keygen.js # SSH Ed25519 key generator
|
|
||||||
config/
|
|
||||||
ConfigOptionMapping-example.php # Config mapping example
|
|
||||||
```
|
|
||||||
|
|
||||||
### Step 2: Set Up Server in WHMCS
|
That's it. Hooks activate automatically and custom fields are created on module load.
|
||||||
|
|
||||||
1. Go to **Configuration > System Settings > Servers**
|
|
||||||
2. Click **Add New Server**
|
|
||||||
3. Fill in:
|
|
||||||
- **Name**: Anything descriptive (e.g., "VirtFusion Production")
|
|
||||||
- **Hostname**: Your VirtFusion panel hostname (e.g., `cp.example.com`)
|
|
||||||
- **Type**: VirtFusion Direct Provisioning
|
|
||||||
- **Password/Access Hash**: Your VirtFusion API token
|
|
||||||
4. Click **Test Connection** to verify
|
|
||||||
5. Click **Save Changes**
|
|
||||||
|
|
||||||
### Step 3: Create Product
|
|
||||||
|
|
||||||
1. Go to **Configuration > System Settings > Products/Services**
|
|
||||||
2. Create a new product or edit an existing one
|
|
||||||
3. On the **Module Settings** tab:
|
|
||||||
- Set **Module Name** to "VirtFusion Direct Provisioning"
|
|
||||||
- Select your VirtFusion server
|
|
||||||
- Set **Hypervisor Group ID**, **Package ID**, and **Default IPv4** count
|
|
||||||
4. Save the product
|
|
||||||
|
|
||||||
### Step 4: Set Up Custom Fields
|
|
||||||
|
|
||||||
See [Custom Fields](#custom-fields) section below.
|
|
||||||
|
|
||||||
### Step 5: Activate Hooks
|
|
||||||
|
|
||||||
The hooks file (`hooks.php`) is automatically detected by WHMCS when the module is active. If you add the module files to an existing installation, you may need to re-save the product settings or clear the WHMCS template cache for hooks to take effect.
|
|
||||||
|
|
||||||
## Upgrading
|
## Upgrading
|
||||||
|
|
||||||
1. Back up your existing `modules/servers/VirtFusionDirect/` directory
|
|
||||||
2. Back up `config/ConfigOptionMapping.php` if you have a custom mapping
|
|
||||||
3. Download and deploy the new version:
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
cd /tmp
|
git clone https://github.com/EZSCALE/virtfusion-whmcs-module.git /tmp/vf && rsync -ahP --delete /tmp/vf/modules/servers/VirtFusionDirect/ /path/to/whmcs/modules/servers/VirtFusionDirect/ && rm -rf /tmp/vf
|
||||||
git clone https://github.com/EZSCALE/virtfusion-whmcs-module.git
|
|
||||||
rsync -ahP --delete /tmp/virtfusion-whmcs-module/modules/servers/VirtFusionDirect/ /path/to/whmcs/modules/servers/VirtFusionDirect/
|
|
||||||
rm -rf /tmp/virtfusion-whmcs-module
|
|
||||||
```
|
```
|
||||||
|
|
||||||
4. Restore your custom `config/ConfigOptionMapping.php` if applicable
|
> **Note:** If you have a custom `config/ConfigOptionMapping.php`, back it up first — `--delete` will remove it. Restore it after upgrading.
|
||||||
5. If you have theme-overridden templates, review them for any new template variables
|
|
||||||
6. Clear the WHMCS template cache: **Configuration > System Settings > General Settings > clear template cache**
|
|
||||||
|
|
||||||
The module database table (`mod_virtfusion_direct`) is automatically migrated on first load.
|
If you use theme-overridden templates, review them for any new template variables. Clear the WHMCS template cache after upgrading: **Configuration > System Settings > General Settings > clear template cache**.
|
||||||
|
|
||||||
## Configuration
|
## Configuration
|
||||||
|
|
||||||
@@ -222,20 +155,9 @@ Each WHMCS product using this module needs:
|
|||||||
|
|
||||||
### Custom Fields
|
### Custom Fields
|
||||||
|
|
||||||
You **must** create two custom fields on each product that uses this module:
|
The module requires two custom fields per product: **Initial Operating System** and **Initial SSH Key**. These are **automatically created** when the module loads — no manual setup required.
|
||||||
|
|
||||||
| Field Name | Field Type | Show on Order Form | Admin Only | Required |
|
The fields are hidden text boxes that are dynamically replaced by dropdown selects via JavaScript hooks on the order form. They are created for every product with the module type set to "VirtFusion Direct Provisioning".
|
||||||
|---|---|---|---|---|
|
|
||||||
| Initial Operating System | Text Box | Yes | No | No |
|
|
||||||
| Initial SSH Key | Text Box | Yes | No | No |
|
|
||||||
|
|
||||||
These fields are hidden text boxes that are dynamically replaced by dropdown selects via JavaScript hooks on the order form.
|
|
||||||
|
|
||||||
**Automated setup**: Run the SQL from [modify.sql](modify.sql) to auto-create these fields for all VirtFusion products:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
mysql -u whmcs_user -p whmcs_database < modules/servers/VirtFusionDirect/modify.sql
|
|
||||||
```
|
|
||||||
|
|
||||||
### Module Configuration Options
|
### Module Configuration Options
|
||||||
|
|
||||||
@@ -305,7 +227,7 @@ Four power control buttons:
|
|||||||
|
|
||||||
### Network Management
|
### Network Management
|
||||||
- View all IPv4 addresses and IPv6 subnets assigned to the server
|
- View all IPv4 addresses and IPv6 subnets assigned to the server
|
||||||
- Remove secondary IPv4 addresses (primary cannot be removed)
|
- Copy IP addresses to clipboard with one click
|
||||||
|
|
||||||
### VNC Console
|
### VNC Console
|
||||||
- Opens a browser-based VNC console to the server
|
- Opens a browser-based VNC console to the server
|
||||||
@@ -407,12 +329,6 @@ WHMCS automatically loads theme-specific templates when they exist. Copy the ori
|
|||||||
| `GET` | `/media/templates/fromServerPackageSpec/{id}` | OS templates |
|
| `GET` | `/media/templates/fromServerPackageSpec/{id}` | OS templates |
|
||||||
| `GET` | `/ssh_keys/user/{id}` | SSH key listing |
|
| `GET` | `/ssh_keys/user/{id}` | SSH key listing |
|
||||||
|
|
||||||
### Network
|
|
||||||
|
|
||||||
| Method | Endpoint | Purpose |
|
|
||||||
|---|---|---|
|
|
||||||
| `DELETE` | `/servers/{id}/ipv4` | Remove IPv4 address |
|
|
||||||
|
|
||||||
### SSH Keys
|
### SSH Keys
|
||||||
|
|
||||||
| Method | Endpoint | Purpose |
|
| Method | Endpoint | Purpose |
|
||||||
@@ -426,7 +342,10 @@ WHMCS automatically loads theme-specific templates when they exist. Copy the ori
|
|||||||
| `GET` | `/selfService/usage/byUserExtRelationId/{id}` | Usage data by WHMCS client ID |
|
| `GET` | `/selfService/usage/byUserExtRelationId/{id}` | Usage data by WHMCS client ID |
|
||||||
| `GET` | `/selfService/report/byUserExtRelationId/{id}` | Billing report by WHMCS client ID |
|
| `GET` | `/selfService/report/byUserExtRelationId/{id}` | Billing report by WHMCS client ID |
|
||||||
| `POST` | `/selfService/credit/byUserExtRelationId/{id}` | Add credit by WHMCS client ID |
|
| `POST` | `/selfService/credit/byUserExtRelationId/{id}` | Add credit by WHMCS client ID |
|
||||||
| `GET` | `/selfService/currencies` | Available self-service currencies |
|
| `GET` | `/servers/{id}/traffic` | Traffic statistics |
|
||||||
|
| `GET` | `/backups/server/{id}` | Backup listing |
|
||||||
|
| `POST` | `/servers/{id}/vnc` | Toggle VNC on/off |
|
||||||
|
| `POST` | `/servers/{id}/resetPassword` | Reset server root password |
|
||||||
|
|
||||||
### Advanced
|
### Advanced
|
||||||
|
|
||||||
@@ -533,9 +452,7 @@ This data appears in the WHMCS client area and admin product details.
|
|||||||
|
|
||||||
7. **Concurrent API Calls** - The module makes individual API calls for each feature panel on the client area page. If the VirtFusion API is slow, the page may take longer to fully load. All panels load asynchronously to minimize perceived delay.
|
7. **Concurrent API Calls** - The module makes individual API calls for each feature panel on the client area page. If the VirtFusion API is slow, the page may take longer to fully load. All panels load asynchronously to minimize perceived delay.
|
||||||
|
|
||||||
8. **Primary IPv4 Protection** - The first IPv4 address cannot be removed through the client area interface. This is by design to prevent users from accidentally removing their primary IP address.
|
8. **Self-Signed SSL Certificates** - SSL verification is enforced by default. VirtFusion panels using self-signed certificates will cause connection failures. Use a valid SSL certificate (e.g., Let's Encrypt) on your VirtFusion panel.
|
||||||
|
|
||||||
9. **Self-Signed SSL Certificates** - SSL verification is enforced by default. VirtFusion panels using self-signed certificates will cause connection failures. Use a valid SSL certificate (e.g., Let's Encrypt) on your VirtFusion panel.
|
|
||||||
|
|
||||||
## Security
|
## Security
|
||||||
|
|
||||||
@@ -564,12 +481,12 @@ modules/servers/VirtFusionDirect/
|
|||||||
client.php # Client-facing AJAX API (authenticated, ownership-validated)
|
client.php # Client-facing AJAX API (authenticated, ownership-validated)
|
||||||
admin.php # Admin-facing AJAX API (admin authentication required)
|
admin.php # Admin-facing AJAX API (admin authentication required)
|
||||||
hooks.php # WHMCS hooks (order form OS/SSH dropdowns, checkout validation)
|
hooks.php # WHMCS hooks (order form OS/SSH dropdowns, checkout validation)
|
||||||
modify.sql # SQL for creating custom fields
|
|
||||||
lib/
|
lib/
|
||||||
Module.php # Base class: API communication, power, network, VNC, rebuild
|
Module.php # Base class: API communication, power, network, VNC, rebuild
|
||||||
ModuleFunctions.php # Provisioning: create, suspend, unsuspend, terminate, change package
|
ModuleFunctions.php # Provisioning: create, suspend, unsuspend, terminate, change package
|
||||||
ConfigureService.php # Order configuration: OS templates, SSH keys, server build init
|
ConfigureService.php # Order configuration: OS templates, SSH keys, server build init
|
||||||
Database.php # Database operations: custom table, WHMCS table queries
|
Database.php # Database operations: custom table, WHMCS table queries
|
||||||
|
Cache.php # Two-tier cache: Redis with filesystem fallback
|
||||||
Curl.php # HTTP client: GET, POST, PUT, PATCH, DELETE with SSL verification
|
Curl.php # HTTP client: GET, POST, PUT, PATCH, DELETE with SSL verification
|
||||||
ServerResource.php # Data transformer: VirtFusion API response -> display format
|
ServerResource.php # Data transformer: VirtFusion API response -> display format
|
||||||
AdminHTML.php # Admin interface: HTML generation for admin services tab
|
AdminHTML.php # Admin interface: HTML generation for admin services tab
|
||||||
|
|||||||
19
composer.json
Normal file
19
composer.json
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
{
|
||||||
|
"name": "ezscale/virtfusion-whmcs-module",
|
||||||
|
"description": "VirtFusion Direct Provisioning Module for WHMCS",
|
||||||
|
"type": "whmcs-module",
|
||||||
|
"license": "GPL-3.0-or-later",
|
||||||
|
"require-dev": {
|
||||||
|
"laravel/pint": "^1.0"
|
||||||
|
},
|
||||||
|
"scripts": {
|
||||||
|
"post-install-cmd": [
|
||||||
|
"cp hooks/pre-commit .git/hooks/pre-commit && chmod +x .git/hooks/pre-commit"
|
||||||
|
],
|
||||||
|
"post-update-cmd": [
|
||||||
|
"cp hooks/pre-commit .git/hooks/pre-commit && chmod +x .git/hooks/pre-commit"
|
||||||
|
],
|
||||||
|
"lint": "pint",
|
||||||
|
"lint-test": "pint --test"
|
||||||
|
}
|
||||||
|
}
|
||||||
87
composer.lock
generated
Normal file
87
composer.lock
generated
Normal file
@@ -0,0 +1,87 @@
|
|||||||
|
{
|
||||||
|
"_readme": [
|
||||||
|
"This file locks the dependencies of your project to a known state",
|
||||||
|
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
|
||||||
|
"This file is @generated automatically"
|
||||||
|
],
|
||||||
|
"content-hash": "f6be98eb2bded4b127a92bc0f1e19d93",
|
||||||
|
"packages": [],
|
||||||
|
"packages-dev": [
|
||||||
|
{
|
||||||
|
"name": "laravel/pint",
|
||||||
|
"version": "v1.29.0",
|
||||||
|
"source": {
|
||||||
|
"type": "git",
|
||||||
|
"url": "https://github.com/laravel/pint.git",
|
||||||
|
"reference": "bdec963f53172c5e36330f3a400604c69bf02d39"
|
||||||
|
},
|
||||||
|
"dist": {
|
||||||
|
"type": "zip",
|
||||||
|
"url": "https://api.github.com/repos/laravel/pint/zipball/bdec963f53172c5e36330f3a400604c69bf02d39",
|
||||||
|
"reference": "bdec963f53172c5e36330f3a400604c69bf02d39",
|
||||||
|
"shasum": ""
|
||||||
|
},
|
||||||
|
"require": {
|
||||||
|
"ext-json": "*",
|
||||||
|
"ext-mbstring": "*",
|
||||||
|
"ext-tokenizer": "*",
|
||||||
|
"ext-xml": "*",
|
||||||
|
"php": "^8.2.0"
|
||||||
|
},
|
||||||
|
"require-dev": {
|
||||||
|
"friendsofphp/php-cs-fixer": "^3.94.2",
|
||||||
|
"illuminate/view": "^12.54.1",
|
||||||
|
"larastan/larastan": "^3.9.3",
|
||||||
|
"laravel-zero/framework": "^12.0.5",
|
||||||
|
"mockery/mockery": "^1.6.12",
|
||||||
|
"nunomaduro/termwind": "^2.4.0",
|
||||||
|
"pestphp/pest": "^3.8.6",
|
||||||
|
"shipfastlabs/agent-detector": "^1.1.0"
|
||||||
|
},
|
||||||
|
"bin": [
|
||||||
|
"builds/pint"
|
||||||
|
],
|
||||||
|
"type": "project",
|
||||||
|
"autoload": {
|
||||||
|
"psr-4": {
|
||||||
|
"App\\": "app/",
|
||||||
|
"Database\\Seeders\\": "database/seeders/",
|
||||||
|
"Database\\Factories\\": "database/factories/"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"notification-url": "https://packagist.org/downloads/",
|
||||||
|
"license": [
|
||||||
|
"MIT"
|
||||||
|
],
|
||||||
|
"authors": [
|
||||||
|
{
|
||||||
|
"name": "Nuno Maduro",
|
||||||
|
"email": "enunomaduro@gmail.com"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "An opinionated code formatter for PHP.",
|
||||||
|
"homepage": "https://laravel.com",
|
||||||
|
"keywords": [
|
||||||
|
"dev",
|
||||||
|
"format",
|
||||||
|
"formatter",
|
||||||
|
"lint",
|
||||||
|
"linter",
|
||||||
|
"php"
|
||||||
|
],
|
||||||
|
"support": {
|
||||||
|
"issues": "https://github.com/laravel/pint/issues",
|
||||||
|
"source": "https://github.com/laravel/pint"
|
||||||
|
},
|
||||||
|
"time": "2026-03-12T15:51:39+00:00"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"aliases": [],
|
||||||
|
"minimum-stability": "stable",
|
||||||
|
"stability-flags": {},
|
||||||
|
"prefer-stable": false,
|
||||||
|
"prefer-lowest": false,
|
||||||
|
"platform": {},
|
||||||
|
"platform-dev": {},
|
||||||
|
"plugin-api-version": "2.9.0"
|
||||||
|
}
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
# VirtFusion OpenAPI Baseline
|
|
||||||
# This file will be auto-populated by the api-sync-check workflow
|
|
||||||
# on first run. Do not edit manually.
|
|
||||||
openapi: "3.0.0"
|
|
||||||
info:
|
|
||||||
title: VirtFusion API Baseline Placeholder
|
|
||||||
version: "0.0.0"
|
|
||||||
26
hooks/pre-commit
Executable file
26
hooks/pre-commit
Executable file
@@ -0,0 +1,26 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
# Run Pint on staged PHP files before committing.
|
||||||
|
# Fixes formatting in-place and re-stages the corrected files.
|
||||||
|
|
||||||
|
STAGED_PHP=$(git diff --cached --name-only --diff-filter=ACM | grep '\.php$')
|
||||||
|
|
||||||
|
if [ -z "$STAGED_PHP" ]; then
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Check that Pint is installed
|
||||||
|
if [ ! -x "./vendor/bin/pint" ]; then
|
||||||
|
echo "Error: laravel/pint is not installed. Run 'composer install' first."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "Running Pint on staged PHP files..."
|
||||||
|
./vendor/bin/pint $STAGED_PHP
|
||||||
|
|
||||||
|
# Re-stage any files that Pint modified
|
||||||
|
for FILE in $STAGED_PHP; do
|
||||||
|
if [ -f "$FILE" ]; then
|
||||||
|
git add "$FILE"
|
||||||
|
fi
|
||||||
|
done
|
||||||
49
modify.sql
49
modify.sql
@@ -1,49 +0,0 @@
|
|||||||
-- Insert records for Initial Operating System if they don't already exist
|
|
||||||
INSERT INTO tblcustomfields
|
|
||||||
(type, relid, fieldname, fieldtype, description, fieldoptions, regexpr, adminonly, required, showorder, showinvoice,
|
|
||||||
sortorder, created_at, updated_at)
|
|
||||||
SELECT 'product',
|
|
||||||
id,
|
|
||||||
'Initial Operating System',
|
|
||||||
'text',
|
|
||||||
'',
|
|
||||||
'',
|
|
||||||
'',
|
|
||||||
'',
|
|
||||||
'',
|
|
||||||
'on',
|
|
||||||
'',
|
|
||||||
0,
|
|
||||||
UTC_TIMESTAMP(),
|
|
||||||
UTC_TIMESTAMP()
|
|
||||||
FROM tblproducts
|
|
||||||
WHERE servertype = 'VirtFusionDirect'
|
|
||||||
AND NOT EXISTS (SELECT 1
|
|
||||||
FROM tblcustomfields
|
|
||||||
WHERE fieldname = 'Initial Operating System'
|
|
||||||
AND relid = tblproducts.id);
|
|
||||||
|
|
||||||
-- Insert records for Initial SSH Key if they don't already exist
|
|
||||||
INSERT INTO tblcustomfields
|
|
||||||
(type, relid, fieldname, fieldtype, description, fieldoptions, regexpr, adminonly, required, showorder, showinvoice,
|
|
||||||
sortorder, created_at, updated_at)
|
|
||||||
SELECT 'product',
|
|
||||||
id,
|
|
||||||
'Initial SSH Key',
|
|
||||||
'text',
|
|
||||||
'',
|
|
||||||
'',
|
|
||||||
'',
|
|
||||||
'',
|
|
||||||
'',
|
|
||||||
'on',
|
|
||||||
'',
|
|
||||||
0,
|
|
||||||
UTC_TIMESTAMP(),
|
|
||||||
UTC_TIMESTAMP()
|
|
||||||
FROM tblproducts
|
|
||||||
WHERE servertype = 'VirtFusionDirect'
|
|
||||||
AND NOT EXISTS (SELECT 1
|
|
||||||
FROM tblcustomfields
|
|
||||||
WHERE fieldname = 'Initial SSH Key'
|
|
||||||
AND relid = tblproducts.id);
|
|
||||||
@@ -1,13 +1,20 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
if (!defined("WHMCS")) {
|
if (! defined('WHMCS')) {
|
||||||
die("This file cannot be accessed directly");
|
exit('This file cannot be accessed directly');
|
||||||
}
|
}
|
||||||
|
|
||||||
use WHMCS\Module\Server\VirtFusionDirect\ModuleFunctions;
|
use WHMCS\Database\Capsule;
|
||||||
use WHMCS\Module\Server\VirtFusionDirect\Module;
|
|
||||||
use WHMCS\Module\Server\VirtFusionDirect\Database;
|
use WHMCS\Module\Server\VirtFusionDirect\Database;
|
||||||
|
use WHMCS\Module\Server\VirtFusionDirect\Log;
|
||||||
|
use WHMCS\Module\Server\VirtFusionDirect\Module;
|
||||||
|
use WHMCS\Module\Server\VirtFusionDirect\ModuleFunctions;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns module metadata consumed by WHMCS.
|
||||||
|
*
|
||||||
|
* @return array
|
||||||
|
*/
|
||||||
function VirtFusionDirect_MetaData()
|
function VirtFusionDirect_MetaData()
|
||||||
{
|
{
|
||||||
return [
|
return [
|
||||||
@@ -19,50 +26,55 @@ function VirtFusionDirect_MetaData()
|
|||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns product configuration options displayed in the WHMCS product editor.
|
||||||
|
*
|
||||||
|
* @return array
|
||||||
|
*/
|
||||||
function VirtFusionDirect_ConfigOptions()
|
function VirtFusionDirect_ConfigOptions()
|
||||||
{
|
{
|
||||||
return [
|
return [
|
||||||
"defaultHypervisorGroupId" => [
|
'defaultHypervisorGroupId' => [
|
||||||
"FriendlyName" => "Hypervisor Group ID",
|
'FriendlyName' => 'Hypervisor Group ID',
|
||||||
"Type" => "text",
|
'Type' => 'text',
|
||||||
"Size" => "20",
|
'Size' => '20',
|
||||||
"Description" => "The default hypervisor group ID for server placement.",
|
'Description' => 'The default hypervisor group ID for server placement.',
|
||||||
"Default" => "1",
|
'Default' => '1',
|
||||||
],
|
],
|
||||||
"packageID" => [
|
'packageID' => [
|
||||||
"FriendlyName" => "Package ID",
|
'FriendlyName' => 'Package ID',
|
||||||
"Type" => "text",
|
'Type' => 'text',
|
||||||
"Size" => "20",
|
'Size' => '20',
|
||||||
"Description" => "The VirtFusion package ID that defines server resources.",
|
'Description' => 'The VirtFusion package ID that defines server resources.',
|
||||||
"Default" => "1",
|
'Default' => '1',
|
||||||
],
|
],
|
||||||
"defaultIPv4" => [
|
'defaultIPv4' => [
|
||||||
"FriendlyName" => "Default IPv4",
|
'FriendlyName' => 'Default IPv4',
|
||||||
"Type" => "dropdown",
|
'Type' => 'dropdown',
|
||||||
"Options" => "0,1,2,3,4,5,6,7,8,9,10",
|
'Options' => '0,1,2,3,4,5,6,7,8,9,10',
|
||||||
"Description" => "The default number of IPv4 addresses to assign to each server.",
|
'Description' => 'The default number of IPv4 addresses to assign to each server.',
|
||||||
"Default" => "1",
|
'Default' => '1',
|
||||||
],
|
],
|
||||||
"selfServiceMode" => [
|
'selfServiceMode' => [
|
||||||
"FriendlyName" => "Self-Service Mode",
|
'FriendlyName' => 'Self-Service Mode',
|
||||||
"Type" => "dropdown",
|
'Type' => 'dropdown',
|
||||||
"Options" => "0|Disabled,1|Hourly,2|Resource Packs,3|Both",
|
'Options' => '0|Disabled,1|Hourly,2|Resource Packs,3|Both',
|
||||||
"Description" => "Enable VirtFusion self-service billing for users created by this product.",
|
'Description' => 'Enable VirtFusion self-service billing for users created by this product.',
|
||||||
"Default" => "0",
|
'Default' => '0',
|
||||||
],
|
],
|
||||||
"autoTopOffThreshold" => [
|
'autoTopOffThreshold' => [
|
||||||
"FriendlyName" => "Auto Top-Off Threshold",
|
'FriendlyName' => 'Auto Top-Off Threshold',
|
||||||
"Type" => "text",
|
'Type' => 'text',
|
||||||
"Size" => "10",
|
'Size' => '10',
|
||||||
"Description" => "Credit balance below which auto top-off triggers during cron. 0 = disabled.",
|
'Description' => 'Credit balance below which auto top-off triggers during cron. 0 = disabled.',
|
||||||
"Default" => "0",
|
'Default' => '0',
|
||||||
],
|
],
|
||||||
"autoTopOffAmount" => [
|
'autoTopOffAmount' => [
|
||||||
"FriendlyName" => "Auto Top-Off Amount",
|
'FriendlyName' => 'Auto Top-Off Amount',
|
||||||
"Type" => "text",
|
'Type' => 'text',
|
||||||
"Size" => "10",
|
'Size' => '10',
|
||||||
"Description" => "Credit amount to add when auto top-off triggers.",
|
'Description' => 'Credit amount to add when auto top-off triggers.',
|
||||||
"Default" => "100",
|
'Default' => '100',
|
||||||
],
|
],
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
@@ -78,7 +90,7 @@ function VirtFusionDirect_TestConnection(array $params)
|
|||||||
}
|
}
|
||||||
|
|
||||||
$url = 'https://' . $hostname . '/api/v1';
|
$url = 'https://' . $hostname . '/api/v1';
|
||||||
$module = new Module();
|
$module = new Module;
|
||||||
$request = $module->initCurl($password);
|
$request = $module->initCurl($password);
|
||||||
$data = $request->get($url . '/connect');
|
$data = $request->get($url . '/connect');
|
||||||
|
|
||||||
@@ -94,27 +106,33 @@ function VirtFusionDirect_TestConnection(array $params)
|
|||||||
|
|
||||||
if ($httpCode == 0) {
|
if ($httpCode == 0) {
|
||||||
$curlError = $request->getRequestInfo('curl_error');
|
$curlError = $request->getRequestInfo('curl_error');
|
||||||
|
|
||||||
return ['success' => false, 'error' => 'Connection failed: ' . ($curlError ?: 'Unable to reach the VirtFusion server. Verify the hostname and that SSL certificates are valid.')];
|
return ['success' => false, 'error' => 'Connection failed: ' . ($curlError ?: 'Unable to reach the VirtFusion server. Verify the hostname and that SSL certificates are valid.')];
|
||||||
}
|
}
|
||||||
|
|
||||||
return ['success' => false, 'error' => 'Unexpected response from VirtFusion API (HTTP ' . $httpCode . '). Please check the server configuration.'];
|
return ['success' => false, 'error' => 'Unexpected response from VirtFusion API (HTTP ' . $httpCode . '). Please check the server configuration.'];
|
||||||
} catch (\Throwable $e) {
|
} catch (Throwable $e) {
|
||||||
return ['success' => false, 'error' => 'Connection test failed: ' . $e->getMessage()];
|
return ['success' => false, 'error' => 'Connection test failed: ' . $e->getMessage()];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns custom admin action buttons shown on the service management page.
|
||||||
|
*
|
||||||
|
* @return array Button label => function suffix pairs
|
||||||
|
*/
|
||||||
function VirtFusionDirect_AdminCustomButtonArray()
|
function VirtFusionDirect_AdminCustomButtonArray()
|
||||||
{
|
{
|
||||||
return [
|
return [
|
||||||
"Update Server Object" => "updateServerObject",
|
'Update Server Object' => 'updateServerObject',
|
||||||
"Validate Server Config" => "validateServerConfig",
|
'Validate Server Config' => 'validateServerConfig',
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
function VirtFusionDirect_ServiceSingleSignOn(array $params)
|
function VirtFusionDirect_ServiceSingleSignOn(array $params)
|
||||||
{
|
{
|
||||||
try {
|
try {
|
||||||
$module = new Module();
|
$module = new Module;
|
||||||
$token = $module->fetchLoginTokens($params['serviceid']);
|
$token = $module->fetchLoginTokens($params['serviceid']);
|
||||||
|
|
||||||
if ($token) {
|
if ($token) {
|
||||||
@@ -122,7 +140,7 @@ function VirtFusionDirect_ServiceSingleSignOn(array $params)
|
|||||||
}
|
}
|
||||||
|
|
||||||
return ['success' => false, 'errorMsg' => 'Unable to generate a login token. The server may not be active or the VirtFusion API may be unreachable.'];
|
return ['success' => false, 'errorMsg' => 'Unable to generate a login token. The server may not be active or the VirtFusion API may be unreachable.'];
|
||||||
} catch (\Exception $e) {
|
} catch (Exception $e) {
|
||||||
return ['success' => false, 'errorMsg' => $e->getMessage()];
|
return ['success' => false, 'errorMsg' => $e->getMessage()];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -132,64 +150,104 @@ function VirtFusionDirect_ServiceSingleSignOn(array $params)
|
|||||||
*/
|
*/
|
||||||
function VirtFusionDirect_CreateAccount(array $params)
|
function VirtFusionDirect_CreateAccount(array $params)
|
||||||
{
|
{
|
||||||
return (new ModuleFunctions())->createAccount($params);
|
return (new ModuleFunctions)->createAccount($params);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Suspends the VirtFusion server associated with a WHMCS service.
|
||||||
|
*
|
||||||
|
* @param array $params WHMCS module parameters
|
||||||
|
* @return string 'success' or error message
|
||||||
|
*/
|
||||||
function VirtFusionDirect_SuspendAccount(array $params)
|
function VirtFusionDirect_SuspendAccount(array $params)
|
||||||
{
|
{
|
||||||
return (new ModuleFunctions())->suspendAccount($params);
|
return (new ModuleFunctions)->suspendAccount($params);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Unsuspends the VirtFusion server associated with a WHMCS service.
|
||||||
|
*
|
||||||
|
* @param array $params WHMCS module parameters
|
||||||
|
* @return string 'success' or error message
|
||||||
|
*/
|
||||||
function VirtFusionDirect_UnsuspendAccount(array $params)
|
function VirtFusionDirect_UnsuspendAccount(array $params)
|
||||||
{
|
{
|
||||||
return (new ModuleFunctions())->unsuspendAccount($params);
|
return (new ModuleFunctions)->unsuspendAccount($params);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Terminates (deletes) the VirtFusion server associated with a WHMCS service.
|
||||||
|
*
|
||||||
|
* @param array $params WHMCS module parameters
|
||||||
|
* @return string 'success' or error message
|
||||||
|
*/
|
||||||
function VirtFusionDirect_TerminateAccount(array $params)
|
function VirtFusionDirect_TerminateAccount(array $params)
|
||||||
{
|
{
|
||||||
return (new ModuleFunctions())->terminateAccount($params);
|
return (new ModuleFunctions)->terminateAccount($params);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Admin custom action: refreshes the local server object from the VirtFusion API.
|
||||||
|
*
|
||||||
|
* @param array $params WHMCS module parameters
|
||||||
|
* @return string 'success' or error message
|
||||||
|
*/
|
||||||
function VirtFusionDirect_updateServerObject(array $params)
|
function VirtFusionDirect_updateServerObject(array $params)
|
||||||
{
|
{
|
||||||
return (new ModuleFunctions())->updateServerObject($params);
|
return (new ModuleFunctions)->updateServerObject($params);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Allows changing of the package of a server
|
* Allows changing of the package of a server
|
||||||
*
|
*
|
||||||
* @param array $params
|
|
||||||
* @return string
|
* @return string
|
||||||
*/
|
*/
|
||||||
function VirtFusionDirect_ChangePackage(array $params)
|
function VirtFusionDirect_ChangePackage(array $params)
|
||||||
{
|
{
|
||||||
return (new ModuleFunctions())->changePackage($params);
|
return (new ModuleFunctions)->changePackage($params);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns HTML fields rendered in the custom admin services tab.
|
||||||
|
*
|
||||||
|
* @param array $params WHMCS module parameters
|
||||||
|
* @return array Field name => HTML value pairs
|
||||||
|
*/
|
||||||
function VirtFusionDirect_AdminServicesTabFields(array $params)
|
function VirtFusionDirect_AdminServicesTabFields(array $params)
|
||||||
{
|
{
|
||||||
return (new ModuleFunctions())->adminServicesTabFields($params);
|
return (new ModuleFunctions)->adminServicesTabFields($params);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handles saving of custom admin services tab field values.
|
||||||
|
*
|
||||||
|
* @param array $params WHMCS module parameters
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
function VirtFusionDirect_AdminServicesTabFieldsSave(array $params)
|
function VirtFusionDirect_AdminServicesTabFieldsSave(array $params)
|
||||||
{
|
{
|
||||||
(new ModuleFunctions())->adminServicesTabFieldsSave($params);
|
(new ModuleFunctions)->adminServicesTabFieldsSave($params);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the client area template variables and template name for the service overview page.
|
||||||
|
*
|
||||||
|
* @param array $params WHMCS module parameters
|
||||||
|
* @return array Smarty template variables and 'templatefile' key
|
||||||
|
*/
|
||||||
function VirtFusionDirect_ClientArea(array $params)
|
function VirtFusionDirect_ClientArea(array $params)
|
||||||
{
|
{
|
||||||
return (new ModuleFunctions())->clientArea($params);
|
return (new ModuleFunctions)->clientArea($params);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Validates server configuration via dry run without creating the server.
|
* Validates server configuration via dry run without creating the server.
|
||||||
*
|
*
|
||||||
* @param array $params
|
|
||||||
* @return string 'success' or error message
|
* @return string 'success' or error message
|
||||||
*/
|
*/
|
||||||
function VirtFusionDirect_validateServerConfig(array $params)
|
function VirtFusionDirect_validateServerConfig(array $params)
|
||||||
{
|
{
|
||||||
return (new ModuleFunctions())->validateServerConfig($params);
|
return (new ModuleFunctions)->validateServerConfig($params);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -204,14 +262,14 @@ function VirtFusionDirect_validateServerConfig(array $params)
|
|||||||
function VirtFusionDirect_UsageUpdate(array $params)
|
function VirtFusionDirect_UsageUpdate(array $params)
|
||||||
{
|
{
|
||||||
try {
|
try {
|
||||||
$module = new Module();
|
$module = new Module;
|
||||||
$cp = $module->getCP($params['serverid']);
|
$cp = $module->getCP($params['serverid']);
|
||||||
|
|
||||||
if (! $cp) {
|
if (! $cp) {
|
||||||
return 'No control server found for usage update.';
|
return 'No control server found for usage update.';
|
||||||
}
|
}
|
||||||
|
|
||||||
$services = \WHMCS\Database\Capsule::table('tblhosting')
|
$services = Capsule::table('tblhosting')
|
||||||
->where('server', $params['serverid'])
|
->where('server', $params['serverid'])
|
||||||
->where('domainstatus', 'Active')
|
->where('domainstatus', 'Active')
|
||||||
->get();
|
->get();
|
||||||
@@ -257,13 +315,13 @@ function VirtFusionDirect_UsageUpdate(array $params)
|
|||||||
|
|
||||||
if (! empty($update)) {
|
if (! empty($update)) {
|
||||||
$update['lastupdate'] = date('Y-m-d H:i:s');
|
$update['lastupdate'] = date('Y-m-d H:i:s');
|
||||||
\WHMCS\Database\Capsule::table('tblhosting')
|
Capsule::table('tblhosting')
|
||||||
->where('id', $service->id)
|
->where('id', $service->id)
|
||||||
->update($update);
|
->update($update);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Self-service auto top-off
|
// Self-service auto top-off
|
||||||
$product = \WHMCS\Database\Capsule::table('tblproducts')
|
$product = Capsule::table('tblproducts')
|
||||||
->where('id', $service->packageid)
|
->where('id', $service->packageid)
|
||||||
->first();
|
->first();
|
||||||
|
|
||||||
@@ -278,24 +336,24 @@ function VirtFusionDirect_UsageUpdate(array $params)
|
|||||||
$credit = $usageInner['credit'] ?? $usageInner['balance'] ?? null;
|
$credit = $usageInner['credit'] ?? $usageInner['balance'] ?? null;
|
||||||
if ($credit !== null && (float) $credit < $threshold) {
|
if ($credit !== null && (float) $credit < $threshold) {
|
||||||
$module->addSelfServiceCredit($service->id, $topOffAmount, 'Auto top-off');
|
$module->addSelfServiceCredit($service->id, $topOffAmount, 'Auto top-off');
|
||||||
\WHMCS\Module\Server\VirtFusionDirect\Log::insert(
|
Log::insert(
|
||||||
'UsageUpdate:autoTopOff',
|
'UsageUpdate:autoTopOff',
|
||||||
['serviceId' => $service->id, 'credit' => $credit, 'threshold' => $threshold],
|
['serviceId' => $service->id, 'credit' => $credit, 'threshold' => $threshold],
|
||||||
['amount' => $topOffAmount]
|
['amount' => $topOffAmount],
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (\Exception $e) {
|
} catch (Exception $e) {
|
||||||
// Log but continue processing other services
|
// Log but continue processing other services
|
||||||
\WHMCS\Module\Server\VirtFusionDirect\Log::insert('UsageUpdate:service:' . $service->id, [], $e->getMessage());
|
Log::insert('UsageUpdate:service:' . $service->id, [], $e->getMessage());
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return 'success';
|
return 'success';
|
||||||
} catch (\Exception $e) {
|
} catch (Exception $e) {
|
||||||
return 'Usage update failed: ' . $e->getMessage();
|
return 'Usage update failed: ' . $e->getMessage();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,92 +2,97 @@
|
|||||||
|
|
||||||
require dirname(__DIR__, 3) . '/init.php';
|
require dirname(__DIR__, 3) . '/init.php';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Admin-facing AJAX API endpoint.
|
||||||
|
*
|
||||||
|
* Requires WHMCS admin authentication. Provides server data lookup
|
||||||
|
* and user impersonation for the admin services tab.
|
||||||
|
*/
|
||||||
|
|
||||||
use WHMCS\Module\Server\VirtFusionDirect\Database;
|
use WHMCS\Module\Server\VirtFusionDirect\Database;
|
||||||
|
use WHMCS\Module\Server\VirtFusionDirect\Log;
|
||||||
use WHMCS\Module\Server\VirtFusionDirect\Module;
|
use WHMCS\Module\Server\VirtFusionDirect\Module;
|
||||||
use WHMCS\Module\Server\VirtFusionDirect\ServerResource;
|
use WHMCS\Module\Server\VirtFusionDirect\ServerResource;
|
||||||
|
|
||||||
$vf = new Module();
|
$vf = new Module;
|
||||||
|
|
||||||
|
try {
|
||||||
|
|
||||||
$vf->adminOnly();
|
$vf->adminOnly();
|
||||||
|
|
||||||
switch ($vf->validateAction(true)) {
|
switch ($vf->validateAction(true)) {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
*
|
|
||||||
* Get server information.
|
* Get server information.
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
case 'serverData':
|
case 'serverData':
|
||||||
|
|
||||||
if ($vf->validateServiceID(true)) {
|
$serviceID = $vf->validateServiceID(true);
|
||||||
|
|
||||||
/** No need to validate ownership **/
|
$whmcsService = Database::getWhmcsService($serviceID);
|
||||||
|
|
||||||
$whmcsService = Database::getWhmcsService((int)$_GET['serviceID']);
|
|
||||||
|
|
||||||
if (! $whmcsService) {
|
if (! $whmcsService) {
|
||||||
$vf->output(['success' => false, 'errors' => 'Service not found.'], true, true, 404);
|
$vf->output(['success' => false, 'errors' => 'Service not found.'], true, true, 404);
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($whmcsService->domainstatus == 'Pending' || $whmcsService->domainstatus == 'Terminated' || $whmcsService->domainstatus == 'Cancelled' || $whmcsService->domainstatus == 'Fraud') {
|
if (in_array($whmcsService->domainstatus, ['Pending', 'Terminated', 'Cancelled', 'Fraud'], true)) {
|
||||||
$vf->output(['success' => false, 'errors' => 'Server is not Active, Suspended or Completed. Not fetching remote data.'], true, true, 400);
|
$vf->output(['success' => false, 'errors' => 'Server is not Active, Suspended or Completed. Not fetching remote data.'], true, true, 400);
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
$data = $vf->fetchServerData((int)$_GET['serviceID']);
|
$data = $vf->fetchServerData($serviceID);
|
||||||
|
|
||||||
if (! $data) {
|
if (! $data) {
|
||||||
$vf->output(['success' => false, 'errors' => 'No data returned from VirtFusion.'], true, true, 502);
|
$vf->output(['success' => false, 'errors' => 'No data returned from VirtFusion.'], true, true, 502);
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
(new Module())->updateWhmcsServiceParamsOnServerObject((int)$_GET['serviceID'], $data);
|
$vf->updateWhmcsServiceParamsOnServerObject($serviceID, $data);
|
||||||
$vf->output(['success' => true, 'data' => (new ServerResource())->process($data)], true, true, 200);
|
$vf->output(['success' => true, 'data' => (new ServerResource)->process($data)], true, true, 200);
|
||||||
|
|
||||||
}
|
|
||||||
break;
|
break;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
*
|
|
||||||
* Impersonate server owner.
|
* Impersonate server owner.
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
case 'impersonateServerOwner':
|
case 'impersonateServerOwner':
|
||||||
|
|
||||||
if ($vf->validateServiceID(true)) {
|
$serviceID = $vf->validateServiceID(true);
|
||||||
|
|
||||||
$service = Database::getSystemService((int)$_GET['serviceID']);
|
|
||||||
|
|
||||||
|
$service = Database::getSystemService($serviceID);
|
||||||
if (! $service) {
|
if (! $service) {
|
||||||
$vf->output(['success' => false, 'errors' => 'Service not found'], true, true, 404);
|
$vf->output(['success' => false, 'errors' => 'Service not found'], true, true, 404);
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
$whmcsService = Database::getWhmcsService((int)$_GET['serviceID']);
|
$whmcsService = Database::getWhmcsService($serviceID);
|
||||||
|
|
||||||
if (! $whmcsService) {
|
if (! $whmcsService) {
|
||||||
$vf->output(['success' => false, 'errors' => 'WHMCS service not found'], true, true, 404);
|
$vf->output(['success' => false, 'errors' => 'WHMCS service not found'], true, true, 404);
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
$cp = $vf->getCP($whmcsService->server);
|
$cp = $vf->getCP($whmcsService->server);
|
||||||
|
|
||||||
if (! $cp) {
|
if (! $cp) {
|
||||||
$vf->output(['success' => false, 'errors' => 'Control server not found'], true, true, 500);
|
$vf->output(['success' => false, 'errors' => 'Control server not found'], true, true, 500);
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
$request = $vf->initCurl($cp['token']);
|
$request = $vf->initCurl($cp['token']);
|
||||||
|
$data = $request->get($cp['url'] . '/users/' . (int) $whmcsService->userid . '/byExtRelation');
|
||||||
$data = $request->get($cp['url'] . '/users/' . $whmcsService->userid . '/byExtRelation');
|
|
||||||
|
|
||||||
if ($request->getRequestInfo('http_code') === 200) {
|
if ($request->getRequestInfo('http_code') === 200) {
|
||||||
$vf->output(['success' => true, 'url' => $cp['base_url'], 'user' => json_decode($data, true)['data']], true, true, 200);
|
$vf->output(['success' => true, 'url' => $cp['base_url'], 'user' => json_decode($data, true)['data']], true, true, 200);
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
$vf->output(['success' => false, 'errors' => 'Received HTTP code ' . $request->getRequestInfo('http_code')], true, true, 502);
|
$vf->output(['success' => false, 'errors' => 'Unable to fetch user data'], true, true, 502);
|
||||||
|
|
||||||
}
|
|
||||||
break;
|
break;
|
||||||
|
|
||||||
default:
|
default:
|
||||||
/** No valid action was specified **/
|
|
||||||
|
|
||||||
$vf->output(['success' => false, 'errors' => 'invalid action'], true, true, 400);
|
$vf->output(['success' => false, 'errors' => 'invalid action'], true, true, 400);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
} catch (Exception $e) {
|
||||||
|
Log::insert('admin.php', [], $e->getMessage());
|
||||||
|
$vf->output(['success' => false, 'errors' => 'An unexpected error occurred'], true, true, 500);
|
||||||
|
}
|
||||||
|
|||||||
@@ -2,10 +2,20 @@
|
|||||||
|
|
||||||
require dirname(__DIR__, 3) . '/init.php';
|
require dirname(__DIR__, 3) . '/init.php';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Client-facing AJAX API endpoint.
|
||||||
|
*
|
||||||
|
* Authenticated by WHMCS session + service ownership validation.
|
||||||
|
* POST for mutations (power, rebuild, rename, credit), GET for reads (serverData, templates, backups).
|
||||||
|
*/
|
||||||
|
|
||||||
|
use WHMCS\Module\Server\VirtFusionDirect\Log;
|
||||||
use WHMCS\Module\Server\VirtFusionDirect\Module;
|
use WHMCS\Module\Server\VirtFusionDirect\Module;
|
||||||
use WHMCS\Module\Server\VirtFusionDirect\ServerResource;
|
use WHMCS\Module\Server\VirtFusionDirect\ServerResource;
|
||||||
|
|
||||||
$vf = new Module();
|
$vf = new Module;
|
||||||
|
|
||||||
|
try {
|
||||||
|
|
||||||
$vf->isAuthenticated();
|
$vf->isAuthenticated();
|
||||||
|
|
||||||
@@ -51,8 +61,8 @@ switch ($action) {
|
|||||||
$data = $vf->fetchServerData($serviceID);
|
$data = $vf->fetchServerData($serviceID);
|
||||||
|
|
||||||
if ($data) {
|
if ($data) {
|
||||||
(new Module())->updateWhmcsServiceParamsOnServerObject($serviceID, $data);
|
$vf->updateWhmcsServiceParamsOnServerObject($serviceID, $data);
|
||||||
$vf->output(['success' => true, 'data' => (new ServerResource())->process($data)], true, true, 200);
|
$vf->output(['success' => true, 'data' => (new ServerResource)->process($data)], true, true, 200);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -398,3 +408,8 @@ switch ($action) {
|
|||||||
default:
|
default:
|
||||||
$vf->output(['success' => false, 'errors' => 'invalid action'], true, true, 400);
|
$vf->output(['success' => false, 'errors' => 'invalid action'], true, true, 400);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
} catch (Exception $e) {
|
||||||
|
Log::insert('client.php', [], $e->getMessage());
|
||||||
|
$vf->output(['success' => false, 'errors' => 'An unexpected error occurred'], true, true, 500);
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
if (!defined("WHMCS")) {
|
if (! defined('WHMCS')) {
|
||||||
die("This file cannot be accessed directly");
|
exit('This file cannot be accessed directly');
|
||||||
}
|
}
|
||||||
|
|
||||||
return [
|
return [
|
||||||
|
|||||||
@@ -1,11 +1,12 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
|
use WHMCS\Database\Capsule;
|
||||||
use WHMCS\Module\Server\VirtFusionDirect\ConfigureService;
|
use WHMCS\Module\Server\VirtFusionDirect\ConfigureService;
|
||||||
use WHMCS\Module\Server\VirtFusionDirect\Database;
|
use WHMCS\Module\Server\VirtFusionDirect\Database;
|
||||||
use WHMCS\User\User;
|
use WHMCS\Module\Server\VirtFusionDirect\Module;
|
||||||
|
|
||||||
if (!defined("WHMCS")) {
|
if (! defined('WHMCS')) {
|
||||||
die("This file cannot be accessed directly");
|
exit('This file cannot be accessed directly');
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -17,6 +18,7 @@ if (!defined("WHMCS")) {
|
|||||||
add_hook('ShoppingCartValidateCheckout', 1, function ($vars) {
|
add_hook('ShoppingCartValidateCheckout', 1, function ($vars) {
|
||||||
$errors = [];
|
$errors = [];
|
||||||
|
|
||||||
|
try {
|
||||||
if (! isset($_SESSION['cart']['products']) || ! is_array($_SESSION['cart']['products'])) {
|
if (! isset($_SESSION['cart']['products']) || ! is_array($_SESSION['cart']['products'])) {
|
||||||
return $errors;
|
return $errors;
|
||||||
}
|
}
|
||||||
@@ -27,7 +29,7 @@ add_hook('ShoppingCartValidateCheckout', 1, function ($vars) {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
$dbProduct = \WHMCS\Database\Capsule::table('tblproducts')
|
$dbProduct = Capsule::table('tblproducts')
|
||||||
->where('id', $pid)
|
->where('id', $pid)
|
||||||
->where('servertype', 'VirtFusionDirect')
|
->where('servertype', 'VirtFusionDirect')
|
||||||
->first();
|
->first();
|
||||||
@@ -39,7 +41,7 @@ add_hook('ShoppingCartValidateCheckout', 1, function ($vars) {
|
|||||||
// Check if Initial Operating System custom field has a value
|
// Check if Initial Operating System custom field has a value
|
||||||
if (isset($product['customfields']) && is_array($product['customfields'])) {
|
if (isset($product['customfields']) && is_array($product['customfields'])) {
|
||||||
$osSelected = false;
|
$osSelected = false;
|
||||||
$customFields = \WHMCS\Database\Capsule::table('tblcustomfields')
|
$customFields = Capsule::table('tblcustomfields')
|
||||||
->where('relid', $pid)
|
->where('relid', $pid)
|
||||||
->where('type', 'product')
|
->where('type', 'product')
|
||||||
->get();
|
->get();
|
||||||
@@ -59,6 +61,9 @@ add_hook('ShoppingCartValidateCheckout', 1, function ($vars) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
} catch (Exception $e) {
|
||||||
|
// Don't block checkout on internal errors
|
||||||
|
}
|
||||||
|
|
||||||
return $errors;
|
return $errors;
|
||||||
});
|
});
|
||||||
@@ -76,19 +81,25 @@ add_hook('ClientAreaFooterOutput', 1, function ($vars) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
$cs = new ConfigureService();
|
$cs = new ConfigureService;
|
||||||
|
|
||||||
$templates_data = $cs->fetchTemplates(
|
$templates_data = $cs->fetchTemplates(
|
||||||
$cs->fetchPackageByDbId($vars['productinfo']['pid']) ?? $cs->fetchPackageId($vars['productinfo']['name'])
|
$cs->fetchPackageByDbId($vars['productinfo']['pid']) ?? $cs->fetchPackageId($vars['productinfo']['name']),
|
||||||
);
|
);
|
||||||
|
|
||||||
if (empty($templates_data)) {
|
if (empty($templates_data)) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
$vfServer = Capsule::table('tblservers')
|
||||||
|
->where('type', 'VirtFusionDirect')
|
||||||
|
->where('disabled', 0)
|
||||||
|
->first();
|
||||||
|
$baseUrl = $vfServer ? rtrim('https://' . $vfServer->hostname, '/') : '';
|
||||||
|
|
||||||
$galleryData = [
|
$galleryData = [
|
||||||
'baseUrl' => '',
|
'baseUrl' => $baseUrl,
|
||||||
'categories' => \WHMCS\Module\Server\VirtFusionDirect\Module::groupOsTemplates($templates_data['data'] ?? [], true),
|
'categories' => Module::groupOsTemplates($templates_data['data'] ?? [], true),
|
||||||
];
|
];
|
||||||
|
|
||||||
$sshKeys = [];
|
$sshKeys = [];
|
||||||
@@ -100,9 +111,10 @@ add_hook('ClientAreaFooterOutput', 1, function ($vars) {
|
|||||||
if ($sshKey['enabled'] === false) {
|
if ($sshKey['enabled'] === false) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
return [
|
return [
|
||||||
'id' => $sshKey['id'],
|
'id' => $sshKey['id'],
|
||||||
'name' => htmlspecialchars($sshKey['name'], ENT_QUOTES, 'UTF-8')
|
'name' => htmlspecialchars($sshKey['name'], ENT_QUOTES, 'UTF-8'),
|
||||||
];
|
];
|
||||||
}, $sshKeysData['data'])));
|
}, $sshKeysData['data'])));
|
||||||
}
|
}
|
||||||
@@ -129,17 +141,17 @@ add_hook('ClientAreaFooterOutput', 1, function ($vars) {
|
|||||||
|
|
||||||
$systemUrl = Database::getSystemUrl();
|
$systemUrl = Database::getSystemUrl();
|
||||||
|
|
||||||
return "
|
return '
|
||||||
<link href=\"" . htmlspecialchars($systemUrl, ENT_QUOTES, 'UTF-8') . "modules/servers/VirtFusionDirect/templates/css/module.css?v=20260319\" rel=\"stylesheet\">
|
<link href="' . htmlspecialchars($systemUrl, ENT_QUOTES, 'UTF-8') . 'modules/servers/VirtFusionDirect/templates/css/module.css?v=' . time() . '" rel="stylesheet">
|
||||||
<script src=\"" . htmlspecialchars($systemUrl, ENT_QUOTES, 'UTF-8') . "modules/servers/VirtFusionDirect/templates/js/keygen.js?v=20260207\"></script>
|
<script src="' . htmlspecialchars($systemUrl, ENT_QUOTES, 'UTF-8') . 'modules/servers/VirtFusionDirect/templates/js/keygen.js?v=' . time() . "\"></script>
|
||||||
<script>
|
<script>
|
||||||
document.addEventListener('DOMContentLoaded', function() {
|
document.addEventListener('DOMContentLoaded', function() {
|
||||||
var osGalleryData = " . json_encode($galleryData, JSON_THROW_ON_ERROR | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) . ";
|
var osGalleryData = " . json_encode($galleryData, JSON_THROW_ON_ERROR | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) . ';
|
||||||
var sshKeys = " . json_encode($sshKeysOptions, JSON_THROW_ON_ERROR | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) . ";
|
var sshKeys = ' . json_encode($sshKeysOptions, JSON_THROW_ON_ERROR | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) . ";
|
||||||
|
|
||||||
var osInputField = document.querySelector('[name=\"customfield[" . (int) $osFieldId . "]\"]');
|
var osInputField = document.querySelector('[name=\"customfield[" . (int) $osFieldId . "]\"]');
|
||||||
var sshInputField = " . ($sshFieldId !== null ? "document.querySelector('[name=\"customfield[" . (int) $sshFieldId . "]\"]')" : "null") . ";
|
var sshInputField = " . ($sshFieldId !== null ? "document.querySelector('[name=\"customfield[" . (int) $sshFieldId . "]\"]')" : 'null') . ';
|
||||||
var sshInputLabel = " . ($sshFieldId !== null ? "document.querySelector('[for=\"customfield" . (int) $sshFieldId . "\"]')" : "null") . ";
|
var sshInputLabel = ' . ($sshFieldId !== null ? "document.querySelector('[for=\"customfield" . (int) $sshFieldId . "\"]')" : 'null') . ";
|
||||||
|
|
||||||
if (!osInputField) return;
|
if (!osInputField) return;
|
||||||
|
|
||||||
@@ -182,8 +194,19 @@ add_hook('ClientAreaFooterOutput', 1, function ($vars) {
|
|||||||
|
|
||||||
var catIcon = document.createElement('span');
|
var catIcon = document.createElement('span');
|
||||||
catIcon.className = 'vf-os-category-icon';
|
catIcon.className = 'vf-os-category-icon';
|
||||||
|
if (cat.icon && osGalleryData.baseUrl) {
|
||||||
|
var catImg = document.createElement('img');
|
||||||
|
catImg.src = osGalleryData.baseUrl + '/img/logo/' + encodeURIComponent(cat.icon);
|
||||||
|
catImg.alt = '';
|
||||||
|
catImg.onerror = function() { this.parentNode.style.background = catColor; this.parentNode.textContent = (cat.name || '?')[0].toUpperCase(); };
|
||||||
|
catIcon.appendChild(catImg);
|
||||||
|
} else if (cat.name === 'Other') {
|
||||||
|
catIcon.style.background = '#6c757d';
|
||||||
|
catIcon.innerHTML = '<svg width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" fill=\"#fff\"><path d=\"M3 2a1 1 0 0 0-1 1v10a1 1 0 0 0 1 1h10a1 1 0 0 0 1-1V3a1 1 0 0 0-1-1H3zm1 2h8v2H4V4zm0 3h8v1H4V7zm0 2h5v1H4V9z\"/></svg>';
|
||||||
|
} else {
|
||||||
catIcon.style.background = catColor;
|
catIcon.style.background = catColor;
|
||||||
catIcon.textContent = (cat.name || '?')[0].toUpperCase();
|
catIcon.textContent = (cat.name || '?')[0].toUpperCase();
|
||||||
|
}
|
||||||
|
|
||||||
var catTitle = document.createElement('span');
|
var catTitle = document.createElement('span');
|
||||||
catTitle.textContent = cat.name + ' (' + cat.templates.length + ')';
|
catTitle.textContent = cat.name + ' (' + cat.templates.length + ')';
|
||||||
@@ -222,10 +245,18 @@ add_hook('ClientAreaFooterOutput', 1, function ($vars) {
|
|||||||
|
|
||||||
var iconDiv = document.createElement('div');
|
var iconDiv = document.createElement('div');
|
||||||
iconDiv.className = 'vf-os-icon';
|
iconDiv.className = 'vf-os-icon';
|
||||||
|
if (tpl.icon && osGalleryData.baseUrl) {
|
||||||
|
var tplImg = document.createElement('img');
|
||||||
|
tplImg.src = osGalleryData.baseUrl + '/img/logo/' + encodeURIComponent(tpl.icon);
|
||||||
|
tplImg.alt = '';
|
||||||
|
tplImg.onerror = function() { this.parentNode.style.background = catColor; this.parentNode.textContent = ''; var s = document.createElement('span'); s.textContent = (tpl.name || '?')[0].toUpperCase(); this.parentNode.appendChild(s); };
|
||||||
|
iconDiv.appendChild(tplImg);
|
||||||
|
} else {
|
||||||
iconDiv.style.background = catColor;
|
iconDiv.style.background = catColor;
|
||||||
var sp = document.createElement('span');
|
var sp = document.createElement('span');
|
||||||
sp.textContent = (tpl.name || '?')[0].toUpperCase();
|
sp.textContent = (tpl.name || '?')[0].toUpperCase();
|
||||||
iconDiv.appendChild(sp);
|
iconDiv.appendChild(sp);
|
||||||
|
}
|
||||||
card.appendChild(iconDiv);
|
card.appendChild(iconDiv);
|
||||||
|
|
||||||
var labelDiv = document.createElement('div');
|
var labelDiv = document.createElement('div');
|
||||||
@@ -540,7 +571,7 @@ add_hook('ClientAreaFooterOutput', 1, function ($vars) {
|
|||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
";
|
";
|
||||||
} catch (\Throwable $e) {
|
} catch (Throwable $e) {
|
||||||
// Silently fail - don't break the checkout page
|
// Silently fail - don't break the checkout page
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,41 +2,76 @@
|
|||||||
|
|
||||||
namespace WHMCS\Module\Server\VirtFusionDirect;
|
namespace WHMCS\Module\Server\VirtFusionDirect;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Static methods that generate HTML fragments for the WHMCS admin services tab.
|
||||||
|
*/
|
||||||
class AdminHTML
|
class AdminHTML
|
||||||
{
|
{
|
||||||
|
/**
|
||||||
|
* Render the "Impersonate Server Owner" button for the admin services tab.
|
||||||
|
*
|
||||||
|
* @param string $systemUrl WHMCS system URL
|
||||||
|
* @param int $serviceId VirtFusion server ID
|
||||||
|
* @return string HTML button markup
|
||||||
|
*/
|
||||||
public static function options($systemUrl, $serviceId)
|
public static function options($systemUrl, $serviceId)
|
||||||
{
|
{
|
||||||
$systemUrl = htmlspecialchars($systemUrl, ENT_QUOTES, 'UTF-8');
|
$systemUrl = htmlspecialchars($systemUrl, ENT_QUOTES, 'UTF-8');
|
||||||
|
|
||||||
return <<<EOT
|
return <<<EOT
|
||||||
<button onclick="impersonateServerOwner('${serviceId}', '${systemUrl}')" type="button" class="btn btn-primary">Impersonate Server Owner</button>
|
<button onclick="impersonateServerOwner('${serviceId}', '${systemUrl}')" type="button" class="btn btn-primary">Impersonate Server Owner</button>
|
||||||
<span class="text-info"> A valid VirtFusion admin session in the same browser is required for this functionality to work.</span>
|
<span class="text-info"> A valid VirtFusion admin session in the same browser is required for this functionality to work.</span>
|
||||||
EOT;
|
EOT;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Render a read-only textarea containing the raw VirtFusion server JSON object.
|
||||||
|
*
|
||||||
|
* @param string $serverObject JSON-encoded server object from the VirtFusion API
|
||||||
|
* @return string HTML textarea markup
|
||||||
|
*/
|
||||||
public static function serverObject($serverObject)
|
public static function serverObject($serverObject)
|
||||||
{
|
{
|
||||||
$serverObject = htmlspecialchars($serverObject, ENT_QUOTES, 'UTF-8');
|
$serverObject = htmlspecialchars($serverObject, ENT_QUOTES, 'UTF-8');
|
||||||
|
|
||||||
return <<<EOT
|
return <<<EOT
|
||||||
<textarea class="form-control" name="modulefields[1]" rows="10" style="width: 100%" disabled>${serverObject}</textarea>
|
<textarea class="form-control" name="modulefields[1]" rows="10" style="width: 100%" disabled>${serverObject}</textarea>
|
||||||
EOT;
|
EOT;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Render an editable text input for the VirtFusion server ID field.
|
||||||
|
*
|
||||||
|
* @param int $serverId Current VirtFusion server ID
|
||||||
|
* @return string HTML input markup with a warning note
|
||||||
|
*/
|
||||||
public static function serverId($serverId)
|
public static function serverId($serverId)
|
||||||
{
|
{
|
||||||
|
$serverId = (int) $serverId;
|
||||||
|
|
||||||
return <<<EOT
|
return <<<EOT
|
||||||
<input type="text" class="form-control input-200 input-inline" name="modulefields[0]" size="20" value="${serverId}" />
|
<input type="text" class="form-control input-200 input-inline" name="modulefields[0]" size="20" value="${serverId}" />
|
||||||
<span class="text-info"> Changing the Sever ID manually is not recommended. Alterations to this field are usually handled automatically.</span>
|
<span class="text-info"> Changing the Sever ID manually is not recommended. Alterations to this field are usually handled automatically.</span>
|
||||||
EOT;
|
EOT;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Render the inline server info panel for the admin services tab, including CSS/JS assets.
|
||||||
|
*
|
||||||
|
* @param string $systemUrl WHMCS system URL (used to build asset and AJAX URLs)
|
||||||
|
* @param int $serviceId VirtFusion server ID passed to the JS data-loader
|
||||||
|
* @return string HTML panel markup with embedded script and asset tags
|
||||||
|
*/
|
||||||
public static function serverInfo($systemUrl, $serviceId)
|
public static function serverInfo($systemUrl, $serviceId)
|
||||||
{
|
{
|
||||||
$systemUrl = htmlspecialchars($systemUrl, ENT_QUOTES, 'UTF-8');
|
$systemUrl = htmlspecialchars($systemUrl, ENT_QUOTES, 'UTF-8');
|
||||||
|
$serviceId = (int) $serviceId;
|
||||||
|
$cacheV = time();
|
||||||
|
|
||||||
return <<<EOT
|
return <<<EOT
|
||||||
<link href="${systemUrl}modules/servers/VirtFusionDirect/templates/css/module.css?v=20260207" rel="stylesheet">
|
<link href="${systemUrl}modules/servers/VirtFusionDirect/templates/css/module.css?v=${cacheV}" rel="stylesheet">
|
||||||
<script src="${systemUrl}modules/servers/VirtFusionDirect/templates/js/module.js?v=20260207"></script>
|
<script src="${systemUrl}modules/servers/VirtFusionDirect/templates/js/module.js?v=${cacheV}"></script>
|
||||||
<div id="vf-loader" class="vf-loader">
|
<div id="vf-loader" class="vf-loader">
|
||||||
<div id="vf-loading"></div>
|
<div id="vf-loading"></div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -2,6 +2,10 @@
|
|||||||
|
|
||||||
namespace WHMCS\Module\Server\VirtFusionDirect;
|
namespace WHMCS\Module\Server\VirtFusionDirect;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Two-tier cache: uses Redis when the ext-redis extension is available, with an atomic
|
||||||
|
* filesystem fallback stored in the system temp directory.
|
||||||
|
*/
|
||||||
class Cache
|
class Cache
|
||||||
{
|
{
|
||||||
const PREFIX = 'vfd:';
|
const PREFIX = 'vfd:';
|
||||||
@@ -30,17 +34,20 @@ class Cache
|
|||||||
|
|
||||||
if (! extension_loaded('redis')) {
|
if (! extension_loaded('redis')) {
|
||||||
self::$redisAvailable = false;
|
self::$redisAvailable = false;
|
||||||
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
$redis = new \Redis();
|
$redis = new \Redis;
|
||||||
$redis->connect('127.0.0.1', 6379, 1.0);
|
$redis->connect('127.0.0.1', 6379, 1.0);
|
||||||
self::$redis = $redis;
|
self::$redis = $redis;
|
||||||
self::$redisAvailable = true;
|
self::$redisAvailable = true;
|
||||||
|
|
||||||
return $redis;
|
return $redis;
|
||||||
} catch (\Exception $e) {
|
} catch (\Exception $e) {
|
||||||
self::$redisAvailable = false;
|
self::$redisAvailable = false;
|
||||||
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -60,6 +67,7 @@ class Cache
|
|||||||
}
|
}
|
||||||
|
|
||||||
self::$fileDir = $dir;
|
self::$fileDir = $dir;
|
||||||
|
|
||||||
return $dir;
|
return $dir;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -87,6 +95,7 @@ class Cache
|
|||||||
if ($data !== false) {
|
if ($data !== false) {
|
||||||
return json_decode($data, true);
|
return json_decode($data, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
return null;
|
return null;
|
||||||
} catch (\Exception $e) {
|
} catch (\Exception $e) {
|
||||||
// Fall through to file cache
|
// Fall through to file cache
|
||||||
@@ -107,11 +116,13 @@ class Cache
|
|||||||
$entry = json_decode($raw, true);
|
$entry = json_decode($raw, true);
|
||||||
if (! $entry || ! isset($entry['expires']) || ! isset($entry['data'])) {
|
if (! $entry || ! isset($entry['expires']) || ! isset($entry['data'])) {
|
||||||
@unlink($path);
|
@unlink($path);
|
||||||
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($entry['expires'] < time()) {
|
if ($entry['expires'] < time()) {
|
||||||
@unlink($path);
|
@unlink($path);
|
||||||
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -132,6 +143,7 @@ class Cache
|
|||||||
if ($redis) {
|
if ($redis) {
|
||||||
try {
|
try {
|
||||||
$redis->setex(self::PREFIX . $key, $ttl, json_encode($value));
|
$redis->setex(self::PREFIX . $key, $ttl, json_encode($value));
|
||||||
|
|
||||||
return;
|
return;
|
||||||
} catch (\Exception $e) {
|
} catch (\Exception $e) {
|
||||||
// Fall through to file cache
|
// Fall through to file cache
|
||||||
@@ -169,28 +181,4 @@ class Cache
|
|||||||
@unlink($path);
|
@unlink($path);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Delete all cache keys matching a pattern.
|
|
||||||
*
|
|
||||||
* @param string $pattern Glob pattern (e.g., "os:*")
|
|
||||||
*/
|
|
||||||
public static function forgetPattern($pattern)
|
|
||||||
{
|
|
||||||
$redis = self::redis();
|
|
||||||
if ($redis) {
|
|
||||||
try {
|
|
||||||
$keys = $redis->keys(self::PREFIX . $pattern);
|
|
||||||
if (!empty($keys)) {
|
|
||||||
$redis->del($keys);
|
|
||||||
}
|
|
||||||
} catch (\Exception $e) {
|
|
||||||
// Continue to file cleanup
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// File cache: can only clear all files for pattern matches
|
|
||||||
// Since file names are md5 hashed, we can't match patterns.
|
|
||||||
// For non-Redis, TTL expiry handles cleanup naturally.
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,17 +2,33 @@
|
|||||||
|
|
||||||
namespace WHMCS\Module\Server\VirtFusionDirect;
|
namespace WHMCS\Module\Server\VirtFusionDirect;
|
||||||
|
|
||||||
use JsonException;
|
|
||||||
use WHMCS\Database\Capsule as DB;
|
use WHMCS\Database\Capsule as DB;
|
||||||
use WHMCS\User\User;
|
use WHMCS\User\User;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handles order-time and provisioning-time operations for VirtFusion servers.
|
||||||
|
*
|
||||||
|
* Extends Module to provide package discovery, OS template fetching, server build
|
||||||
|
* initialization, and SSH key retrieval/creation. Used during WHMCS checkout and
|
||||||
|
* account creation flows rather than ongoing service management.
|
||||||
|
*/
|
||||||
class ConfigureService extends Module
|
class ConfigureService extends Module
|
||||||
{
|
{
|
||||||
/**
|
/**
|
||||||
* @var array|false $cp
|
* The first available VirtFusion control panel connection, as returned by
|
||||||
|
* getCP(). Holds server URL and API token used for all API calls in this
|
||||||
|
* class. False if no active VirtFusion server is configured in WHMCS.
|
||||||
|
*
|
||||||
|
* @var array|false
|
||||||
*/
|
*/
|
||||||
private array|bool $cp;
|
private array|bool $cp;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Initialize the service configurator with the first available VirtFusion server.
|
||||||
|
*
|
||||||
|
* Calls the parent Module constructor then resolves the control panel connection
|
||||||
|
* so all methods in this class have a ready API endpoint.
|
||||||
|
*/
|
||||||
public function __construct()
|
public function __construct()
|
||||||
{
|
{
|
||||||
parent::__construct();
|
parent::__construct();
|
||||||
@@ -20,24 +36,32 @@ class ConfigureService extends Module
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param string $packageName
|
* Find a VirtFusion package ID by its name via the API.
|
||||||
* @return int|null
|
*
|
||||||
* @throws JsonException
|
* Searches the packages list for an enabled package whose name matches
|
||||||
|
* exactly. Result is cached for 10 minutes. Returns null if not found
|
||||||
|
* or if no control panel is available.
|
||||||
|
*
|
||||||
|
* @param string $packageName Exact package name as configured in VirtFusion.
|
||||||
|
* @return int|null Package ID, or null if not found.
|
||||||
*/
|
*/
|
||||||
public function fetchPackageId(string $packageName): ?int
|
public function fetchPackageId(string $packageName): ?int
|
||||||
{
|
{
|
||||||
|
try {
|
||||||
$cacheKey = 'pkg_name:' . md5($packageName);
|
$cacheKey = 'pkg_name:' . md5($packageName);
|
||||||
$cached = Cache::get($cacheKey);
|
$cached = Cache::get($cacheKey);
|
||||||
if ($cached !== null) {
|
if ($cached !== null) {
|
||||||
return $cached;
|
return $cached;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!$this->cp) return null;
|
if (! $this->cp) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
$request = $this->initCurl($this->cp['token']);
|
$request = $this->initCurl($this->cp['token']);
|
||||||
|
|
||||||
$response = $request->get(
|
$response = $request->get(
|
||||||
sprintf("%s/packages", $this->cp['url'])
|
sprintf('%s/packages', $this->cp['url']),
|
||||||
);
|
);
|
||||||
|
|
||||||
$packages = $this->decodeResponseFromJson($response);
|
$packages = $this->decodeResponseFromJson($response);
|
||||||
@@ -45,20 +69,31 @@ class ConfigureService extends Module
|
|||||||
foreach ($packages['data'] as $package) {
|
foreach ($packages['data'] as $package) {
|
||||||
if ($package['name'] === $packageName && $package['enabled'] === true) {
|
if ($package['name'] === $packageName && $package['enabled'] === true) {
|
||||||
Cache::set($cacheKey, $package['id'], 600);
|
Cache::set($cacheKey, $package['id'], 600);
|
||||||
|
|
||||||
return $package['id'];
|
return $package['id'];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return null;
|
return null;
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
Log::insert(__FUNCTION__, [], $e->getMessage());
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param int $productId
|
* Get the VirtFusion package ID from a WHMCS product's config option.
|
||||||
* @return int|null
|
*
|
||||||
|
* Reads configoption2 directly from the tblproducts database record for
|
||||||
|
* the given WHMCS product ID. Returns null if the product does not exist.
|
||||||
|
*
|
||||||
|
* @param int $productId WHMCS product (tblproducts) ID.
|
||||||
|
* @return int|null VirtFusion package ID, or null if the product is not found.
|
||||||
*/
|
*/
|
||||||
public function fetchPackageByDbId(int $productId): ?int
|
public function fetchPackageByDbId(int $productId): ?int
|
||||||
{
|
{
|
||||||
|
try {
|
||||||
$product = DB::table('tblproducts')->where('id', $productId)->first();
|
$product = DB::table('tblproducts')->where('id', $productId)->first();
|
||||||
|
|
||||||
if (is_null($product)) {
|
if (is_null($product)) {
|
||||||
@@ -66,15 +101,26 @@ class ConfigureService extends Module
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (int) $product->configoption2;
|
return (int) $product->configoption2;
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
Log::insert(__FUNCTION__, [], $e->getMessage());
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param int $serverPackageId
|
* Fetch the available OS templates for a given VirtFusion server package.
|
||||||
* @return array|null
|
*
|
||||||
* @throws JsonException
|
* Queries the VirtFusion API for templates compatible with the specified
|
||||||
|
* package spec ID. Result is cached for 10 minutes. Returns null if no
|
||||||
|
* package ID is provided or no control panel is available.
|
||||||
|
*
|
||||||
|
* @param int|null $serverPackageId VirtFusion server package spec ID.
|
||||||
|
* @return array|null Template list from the API, or null on failure.
|
||||||
*/
|
*/
|
||||||
public function fetchTemplates(?int $serverPackageId): ?array
|
public function fetchTemplates(?int $serverPackageId): ?array
|
||||||
{
|
{
|
||||||
|
try {
|
||||||
if (is_null($serverPackageId)) {
|
if (is_null($serverPackageId)) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@@ -85,72 +131,118 @@ class ConfigureService extends Module
|
|||||||
return $cached;
|
return $cached;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!$this->cp) return null;
|
if (! $this->cp) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
$request = $this->initCurl($this->cp['token']);
|
$request = $this->initCurl($this->cp['token']);
|
||||||
|
|
||||||
$response = $request->get(
|
$response = $request->get(
|
||||||
sprintf("%s/media/templates/fromServerPackageSpec/%d", $this->cp['url'], $serverPackageId)
|
sprintf('%s/media/templates/fromServerPackageSpec/%d', $this->cp['url'], $serverPackageId),
|
||||||
);
|
);
|
||||||
|
|
||||||
$result = $this->decodeResponseFromJson($response);
|
$result = $this->decodeResponseFromJson($response);
|
||||||
Cache::set($cacheKey, $result, 600);
|
Cache::set($cacheKey, $result, 600);
|
||||||
|
|
||||||
return $result;
|
return $result;
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
Log::insert(__FUNCTION__, [], $e->getMessage());
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param User|null $user
|
* Get the SSH keys registered for a VirtFusion user.
|
||||||
* @return array|null
|
*
|
||||||
* @throws JsonException
|
* Looks up the VirtFusion account for the given WHMCS user via external
|
||||||
|
* relation ID, then fetches their SSH key list from the API. Returns null
|
||||||
|
* if the user is not found in VirtFusion or no control panel is available.
|
||||||
|
*
|
||||||
|
* @param User|null $user WHMCS User object.
|
||||||
|
* @return array|null SSH key list from the API, or null on failure.
|
||||||
*/
|
*/
|
||||||
public function getUserSshKeys(?User $user): ?array
|
public function getUserSshKeys(?User $user): ?array
|
||||||
{
|
{
|
||||||
|
try {
|
||||||
if (is_null($user)) {
|
if (is_null($user)) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!$this->cp) return null;
|
if (! $this->cp) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
$request = $this->initCurl($this->cp['token']);
|
$request = $this->initCurl($this->cp['token']);
|
||||||
|
|
||||||
$vfUser = $this->getVFUserDetails($user['id']);
|
$vfUser = $this->getVFUserDetails($user['id']);
|
||||||
|
|
||||||
if (!$vfUser) return null;
|
if (! $vfUser) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
$response = $request->get(
|
$response = $request->get(
|
||||||
sprintf("%s/ssh_keys/user/%d", $this->cp['url'], $vfUser['id'])
|
sprintf('%s/ssh_keys/user/%d', $this->cp['url'], $vfUser['id']),
|
||||||
);
|
);
|
||||||
|
|
||||||
return $this->decodeResponseFromJson($response);
|
return $this->decodeResponseFromJson($response);
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
Log::insert(__FUNCTION__, [], $e->getMessage());
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param int $id
|
* Look up a VirtFusion user by WHMCS external relation ID.
|
||||||
* @return array|null
|
*
|
||||||
* @throws JsonException
|
* Calls the VirtFusion API's byExtRelation endpoint using the WHMCS client
|
||||||
|
* ID. Returns null if the user does not exist in VirtFusion or no control
|
||||||
|
* panel is available.
|
||||||
|
*
|
||||||
|
* @param int $id WHMCS client ID used as the VirtFusion external relation ID.
|
||||||
|
* @return array|null VirtFusion user data array, or null if not found.
|
||||||
*/
|
*/
|
||||||
public function getVFUserDetails(int $id): ?array
|
public function getVFUserDetails(int $id): ?array
|
||||||
{
|
{
|
||||||
if (!$this->cp) return null;
|
try {
|
||||||
|
if (! $this->cp) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
$request = $this->initCurl($this->cp['token']);
|
$request = $this->initCurl($this->cp['token']);
|
||||||
|
|
||||||
$response = $this->decodeResponseFromJson($request->get(
|
$response = $this->decodeResponseFromJson($request->get(
|
||||||
sprintf("%s/users/%d/byExtRelation", $this->cp['url'], $id)
|
sprintf('%s/users/%d/byExtRelation', $this->cp['url'], $id),
|
||||||
));
|
));
|
||||||
|
|
||||||
return isset($response['msg']) && $response['msg'] === "ext_relation_id not found" ? null : $response['data'];
|
return isset($response['msg']) && $response['msg'] === 'ext_relation_id not found' ? null : $response['data'];
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
Log::insert(__FUNCTION__, [], $e->getMessage());
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param int $id
|
* Trigger OS installation on a newly created VirtFusion server.
|
||||||
* @param array $vars
|
*
|
||||||
* @param int|null $vfUserId VirtFusion user ID (for creating SSH keys from raw public key)
|
* Posts a build request to the VirtFusion API with the selected OS template
|
||||||
* @return bool
|
* and optionally an SSH key. If the custom field contains a numeric value it
|
||||||
|
* is treated as an existing key ID; if it is a raw public key string, the key
|
||||||
|
* is created first via createUserSshKey(). Returns true on HTTP 200/201.
|
||||||
|
*
|
||||||
|
* @param int $id VirtFusion server ID to build.
|
||||||
|
* @param array $vars WHMCS order vars, including customfields for OS and SSH key.
|
||||||
|
* @param int|null $vfUserId VirtFusion user ID, required when creating a new SSH key from a raw public key.
|
||||||
|
* @return bool True if the build request was accepted, false otherwise.
|
||||||
*/
|
*/
|
||||||
public function initServerBuild(int $id, array $vars, ?int $vfUserId = null): bool
|
public function initServerBuild(int $id, array $vars, ?int $vfUserId = null): bool
|
||||||
{
|
{
|
||||||
if (!$this->cp) return false;
|
try {
|
||||||
|
if (! $this->cp) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
$request = $this->initCurl($this->cp['token']);
|
$request = $this->initCurl($this->cp['token']);
|
||||||
|
|
||||||
@@ -171,9 +263,9 @@ class ConfigureService extends Module
|
|||||||
}
|
}
|
||||||
|
|
||||||
$inputData = [
|
$inputData = [
|
||||||
"operatingSystemId" => $vars['customfields']['Initial Operating System'] ?? null,
|
'operatingSystemId' => $vars['customfields']['Initial Operating System'] ?? null,
|
||||||
"name" => $hostname,
|
'name' => $hostname,
|
||||||
'email' => true
|
'email' => true,
|
||||||
];
|
];
|
||||||
|
|
||||||
if ($sshKeyId) {
|
if ($sshKeyId) {
|
||||||
@@ -183,13 +275,18 @@ class ConfigureService extends Module
|
|||||||
$request->addOption(CURLOPT_POSTFIELDS, json_encode($inputData));
|
$request->addOption(CURLOPT_POSTFIELDS, json_encode($inputData));
|
||||||
|
|
||||||
$response = $request->post(
|
$response = $request->post(
|
||||||
sprintf("%s/servers/%d/build", $this->cp['url'], $id)
|
sprintf('%s/servers/%d/build', $this->cp['url'], $id),
|
||||||
);
|
);
|
||||||
|
|
||||||
$httpCode = $request->getRequestInfo('http_code');
|
$httpCode = $request->getRequestInfo('http_code');
|
||||||
Log::insert(__FUNCTION__, $request->getRequestInfo(), $response);
|
Log::insert(__FUNCTION__, $request->getRequestInfo(), $response);
|
||||||
|
|
||||||
return ($httpCode == 200 || $httpCode == 201);
|
return $httpCode == 200 || $httpCode == 201;
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
Log::insert(__FUNCTION__, [], $e->getMessage());
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -201,7 +298,10 @@ class ConfigureService extends Module
|
|||||||
*/
|
*/
|
||||||
public function createUserSshKey(int $userId, string $publicKey): ?int
|
public function createUserSshKey(int $userId, string $publicKey): ?int
|
||||||
{
|
{
|
||||||
if (!$this->cp) return null;
|
try {
|
||||||
|
if (! $this->cp) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
$request = $this->initCurl($this->cp['token']);
|
$request = $this->initCurl($this->cp['token']);
|
||||||
|
|
||||||
@@ -219,9 +319,15 @@ class ConfigureService extends Module
|
|||||||
$httpCode = $request->getRequestInfo('http_code');
|
$httpCode = $request->getRequestInfo('http_code');
|
||||||
if ($httpCode == 200 || $httpCode == 201) {
|
if ($httpCode == 200 || $httpCode == 201) {
|
||||||
$data = json_decode($response, true);
|
$data = json_decode($response, true);
|
||||||
|
|
||||||
return $data['data']['id'] ?? null;
|
return $data['data']['id'] ?? null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
Log::insert(__FUNCTION__, [], $e->getMessage());
|
||||||
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -2,11 +2,22 @@
|
|||||||
|
|
||||||
namespace WHMCS\Module\Server\VirtFusionDirect;
|
namespace WHMCS\Module\Server\VirtFusionDirect;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* HTTP client wrapper with Bearer token auth, SSL verification, and a 30s timeout.
|
||||||
|
* Single-use — each instance makes one request.
|
||||||
|
*/
|
||||||
class Curl
|
class Curl
|
||||||
{
|
{
|
||||||
|
/** @var resource|\CurlHandle cURL handle */
|
||||||
private $ch;
|
private $ch;
|
||||||
|
|
||||||
|
/** @var array Response info and parsed header data collected after exec */
|
||||||
private $data;
|
private $data;
|
||||||
|
|
||||||
|
/** @var array User-supplied cURL options that override defaults */
|
||||||
private $customOptions = [];
|
private $customOptions = [];
|
||||||
|
|
||||||
|
/** @var array Default cURL options applied to every request */
|
||||||
private $defaultOptions = [
|
private $defaultOptions = [
|
||||||
CURLOPT_SSL_VERIFYPEER => true,
|
CURLOPT_SSL_VERIFYPEER => true,
|
||||||
CURLOPT_SSL_VERIFYHOST => 2,
|
CURLOPT_SSL_VERIFYHOST => 2,
|
||||||
@@ -18,32 +29,17 @@ class Curl
|
|||||||
CURLOPT_CONNECTTIMEOUT => 10,
|
CURLOPT_CONNECTTIMEOUT => 10,
|
||||||
];
|
];
|
||||||
|
|
||||||
|
/** Initialise the cURL handle. */
|
||||||
public function __construct()
|
public function __construct()
|
||||||
{
|
{
|
||||||
$this->ch = curl_init();
|
$this->ch = curl_init();
|
||||||
}
|
}
|
||||||
|
|
||||||
public function useCookies()
|
|
||||||
{
|
|
||||||
$cookiesFile = tempnam(sys_get_temp_dir(), 'virtfusion_cookies');
|
|
||||||
$this->defaultOptions[CURLOPT_COOKIEFILE] = $cookiesFile;
|
|
||||||
$this->defaultOptions[CURLOPT_COOKIEJAR] = $cookiesFile;
|
|
||||||
}
|
|
||||||
|
|
||||||
public function setLog()
|
|
||||||
{
|
|
||||||
$log = fopen(__DIR__ . '/CURL.log', 'a');
|
|
||||||
if ($log) {
|
|
||||||
fwrite($log, str_repeat('=', 80) . PHP_EOL);
|
|
||||||
$this->addOption(CURLOPT_STDERR, $log);
|
|
||||||
$this->addOption(CURLOPT_VERBOSE, true);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param $name
|
* Set a custom cURL option, overriding the defaults.
|
||||||
* @param $value
|
*
|
||||||
|
* @param int $name A CURLOPT_* constant
|
||||||
|
* @param mixed $value The option value
|
||||||
*/
|
*/
|
||||||
public function addOption($name, $value)
|
public function addOption($name, $value)
|
||||||
{
|
{
|
||||||
@@ -51,8 +47,10 @@ class Curl
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param null $url
|
* Execute a PUT request.
|
||||||
* @return bool|string|void
|
*
|
||||||
|
* @param string|null $url Target URL, or null to use a previously set CURLOPT_URL
|
||||||
|
* @return bool|string Response body, or false on failure
|
||||||
*/
|
*/
|
||||||
public function put($url = null)
|
public function put($url = null)
|
||||||
{
|
{
|
||||||
@@ -60,8 +58,10 @@ class Curl
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param null $url
|
* Execute a PATCH request.
|
||||||
* @return bool|string|void
|
*
|
||||||
|
* @param string|null $url Target URL, or null to use a previously set CURLOPT_URL
|
||||||
|
* @return bool|string Response body, or false on failure
|
||||||
*/
|
*/
|
||||||
public function patch($url = null)
|
public function patch($url = null)
|
||||||
{
|
{
|
||||||
@@ -69,9 +69,13 @@ class Curl
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param $method
|
* Set the HTTP method and URL, then execute the request.
|
||||||
* @param $url
|
*
|
||||||
* @return bool|string|void
|
* @param string $method HTTP method (GET, POST, PUT, PATCH, DELETE)
|
||||||
|
* @param string|null $url Target URL, or null to use a previously set CURLOPT_URL
|
||||||
|
* @return bool|string Response body, or false on failure
|
||||||
|
*
|
||||||
|
* @throws \RuntimeException If no URL is available
|
||||||
*/
|
*/
|
||||||
private function send($method, $url)
|
private function send($method, $url)
|
||||||
{
|
{
|
||||||
@@ -87,7 +91,9 @@ class Curl
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @return bool|string
|
* Apply options, run the cURL handle, collect response info, and close the handle.
|
||||||
|
*
|
||||||
|
* @return bool|string Response body, or false on cURL error
|
||||||
*/
|
*/
|
||||||
private function exec()
|
private function exec()
|
||||||
{
|
{
|
||||||
@@ -111,6 +117,7 @@ class Curl
|
|||||||
return $response;
|
return $response;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Merge custom and default cURL options and apply them to the handle. */
|
||||||
private function setOptions()
|
private function setOptions()
|
||||||
{
|
{
|
||||||
if (isset($this->customOptions[CURLOPT_HEADER]) && $this->customOptions[CURLOPT_HEADER]) {
|
if (isset($this->customOptions[CURLOPT_HEADER]) && $this->customOptions[CURLOPT_HEADER]) {
|
||||||
@@ -122,7 +129,9 @@ class Curl
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param $data
|
* Split a response containing headers into header and body parts and store them.
|
||||||
|
*
|
||||||
|
* @param string $data Raw response string (headers + body); replaced with body only
|
||||||
*/
|
*/
|
||||||
private function processHeaders(&$data)
|
private function processHeaders(&$data)
|
||||||
{
|
{
|
||||||
@@ -133,15 +142,17 @@ class Curl
|
|||||||
|
|
||||||
$tmp = explode("\r\n", $this->data['info']['response_header']);
|
$tmp = explode("\r\n", $this->data['info']['response_header']);
|
||||||
$this->data['data']['Message'] = $tmp[0];
|
$this->data['data']['Message'] = $tmp[0];
|
||||||
for ($i = 1, $size = count($tmp); $i < $size; ++$i) {
|
for ($i = 1, $size = count($tmp); $i < $size; $i++) {
|
||||||
$string = explode(': ', $tmp[$i], 2);
|
$string = explode(': ', $tmp[$i], 2);
|
||||||
$this->data['data'][$string[0]] = $string[1];
|
$this->data['data'][$string[0]] = $string[1];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param null $url
|
* Execute a GET request.
|
||||||
* @return bool|string|void
|
*
|
||||||
|
* @param string|null $url Target URL, or null to use a previously set CURLOPT_URL
|
||||||
|
* @return bool|string Response body, or false on failure
|
||||||
*/
|
*/
|
||||||
public function get($url = null)
|
public function get($url = null)
|
||||||
{
|
{
|
||||||
@@ -149,8 +160,10 @@ class Curl
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param null $url
|
* Execute a DELETE request.
|
||||||
* @return bool|string|void
|
*
|
||||||
|
* @param string|null $url Target URL, or null to use a previously set CURLOPT_URL
|
||||||
|
* @return bool|string Response body, or false on failure
|
||||||
*/
|
*/
|
||||||
public function delete($url = null)
|
public function delete($url = null)
|
||||||
{
|
{
|
||||||
@@ -158,8 +171,10 @@ class Curl
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param null $url
|
* Execute a POST request.
|
||||||
* @return bool|string|void
|
*
|
||||||
|
* @param string|null $url Target URL, or null to use a previously set CURLOPT_URL
|
||||||
|
* @return bool|string Response body, or false on failure
|
||||||
*/
|
*/
|
||||||
public function post($url = null)
|
public function post($url = null)
|
||||||
{
|
{
|
||||||
@@ -167,17 +182,10 @@ class Curl
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param null $url
|
* Return curl_getinfo data for the completed request.
|
||||||
* @return bool|string|void
|
*
|
||||||
*/
|
* @param string|false $param A specific info key to retrieve, or false for the full array
|
||||||
public function head($url = null)
|
* @return mixed|null The requested info value, the full info array, or null if the key is absent
|
||||||
{
|
|
||||||
return $this->send('HEAD', $url);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param false $param
|
|
||||||
* @return mixed|null
|
|
||||||
*/
|
*/
|
||||||
public function getRequestInfo($param = false)
|
public function getRequestInfo($param = false)
|
||||||
{
|
{
|
||||||
@@ -189,9 +197,11 @@ class Curl
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param $what
|
* Retrieve a single item from the internal data store by section and key.
|
||||||
* @param $name
|
*
|
||||||
* @return mixed|null
|
* @param string $what Top-level section key (e.g. 'info', 'data')
|
||||||
|
* @param string $name Item key within that section
|
||||||
|
* @return mixed|null The stored value, or null if not found
|
||||||
*/
|
*/
|
||||||
private function getDataItem($what, $name)
|
private function getDataItem($what, $name)
|
||||||
{
|
{
|
||||||
@@ -201,17 +211,4 @@ class Curl
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* @param false $param
|
|
||||||
* @return mixed|null
|
|
||||||
*/
|
|
||||||
public function getHeadersData($param = false)
|
|
||||||
{
|
|
||||||
if ($param) {
|
|
||||||
return $this->getDataItem('data', $param);
|
|
||||||
}
|
|
||||||
|
|
||||||
return $this->data['data'];
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,10 +4,25 @@ namespace WHMCS\Module\Server\VirtFusionDirect;
|
|||||||
|
|
||||||
use WHMCS\Database\Capsule as DB;
|
use WHMCS\Database\Capsule as DB;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handles all database operations for the module's custom table (mod_virtfusion_direct)
|
||||||
|
* and queries against core WHMCS tables (tblhosting, tblclients, tblservers, etc.).
|
||||||
|
*/
|
||||||
class Database
|
class Database
|
||||||
{
|
{
|
||||||
const SYSTEM_TABLE = 'mod_virtfusion_direct';
|
const SYSTEM_TABLE = 'mod_virtfusion_direct';
|
||||||
|
|
||||||
|
/** @var bool Tracks whether custom field existence has already been verified this request. */
|
||||||
|
private static $fieldsChecked = false;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates or migrates the module table schema and ensures custom fields exist.
|
||||||
|
*
|
||||||
|
* Creates mod_virtfusion_direct with service_id and server_id columns if absent,
|
||||||
|
* adds the server_object column if missing, then calls ensureCustomFields().
|
||||||
|
*
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
public static function schema()
|
public static function schema()
|
||||||
{
|
{
|
||||||
if (! DB::schema()->hasTable(self::SYSTEM_TABLE)) {
|
if (! DB::schema()->hasTable(self::SYSTEM_TABLE)) {
|
||||||
@@ -31,10 +46,65 @@ class Database
|
|||||||
Log::insert(__FUNCTION__, [], $e->getMessage());
|
Log::insert(__FUNCTION__, [], $e->getMessage());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
self::ensureCustomFields();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ensures the "Initial Operating System" and "Initial SSH Key" custom fields exist
|
||||||
|
* for every VirtFusionDirect product, creating them via upsert if absent.
|
||||||
|
*
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public static function ensureCustomFields()
|
||||||
|
{
|
||||||
|
if (self::$fieldsChecked) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
self::$fieldsChecked = true;
|
||||||
|
|
||||||
|
try {
|
||||||
|
$productIds = DB::table('tblproducts')
|
||||||
|
->where('servertype', 'VirtFusionDirect')
|
||||||
|
->pluck('id');
|
||||||
|
|
||||||
|
foreach ($productIds as $productId) {
|
||||||
|
foreach (['Initial Operating System', 'Initial SSH Key'] as $fieldName) {
|
||||||
|
DB::table('tblcustomfields')->updateOrInsert(
|
||||||
|
['type' => 'product', 'relid' => $productId, 'fieldname' => $fieldName],
|
||||||
|
[
|
||||||
|
'fieldtype' => 'text',
|
||||||
|
'description' => '',
|
||||||
|
'fieldoptions' => '',
|
||||||
|
'regexpr' => '',
|
||||||
|
'adminonly' => '',
|
||||||
|
'required' => '',
|
||||||
|
'showorder' => 'on',
|
||||||
|
'showinvoice' => '',
|
||||||
|
'sortorder' => 0,
|
||||||
|
'updated_at' => DB::raw('UTC_TIMESTAMP()'),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
Log::insert(__FUNCTION__, [], $e->getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fetches a VirtFusionDirect server record from tblservers.
|
||||||
|
*
|
||||||
|
* When $server is non-zero, returns the matching server by ID.
|
||||||
|
* When $any is true and $server is 0, returns the first enabled server.
|
||||||
|
*
|
||||||
|
* @param int $server WHMCS server ID to look up (0 to skip ID filter).
|
||||||
|
* @param bool $any If true, fall back to the first active server.
|
||||||
|
* @return object|false Row object on success, false on failure or not found.
|
||||||
|
*/
|
||||||
public static function getWhmcsServer(int $server, $any = false)
|
public static function getWhmcsServer(int $server, $any = false)
|
||||||
{
|
{
|
||||||
|
try {
|
||||||
if ($server) {
|
if ($server) {
|
||||||
return DB::table('tblservers')->where('type', 'VirtFusionDirect')->where('id', $server)->first();
|
return DB::table('tblservers')->where('type', 'VirtFusionDirect')->where('id', $server)->first();
|
||||||
}
|
}
|
||||||
@@ -42,81 +112,217 @@ class Database
|
|||||||
if ($any) {
|
if ($any) {
|
||||||
return DB::table('tblservers')->where('type', 'VirtFusionDirect')->where('disabled', 0)->first();
|
return DB::table('tblservers')->where('type', 'VirtFusionDirect')->where('disabled', 0)->first();
|
||||||
}
|
}
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
Log::insert(__FUNCTION__, [], $e->getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Checks whether a WHMCS service belongs to the given client.
|
||||||
|
*
|
||||||
|
* @param int $serviceId WHMCS hosting service ID.
|
||||||
|
* @param int $userId WHMCS client ID.
|
||||||
|
* @return bool True if the service is owned by the client, false otherwise.
|
||||||
|
*/
|
||||||
public static function userWhmcsService(int $serviceId, int $userId)
|
public static function userWhmcsService(int $serviceId, int $userId)
|
||||||
{
|
{
|
||||||
|
try {
|
||||||
return DB::table('tblhosting')->where('id', $serviceId)->where('userid', $userId)->exists();
|
return DB::table('tblhosting')->where('id', $serviceId)->where('userid', $userId)->exists();
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
Log::insert(__FUNCTION__, [], $e->getMessage());
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the WHMCS system URL from tblconfiguration.
|
||||||
|
*
|
||||||
|
* @return string The system URL, or an empty string if not found or on error.
|
||||||
|
*/
|
||||||
public static function getSystemUrl()
|
public static function getSystemUrl()
|
||||||
{
|
{
|
||||||
|
try {
|
||||||
$url = DB::table('tblconfiguration')->where('setting', '=', 'SystemURL')->first();
|
$url = DB::table('tblconfiguration')->where('setting', '=', 'SystemURL')->first();
|
||||||
if (!$url) return '';
|
if (! $url) {
|
||||||
return $url->value;
|
return '';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return $url->value;
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
Log::insert(__FUNCTION__, [], $e->getMessage());
|
||||||
|
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fetches a WHMCS client record by ID.
|
||||||
|
*
|
||||||
|
* @param int $id WHMCS client ID.
|
||||||
|
* @return object|null Row object on success, null on failure or not found.
|
||||||
|
*/
|
||||||
public static function getUser(int $id)
|
public static function getUser(int $id)
|
||||||
{
|
{
|
||||||
|
try {
|
||||||
return DB::table('tblclients')->where('id', $id)->first();
|
return DB::table('tblclients')->where('id', $id)->first();
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
Log::insert(__FUNCTION__, [], $e->getMessage());
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fetches a WHMCS hosting service record by ID.
|
||||||
|
*
|
||||||
|
* @param int $serviceId WHMCS hosting service ID.
|
||||||
|
* @return object|null Row object on success, null on failure or not found.
|
||||||
|
*/
|
||||||
public static function getWhmcsService(int $serviceId)
|
public static function getWhmcsService(int $serviceId)
|
||||||
{
|
{
|
||||||
|
try {
|
||||||
return DB::table('tblhosting')->where('id', $serviceId)->first();
|
return DB::table('tblhosting')->where('id', $serviceId)->first();
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
Log::insert(__FUNCTION__, [], $e->getMessage());
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Upserts the VirtFusion server ID for a given WHMCS service in the module table.
|
||||||
|
*
|
||||||
|
* @param int $serviceId WHMCS hosting service ID.
|
||||||
|
* @param int $serverId VirtFusion server ID.
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
public static function updateSystemServiceServerId(int $serviceId, int $serverId)
|
public static function updateSystemServiceServerId(int $serviceId, int $serverId)
|
||||||
{
|
{
|
||||||
|
try {
|
||||||
DB::table(self::SYSTEM_TABLE)->updateOrInsert(
|
DB::table(self::SYSTEM_TABLE)->updateOrInsert(
|
||||||
[
|
[
|
||||||
"service_id" => $serviceId
|
'service_id' => $serviceId,
|
||||||
],
|
],
|
||||||
[
|
[
|
||||||
'server_id' => $serverId
|
'server_id' => $serverId,
|
||||||
]
|
],
|
||||||
);
|
);
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
Log::insert(__FUNCTION__, [], $e->getMessage());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Updates one or more WHMCS tables with the provided data for a given service ID.
|
||||||
|
*
|
||||||
|
* $data is keyed by table name; each value is an associative array of column => value
|
||||||
|
* pairs passed to an update() WHERE id = $serviceId.
|
||||||
|
*
|
||||||
|
* @param int $serviceId WHMCS hosting service ID.
|
||||||
|
* @param array $data Map of table name to column-value pairs to update.
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
public static function updateWhmcsServiceParams(int $serviceId, $data)
|
public static function updateWhmcsServiceParams(int $serviceId, $data)
|
||||||
{
|
{
|
||||||
|
try {
|
||||||
if (count($data)) {
|
if (count($data)) {
|
||||||
foreach ($data as $key => $items) {
|
foreach ($data as $key => $items) {
|
||||||
DB::table($key)->where('id', $serviceId)->update($items);
|
DB::table($key)->where('id', $serviceId)->update($items);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
Log::insert(__FUNCTION__, [], $e->getMessage());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Checks whether a module table record exists for the given service.
|
||||||
|
*
|
||||||
|
* @param int $serviceId WHMCS hosting service ID.
|
||||||
|
* @return bool True if a record exists, false otherwise.
|
||||||
|
*/
|
||||||
public static function checkSystemService(int $serviceId)
|
public static function checkSystemService(int $serviceId)
|
||||||
{
|
{
|
||||||
|
try {
|
||||||
return DB::table(self::SYSTEM_TABLE)->where('service_id', $serviceId)->exists();
|
return DB::table(self::SYSTEM_TABLE)->where('service_id', $serviceId)->exists();
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
Log::insert(__FUNCTION__, [], $e->getMessage());
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Deletes the module table record for the given service.
|
||||||
|
*
|
||||||
|
* @param int $serviceId WHMCS hosting service ID.
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
public static function deleteSystemService(int $serviceId)
|
public static function deleteSystemService(int $serviceId)
|
||||||
{
|
{
|
||||||
|
try {
|
||||||
DB::table(self::SYSTEM_TABLE)->where('service_id', $serviceId)->delete();
|
DB::table(self::SYSTEM_TABLE)->where('service_id', $serviceId)->delete();
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
Log::insert(__FUNCTION__, [], $e->getMessage());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Persists the raw VirtFusion server API response as JSON in the module table.
|
||||||
|
*
|
||||||
|
* @param int $serviceId WHMCS hosting service ID.
|
||||||
|
* @param mixed $data Server object from the VirtFusion API (will be JSON-encoded).
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
public static function updateSystemServiceServerObject(int $serviceId, $data)
|
public static function updateSystemServiceServerObject(int $serviceId, $data)
|
||||||
{
|
{
|
||||||
|
try {
|
||||||
DB::table(self::SYSTEM_TABLE)->where('service_id', $serviceId)->update(['server_object' => json_encode($data, JSON_PRETTY_PRINT)]);
|
DB::table(self::SYSTEM_TABLE)->where('service_id', $serviceId)->update(['server_object' => json_encode($data, JSON_PRETTY_PRINT)]);
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
Log::insert(__FUNCTION__, [], $e->getMessage());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Inserts or updates the module table record immediately after a VirtFusion server is created.
|
||||||
|
*
|
||||||
|
* Stores both the VirtFusion server ID (from $data->data->id) and the full server
|
||||||
|
* object JSON. Uses update if a record already exists, otherwise inserts.
|
||||||
|
*
|
||||||
|
* @param int $serviceId WHMCS hosting service ID.
|
||||||
|
* @param mixed $data Full API response object from the VirtFusion server creation call.
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
public static function systemOnServerCreate(int $serviceId, $data)
|
public static function systemOnServerCreate(int $serviceId, $data)
|
||||||
{
|
{
|
||||||
|
try {
|
||||||
if (DB::table(self::SYSTEM_TABLE)->where('service_id', $serviceId)->exists()) {
|
if (DB::table(self::SYSTEM_TABLE)->where('service_id', $serviceId)->exists()) {
|
||||||
DB::table(self::SYSTEM_TABLE)->where('service_id', $serviceId)->update(['server_id' => $data->data->id, 'server_object' => json_encode($data, JSON_PRETTY_PRINT)]);
|
DB::table(self::SYSTEM_TABLE)->where('service_id', $serviceId)->update(['server_id' => $data->data->id, 'server_object' => json_encode($data, JSON_PRETTY_PRINT)]);
|
||||||
} else {
|
} else {
|
||||||
DB::table(self::SYSTEM_TABLE)->insert(['service_id' => $serviceId, 'server_id' => $data->data->id, 'server_object' => json_encode($data, JSON_PRETTY_PRINT)]);
|
DB::table(self::SYSTEM_TABLE)->insert(['service_id' => $serviceId, 'server_id' => $data->data->id, 'server_object' => json_encode($data, JSON_PRETTY_PRINT)]);
|
||||||
}
|
}
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
Log::insert(__FUNCTION__, [], $e->getMessage());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fetches the module table record for the given service.
|
||||||
|
*
|
||||||
|
* @param int $serviceId WHMCS hosting service ID.
|
||||||
|
* @return object|null Row object on success, null on failure or not found.
|
||||||
|
*/
|
||||||
public static function getSystemService(int $serviceId)
|
public static function getSystemService(int $serviceId)
|
||||||
{
|
{
|
||||||
|
try {
|
||||||
return DB::table(self::SYSTEM_TABLE)->where('service_id', $serviceId)->first();
|
return DB::table(self::SYSTEM_TABLE)->where('service_id', $serviceId)->first();
|
||||||
}
|
} catch (\Exception $e) {
|
||||||
|
Log::insert(__FUNCTION__, [], $e->getMessage());
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -2,22 +2,22 @@
|
|||||||
|
|
||||||
namespace WHMCS\Module\Server\VirtFusionDirect;
|
namespace WHMCS\Module\Server\VirtFusionDirect;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Thin wrapper around the WHMCS logModuleCall() function for module-level logging.
|
||||||
|
*/
|
||||||
class Log
|
class Log
|
||||||
{
|
{
|
||||||
const LOG_MODULE = 'VirtFusionDirect';
|
const LOG_MODULE = 'VirtFusionDirect';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Write an entry to the WHMCS module log.
|
||||||
|
*
|
||||||
|
* @param string $action Name of the action being logged (e.g. 'CreateAccount')
|
||||||
|
* @param string|array $requestString Request data sent to the API
|
||||||
|
* @param string|array $responseData Response data received from the API
|
||||||
|
*/
|
||||||
public static function insert($action, $requestString, $responseData)
|
public static function insert($action, $requestString, $responseData)
|
||||||
{
|
{
|
||||||
/**
|
|
||||||
* Log module call.
|
|
||||||
*
|
|
||||||
* @param string $module The name of the module
|
|
||||||
* @param string $action The name of the action being performed
|
|
||||||
* @param string|array $requestString The input parameters for the API call
|
|
||||||
* @param string|array $responseData The response data from the API call
|
|
||||||
* @param string|array $processedData The resulting data after any post processing (eg. json decode, xml decode, etc...)
|
|
||||||
* @param array $replaceVars An array of strings for replacement
|
|
||||||
*/
|
|
||||||
logModuleCall(self::LOG_MODULE, $action, $requestString, $responseData);
|
logModuleCall(self::LOG_MODULE, $action, $requestString, $responseData);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2,8 +2,22 @@
|
|||||||
|
|
||||||
namespace WHMCS\Module\Server\VirtFusionDirect;
|
namespace WHMCS\Module\Server\VirtFusionDirect;
|
||||||
|
|
||||||
|
use WHMCS\Authentication\CurrentUser;
|
||||||
|
use WHMCS\Database\Capsule;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Base class providing VirtFusion API integration, authentication checks, and all
|
||||||
|
* server feature methods (power, network, VNC, backup, resource modification,
|
||||||
|
* self-service billing, traffic, rename, password reset).
|
||||||
|
*
|
||||||
|
* Extended by ModuleFunctions (service lifecycle) and ConfigureService (order-time
|
||||||
|
* operations). Most business logic lives here; subclasses delegate to these methods.
|
||||||
|
*/
|
||||||
class Module
|
class Module
|
||||||
{
|
{
|
||||||
|
/**
|
||||||
|
* Initialises the module and ensures the database schema is up to date.
|
||||||
|
*/
|
||||||
public function __construct()
|
public function __construct()
|
||||||
{
|
{
|
||||||
Database::schema();
|
Database::schema();
|
||||||
@@ -18,6 +32,7 @@ class Module
|
|||||||
if (! isset($_GET['action'])) {
|
if (! isset($_GET['action'])) {
|
||||||
$this->output(['success' => false, 'errors' => 'no action specified'], true, $exitOnError, 400);
|
$this->output(['success' => false, 'errors' => 'no action specified'], true, $exitOnError, 400);
|
||||||
}
|
}
|
||||||
|
|
||||||
return preg_replace('/[^a-zA-Z0-9_]/', '', $_GET['action']);
|
return preg_replace('/[^a-zA-Z0-9_]/', '', $_GET['action']);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -30,6 +45,7 @@ class Module
|
|||||||
if (! isset($_GET['serviceID']) || ! is_numeric($_GET['serviceID'])) {
|
if (! isset($_GET['serviceID']) || ! is_numeric($_GET['serviceID'])) {
|
||||||
$this->output(['success' => false, 'errors' => 'no valid serviceID specified'], true, $exitOnError, 400);
|
$this->output(['success' => false, 'errors' => 'no valid serviceID specified'], true, $exitOnError, 400);
|
||||||
}
|
}
|
||||||
|
|
||||||
return (int) $_GET['serviceID'];
|
return (int) $_GET['serviceID'];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -41,7 +57,7 @@ class Module
|
|||||||
public function validateUserOwnsService($serviceID, $exitOnError = true)
|
public function validateUserOwnsService($serviceID, $exitOnError = true)
|
||||||
{
|
{
|
||||||
$serviceID = (int) $serviceID;
|
$serviceID = (int) $serviceID;
|
||||||
$currentUser = new \WHMCS\Authentication\CurrentUser;
|
$currentUser = new CurrentUser;
|
||||||
$client = $currentUser->client();
|
$client = $currentUser->client();
|
||||||
|
|
||||||
if (! $client) {
|
if (! $client) {
|
||||||
@@ -64,15 +80,22 @@ class Module
|
|||||||
*/
|
*/
|
||||||
protected function resolveServiceContext($serviceID)
|
protected function resolveServiceContext($serviceID)
|
||||||
{
|
{
|
||||||
|
try {
|
||||||
$serviceID = (int) $serviceID;
|
$serviceID = (int) $serviceID;
|
||||||
$service = Database::getSystemService($serviceID);
|
$service = Database::getSystemService($serviceID);
|
||||||
if (!$service) return false;
|
if (! $service) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
$whmcsService = Database::getWhmcsService($serviceID);
|
$whmcsService = Database::getWhmcsService($serviceID);
|
||||||
if (!$whmcsService) return false;
|
if (! $whmcsService) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
$cp = $this->getCP($whmcsService->server);
|
$cp = $this->getCP($whmcsService->server);
|
||||||
if (!$cp) return false;
|
if (! $cp) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
return [
|
return [
|
||||||
'service' => $service,
|
'service' => $service,
|
||||||
@@ -81,6 +104,11 @@ class Module
|
|||||||
'request' => $this->initCurl($cp['token']),
|
'request' => $this->initCurl($cp['token']),
|
||||||
'serverId' => (int) $service->server_id,
|
'serverId' => (int) $service->server_id,
|
||||||
];
|
];
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
Log::insert(__FUNCTION__, [], $e->getMessage());
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -89,8 +117,11 @@ class Module
|
|||||||
*/
|
*/
|
||||||
public function fetchLoginTokens($serviceID)
|
public function fetchLoginTokens($serviceID)
|
||||||
{
|
{
|
||||||
|
try {
|
||||||
$ctx = $this->resolveServiceContext($serviceID);
|
$ctx = $this->resolveServiceContext($serviceID);
|
||||||
if (!$ctx) return false;
|
if (! $ctx) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
$data = $ctx['request']->post($ctx['cp']['url'] . '/users/' . (int) $ctx['whmcsService']->userid . '/serverAuthenticationTokens/' . $ctx['serverId']);
|
$data = $ctx['request']->post($ctx['cp']['url'] . '/users/' . (int) $ctx['whmcsService']->userid . '/serverAuthenticationTokens/' . $ctx['serverId']);
|
||||||
Log::insert(__FUNCTION__, $ctx['request']->getRequestInfo(), $data);
|
Log::insert(__FUNCTION__, $ctx['request']->getRequestInfo(), $data);
|
||||||
@@ -101,14 +132,30 @@ class Module
|
|||||||
return $ctx['cp']['base_url'] . $data->data->authentication->endpoint_complete;
|
return $ctx['cp']['base_url'] . $data->data->authentication->endpoint_complete;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
Log::insert(__FUNCTION__, [], $e->getMessage());
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Extract IP address and hostname from a VirtFusion server object and persist
|
||||||
|
* them to the corresponding tblhosting record (dedicatedip, domain, username,
|
||||||
|
* password).
|
||||||
|
*
|
||||||
|
* @param int $serviceId WHMCS service ID
|
||||||
|
* @param object $data Raw server object returned by the VirtFusion API
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
public function updateWhmcsServiceParamsOnServerObject($serviceId, $data)
|
public function updateWhmcsServiceParamsOnServerObject($serviceId, $data)
|
||||||
{
|
{
|
||||||
|
try {
|
||||||
$output = [];
|
$output = [];
|
||||||
|
|
||||||
$serverResource = (new ServerResource())->process($data);
|
$serverResource = (new ServerResource)->process($data);
|
||||||
|
|
||||||
$dedicatedIpv4 = null;
|
$dedicatedIpv4 = null;
|
||||||
|
|
||||||
@@ -126,22 +173,44 @@ class Module
|
|||||||
$name = $serverResource['hostname'];
|
$name = $serverResource['hostname'];
|
||||||
}
|
}
|
||||||
|
|
||||||
$output['tblhosting'] = ["dedicatedip" => $dedicatedIpv4, "domain" => $name, "username" => $serverResource['username'], "password" => $serverResource['password']];
|
$output['tblhosting'] = ['dedicatedip' => $dedicatedIpv4, 'domain' => $name, 'username' => $serverResource['username'], 'password' => $serverResource['password']];
|
||||||
|
|
||||||
Database::updateWhmcsServiceParams($serviceId, $output);
|
Database::updateWhmcsServiceParams($serviceId, $output);
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
Log::insert(__FUNCTION__, [], $e->getMessage());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Clear the dedicated IP on the tblhosting record when a server is terminated.
|
||||||
|
*
|
||||||
|
* @param int $serviceId WHMCS service ID
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
public function updateWhmcsServiceParamsOnDestroy($serviceId)
|
public function updateWhmcsServiceParamsOnDestroy($serviceId)
|
||||||
{
|
{
|
||||||
$output['tblhosting'] = ["dedicatedip" => null];
|
try {
|
||||||
|
$output['tblhosting'] = ['dedicatedip' => null];
|
||||||
|
|
||||||
Database::updateWhmcsServiceParams($serviceId, $output);
|
Database::updateWhmcsServiceParams($serviceId, $output);
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
Log::insert(__FUNCTION__, [], $e->getMessage());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fetch full server details from the VirtFusion API for a given service.
|
||||||
|
*
|
||||||
|
* @param int $serviceID WHMCS service ID
|
||||||
|
* @return object|false Decoded API response object, or false on failure
|
||||||
|
*/
|
||||||
public function fetchServerData($serviceID)
|
public function fetchServerData($serviceID)
|
||||||
{
|
{
|
||||||
|
try {
|
||||||
$ctx = $this->resolveServiceContext($serviceID);
|
$ctx = $this->resolveServiceContext($serviceID);
|
||||||
if (!$ctx) return false;
|
if (! $ctx) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
$data = $ctx['request']->get($ctx['cp']['url'] . '/servers/' . $ctx['serverId']);
|
$data = $ctx['request']->get($ctx['cp']['url'] . '/servers/' . $ctx['serverId']);
|
||||||
Log::insert(__FUNCTION__, $ctx['request']->getRequestInfo(), $data);
|
Log::insert(__FUNCTION__, $ctx['request']->getRequestInfo(), $data);
|
||||||
@@ -149,7 +218,13 @@ class Module
|
|||||||
if ($ctx['request']->getRequestInfo('http_code') == '200') {
|
if ($ctx['request']->getRequestInfo('http_code') == '200') {
|
||||||
return json_decode($data);
|
return json_decode($data);
|
||||||
}
|
}
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
Log::insert(__FUNCTION__, [], $e->getMessage());
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -161,13 +236,16 @@ class Module
|
|||||||
*/
|
*/
|
||||||
public function serverPowerAction($serviceID, $action)
|
public function serverPowerAction($serviceID, $action)
|
||||||
{
|
{
|
||||||
|
try {
|
||||||
$allowedActions = ['boot', 'shutdown', 'restart', 'poweroff'];
|
$allowedActions = ['boot', 'shutdown', 'restart', 'poweroff'];
|
||||||
if (! in_array($action, $allowedActions, true)) {
|
if (! in_array($action, $allowedActions, true)) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
$ctx = $this->resolveServiceContext($serviceID);
|
$ctx = $this->resolveServiceContext($serviceID);
|
||||||
if (!$ctx) return false;
|
if (! $ctx) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
$data = $ctx['request']->post($ctx['cp']['url'] . '/servers/' . $ctx['serverId'] . '/power/' . $action);
|
$data = $ctx['request']->post($ctx['cp']['url'] . '/servers/' . $ctx['serverId'] . '/power/' . $action);
|
||||||
Log::insert(__FUNCTION__ . ':' . $action, $ctx['request']->getRequestInfo(), $data);
|
Log::insert(__FUNCTION__ . ':' . $action, $ctx['request']->getRequestInfo(), $data);
|
||||||
@@ -176,7 +254,13 @@ class Module
|
|||||||
if ($httpCode == 200 || $httpCode == 204) {
|
if ($httpCode == 200 || $httpCode == 204) {
|
||||||
return json_decode($data) ?: (object) ['success' => true];
|
return json_decode($data) ?: (object) ['success' => true];
|
||||||
}
|
}
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
Log::insert(__FUNCTION__, [], $e->getMessage());
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -189,11 +273,16 @@ class Module
|
|||||||
*/
|
*/
|
||||||
public function rebuildServer($serviceID, $osId, $hostname = null)
|
public function rebuildServer($serviceID, $osId, $hostname = null)
|
||||||
{
|
{
|
||||||
|
try {
|
||||||
$osId = (int) $osId;
|
$osId = (int) $osId;
|
||||||
if ($osId <= 0) return false;
|
if ($osId <= 0) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
$ctx = $this->resolveServiceContext($serviceID);
|
$ctx = $this->resolveServiceContext($serviceID);
|
||||||
if (!$ctx) return false;
|
if (! $ctx) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
$buildData = ['operatingSystemId' => $osId, 'email' => true];
|
$buildData = ['operatingSystemId' => $osId, 'email' => true];
|
||||||
if ($hostname !== null && $hostname !== '') {
|
if ($hostname !== null && $hostname !== '') {
|
||||||
@@ -206,10 +295,17 @@ class Module
|
|||||||
|
|
||||||
$httpCode = $ctx['request']->getRequestInfo('http_code');
|
$httpCode = $ctx['request']->getRequestInfo('http_code');
|
||||||
if ($httpCode == 200 || $httpCode == 201) {
|
if ($httpCode == 200 || $httpCode == 201) {
|
||||||
Cache::forgetPattern('backups:' . $ctx['serverId']);
|
Cache::forget('backups:' . $ctx['serverId']);
|
||||||
|
|
||||||
return json_decode($data) ?: (object) ['success' => true];
|
return json_decode($data) ?: (object) ['success' => true];
|
||||||
}
|
}
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
Log::insert(__FUNCTION__, [], $e->getMessage());
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -221,18 +317,29 @@ class Module
|
|||||||
*/
|
*/
|
||||||
public function renameServer($serviceID, $newName)
|
public function renameServer($serviceID, $newName)
|
||||||
{
|
{
|
||||||
|
try {
|
||||||
$newName = trim($newName);
|
$newName = trim($newName);
|
||||||
if (empty($newName) || strlen($newName) > 255) return false;
|
if (empty($newName) || strlen($newName) > 255) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
$ctx = $this->resolveServiceContext($serviceID);
|
$ctx = $this->resolveServiceContext($serviceID);
|
||||||
if (!$ctx) return false;
|
if (! $ctx) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
$ctx['request']->addOption(CURLOPT_POSTFIELDS, json_encode(['name' => $newName]));
|
$ctx['request']->addOption(CURLOPT_POSTFIELDS, json_encode(['name' => $newName]));
|
||||||
$data = $ctx['request']->patch($ctx['cp']['url'] . '/servers/' . $ctx['serverId'] . '/name');
|
$data = $ctx['request']->patch($ctx['cp']['url'] . '/servers/' . $ctx['serverId'] . '/name');
|
||||||
Log::insert(__FUNCTION__, $ctx['request']->getRequestInfo(), $data);
|
Log::insert(__FUNCTION__, $ctx['request']->getRequestInfo(), $data);
|
||||||
|
|
||||||
$httpCode = $ctx['request']->getRequestInfo('http_code');
|
$httpCode = $ctx['request']->getRequestInfo('http_code');
|
||||||
return ($httpCode == 200 || $httpCode == 204);
|
|
||||||
|
return $httpCode == 200 || $httpCode == 204;
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
Log::insert(__FUNCTION__, [], $e->getMessage());
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -243,15 +350,22 @@ class Module
|
|||||||
*/
|
*/
|
||||||
public function fetchOsTemplates($serviceID)
|
public function fetchOsTemplates($serviceID)
|
||||||
{
|
{
|
||||||
|
try {
|
||||||
$ctx = $this->resolveServiceContext($serviceID);
|
$ctx = $this->resolveServiceContext($serviceID);
|
||||||
if (!$ctx) return false;
|
if (! $ctx) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
$product = \WHMCS\Database\Capsule::table('tblproducts')->where('id', $ctx['whmcsService']->packageid)->first();
|
$product = Capsule::table('tblproducts')->where('id', $ctx['whmcsService']->packageid)->first();
|
||||||
if (!$product || !$product->configoption2) return false;
|
if (! $product || ! $product->configoption2) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
$cacheKey = 'os:' . (int) $product->configoption2;
|
$cacheKey = 'os:' . (int) $product->configoption2;
|
||||||
$cached = Cache::get($cacheKey);
|
$cached = Cache::get($cacheKey);
|
||||||
if ($cached !== null) return $cached;
|
if ($cached !== null) {
|
||||||
|
return $cached;
|
||||||
|
}
|
||||||
|
|
||||||
$data = $ctx['request']->get($ctx['cp']['url'] . '/media/templates/fromServerPackageSpec/' . (int) $product->configoption2);
|
$data = $ctx['request']->get($ctx['cp']['url'] . '/media/templates/fromServerPackageSpec/' . (int) $product->configoption2);
|
||||||
Log::insert(__FUNCTION__, $ctx['request']->getRequestInfo(), $data);
|
Log::insert(__FUNCTION__, $ctx['request']->getRequestInfo(), $data);
|
||||||
@@ -266,9 +380,16 @@ class Module
|
|||||||
];
|
];
|
||||||
|
|
||||||
Cache::set($cacheKey, $result, 600);
|
Cache::set($cacheKey, $result, 600);
|
||||||
|
|
||||||
return $result;
|
return $result;
|
||||||
}
|
}
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
Log::insert(__FUNCTION__, [], $e->getMessage());
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -277,7 +398,6 @@ class Module
|
|||||||
*
|
*
|
||||||
* @param array $data Raw template data from VirtFusion API
|
* @param array $data Raw template data from VirtFusion API
|
||||||
* @param bool $htmlEscape Whether to escape names for HTML output
|
* @param bool $htmlEscape Whether to escape names for HTML output
|
||||||
* @return array
|
|
||||||
*/
|
*/
|
||||||
public static function groupOsTemplates(array $data, bool $htmlEscape = false): array
|
public static function groupOsTemplates(array $data, bool $htmlEscape = false): array
|
||||||
{
|
{
|
||||||
@@ -303,9 +423,10 @@ class Module
|
|||||||
if (count($catTemplates) <= 1) {
|
if (count($catTemplates) <= 1) {
|
||||||
$otherTemplates = array_merge($otherTemplates, $catTemplates);
|
$otherTemplates = array_merge($otherTemplates, $catTemplates);
|
||||||
} else {
|
} else {
|
||||||
|
$catName = $osCategory['name'] ?? 'Unknown';
|
||||||
$categories[] = [
|
$categories[] = [
|
||||||
'name' => $esc($osCategory['name'] ?? 'Unknown'),
|
'name' => $esc($catName),
|
||||||
'icon' => $osCategory['icon'] ?? null,
|
'icon' => ($catName === 'Other') ? null : ($osCategory['icon'] ?? null),
|
||||||
'templates' => $catTemplates,
|
'templates' => $catTemplates,
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
@@ -330,12 +451,17 @@ class Module
|
|||||||
*/
|
*/
|
||||||
public function getTrafficStats($serviceID)
|
public function getTrafficStats($serviceID)
|
||||||
{
|
{
|
||||||
|
try {
|
||||||
$ctx = $this->resolveServiceContext($serviceID);
|
$ctx = $this->resolveServiceContext($serviceID);
|
||||||
if (!$ctx) return false;
|
if (! $ctx) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
$cacheKey = 'traffic:' . $ctx['serverId'];
|
$cacheKey = 'traffic:' . $ctx['serverId'];
|
||||||
$cached = Cache::get($cacheKey);
|
$cached = Cache::get($cacheKey);
|
||||||
if ($cached !== null) return $cached;
|
if ($cached !== null) {
|
||||||
|
return $cached;
|
||||||
|
}
|
||||||
|
|
||||||
$data = $ctx['request']->get($ctx['cp']['url'] . '/servers/' . $ctx['serverId'] . '/traffic');
|
$data = $ctx['request']->get($ctx['cp']['url'] . '/servers/' . $ctx['serverId'] . '/traffic');
|
||||||
Log::insert(__FUNCTION__, $ctx['request']->getRequestInfo(), $data);
|
Log::insert(__FUNCTION__, $ctx['request']->getRequestInfo(), $data);
|
||||||
@@ -343,34 +469,16 @@ class Module
|
|||||||
if ($ctx['request']->getRequestInfo('http_code') == 200) {
|
if ($ctx['request']->getRequestInfo('http_code') == 200) {
|
||||||
$result = json_decode($data, true);
|
$result = json_decode($data, true);
|
||||||
Cache::set($cacheKey, $result, 120);
|
Cache::set($cacheKey, $result, 120);
|
||||||
|
|
||||||
return $result;
|
return $result;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
Log::insert(__FUNCTION__, [], $e->getMessage());
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// =========================================================================
|
|
||||||
// IP Address Management
|
|
||||||
// =========================================================================
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Add an IPv4 address to a server.
|
|
||||||
*
|
|
||||||
* @param int $serviceID
|
|
||||||
* @return object|false
|
|
||||||
*/
|
|
||||||
public function addIPv4($serviceID)
|
|
||||||
{
|
|
||||||
$ctx = $this->resolveServiceContext($serviceID);
|
|
||||||
if (!$ctx) return false;
|
|
||||||
|
|
||||||
$data = $ctx['request']->post($ctx['cp']['url'] . '/servers/' . $ctx['serverId'] . '/ipv4');
|
|
||||||
Log::insert(__FUNCTION__, $ctx['request']->getRequestInfo(), $data);
|
|
||||||
|
|
||||||
$httpCode = $ctx['request']->getRequestInfo('http_code');
|
|
||||||
if ($httpCode == 200 || $httpCode == 201) {
|
|
||||||
return json_decode($data) ?: (object) ['success' => true];
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// =========================================================================
|
// =========================================================================
|
||||||
@@ -385,12 +493,17 @@ class Module
|
|||||||
*/
|
*/
|
||||||
public function getServerBackups($serviceID)
|
public function getServerBackups($serviceID)
|
||||||
{
|
{
|
||||||
|
try {
|
||||||
$ctx = $this->resolveServiceContext($serviceID);
|
$ctx = $this->resolveServiceContext($serviceID);
|
||||||
if (!$ctx) return false;
|
if (! $ctx) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
$cacheKey = 'backups:' . $ctx['serverId'];
|
$cacheKey = 'backups:' . $ctx['serverId'];
|
||||||
$cached = Cache::get($cacheKey);
|
$cached = Cache::get($cacheKey);
|
||||||
if ($cached !== null) return $cached;
|
if ($cached !== null) {
|
||||||
|
return $cached;
|
||||||
|
}
|
||||||
|
|
||||||
$data = $ctx['request']->get($ctx['cp']['url'] . '/backups/server/' . $ctx['serverId']);
|
$data = $ctx['request']->get($ctx['cp']['url'] . '/backups/server/' . $ctx['serverId']);
|
||||||
Log::insert(__FUNCTION__, $ctx['request']->getRequestInfo(), $data);
|
Log::insert(__FUNCTION__, $ctx['request']->getRequestInfo(), $data);
|
||||||
@@ -398,34 +511,16 @@ class Module
|
|||||||
if ($ctx['request']->getRequestInfo('http_code') == 200) {
|
if ($ctx['request']->getRequestInfo('http_code') == 200) {
|
||||||
$result = json_decode($data, true);
|
$result = json_decode($data, true);
|
||||||
Cache::set($cacheKey, $result, 120);
|
Cache::set($cacheKey, $result, 120);
|
||||||
|
|
||||||
return $result;
|
return $result;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
Log::insert(__FUNCTION__, [], $e->getMessage());
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Assign a backup plan to a server.
|
|
||||||
*
|
|
||||||
* @param int $serviceID
|
|
||||||
* @param int $planId Backup plan ID (0 to remove)
|
|
||||||
* @return object|false
|
|
||||||
*/
|
|
||||||
public function assignBackupPlan($serviceID, $planId)
|
|
||||||
{
|
|
||||||
$planId = (int) $planId;
|
|
||||||
$ctx = $this->resolveServiceContext($serviceID);
|
|
||||||
if (!$ctx) return false;
|
|
||||||
|
|
||||||
$ctx['request']->addOption(CURLOPT_POSTFIELDS, json_encode(['planId' => $planId]));
|
|
||||||
$endpoint = $ctx['cp']['url'] . '/servers/' . $ctx['serverId'] . '/backup/plan';
|
|
||||||
$data = $planId > 0 ? $ctx['request']->post($endpoint) : $ctx['request']->delete($endpoint);
|
|
||||||
Log::insert(__FUNCTION__, $ctx['request']->getRequestInfo(), $data);
|
|
||||||
|
|
||||||
$httpCode = $ctx['request']->getRequestInfo('http_code');
|
|
||||||
if ($httpCode == 200 || $httpCode == 204) {
|
|
||||||
return json_decode($data) ?: (object) ['success' => true];
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// =========================================================================
|
// =========================================================================
|
||||||
@@ -440,8 +535,11 @@ class Module
|
|||||||
*/
|
*/
|
||||||
public function getVncConsole($serviceID)
|
public function getVncConsole($serviceID)
|
||||||
{
|
{
|
||||||
|
try {
|
||||||
$ctx = $this->resolveServiceContext($serviceID);
|
$ctx = $this->resolveServiceContext($serviceID);
|
||||||
if (!$ctx) return false;
|
if (! $ctx) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
$data = $ctx['request']->get($ctx['cp']['url'] . '/servers/' . $ctx['serverId'] . '/vnc');
|
$data = $ctx['request']->get($ctx['cp']['url'] . '/servers/' . $ctx['serverId'] . '/vnc');
|
||||||
Log::insert(__FUNCTION__, $ctx['request']->getRequestInfo(), $data);
|
Log::insert(__FUNCTION__, $ctx['request']->getRequestInfo(), $data);
|
||||||
@@ -449,7 +547,13 @@ class Module
|
|||||||
if ($ctx['request']->getRequestInfo('http_code') == 200) {
|
if ($ctx['request']->getRequestInfo('http_code') == 200) {
|
||||||
return json_decode($data, true);
|
return json_decode($data, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
Log::insert(__FUNCTION__, [], $e->getMessage());
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -461,8 +565,11 @@ class Module
|
|||||||
*/
|
*/
|
||||||
public function toggleVnc($serviceID, $enabled)
|
public function toggleVnc($serviceID, $enabled)
|
||||||
{
|
{
|
||||||
|
try {
|
||||||
$ctx = $this->resolveServiceContext($serviceID);
|
$ctx = $this->resolveServiceContext($serviceID);
|
||||||
if (!$ctx) return false;
|
if (! $ctx) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
$ctx['request']->addOption(CURLOPT_POSTFIELDS, json_encode(['enabled' => (bool) $enabled]));
|
$ctx['request']->addOption(CURLOPT_POSTFIELDS, json_encode(['enabled' => (bool) $enabled]));
|
||||||
$data = $ctx['request']->post($ctx['cp']['url'] . '/servers/' . $ctx['serverId'] . '/vnc');
|
$data = $ctx['request']->post($ctx['cp']['url'] . '/servers/' . $ctx['serverId'] . '/vnc');
|
||||||
@@ -472,7 +579,13 @@ class Module
|
|||||||
if ($httpCode == 200 || $httpCode == 204) {
|
if ($httpCode == 200 || $httpCode == 204) {
|
||||||
return json_decode($data, true) ?: ['success' => true];
|
return json_decode($data, true) ?: ['success' => true];
|
||||||
}
|
}
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
Log::insert(__FUNCTION__, [], $e->getMessage());
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// =========================================================================
|
// =========================================================================
|
||||||
@@ -489,14 +602,21 @@ class Module
|
|||||||
*/
|
*/
|
||||||
public function modifyResource($serviceID, $resource, $value)
|
public function modifyResource($serviceID, $resource, $value)
|
||||||
{
|
{
|
||||||
|
try {
|
||||||
$allowedResources = ['memory', 'cpuCores', 'traffic'];
|
$allowedResources = ['memory', 'cpuCores', 'traffic'];
|
||||||
if (!in_array($resource, $allowedResources, true)) return false;
|
if (! in_array($resource, $allowedResources, true)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
$value = (int) $value;
|
$value = (int) $value;
|
||||||
if ($value < 0) return false;
|
if ($value < 0) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
$ctx = $this->resolveServiceContext($serviceID);
|
$ctx = $this->resolveServiceContext($serviceID);
|
||||||
if (!$ctx) return false;
|
if (! $ctx) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
$ctx['request']->addOption(CURLOPT_POSTFIELDS, json_encode([$resource => $value]));
|
$ctx['request']->addOption(CURLOPT_POSTFIELDS, json_encode([$resource => $value]));
|
||||||
$data = $ctx['request']->put($ctx['cp']['url'] . '/servers/' . $ctx['serverId'] . '/modify/' . $resource);
|
$data = $ctx['request']->put($ctx['cp']['url'] . '/servers/' . $ctx['serverId'] . '/modify/' . $resource);
|
||||||
@@ -506,7 +626,13 @@ class Module
|
|||||||
if ($httpCode == 200 || $httpCode == 204) {
|
if ($httpCode == 200 || $httpCode == 204) {
|
||||||
return json_decode($data) ?: (object) ['success' => true];
|
return json_decode($data) ?: (object) ['success' => true];
|
||||||
}
|
}
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
Log::insert(__FUNCTION__, [], $e->getMessage());
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// =========================================================================
|
// =========================================================================
|
||||||
@@ -522,6 +648,7 @@ class Module
|
|||||||
*/
|
*/
|
||||||
public function validateServerCreation($options, $serverId)
|
public function validateServerCreation($options, $serverId)
|
||||||
{
|
{
|
||||||
|
try {
|
||||||
$cp = $this->getCP($serverId, ! $serverId);
|
$cp = $this->getCP($serverId, ! $serverId);
|
||||||
if (! $cp) {
|
if (! $cp) {
|
||||||
return ['valid' => false, 'errors' => ['No control server found']];
|
return ['valid' => false, 'errors' => ['No control server found']];
|
||||||
@@ -550,6 +677,11 @@ class Module
|
|||||||
}
|
}
|
||||||
|
|
||||||
return ['valid' => false, 'errors' => $errors];
|
return ['valid' => false, 'errors' => $errors];
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
Log::insert(__FUNCTION__, [], $e->getMessage());
|
||||||
|
|
||||||
|
return ['valid' => false, 'errors' => [$e->getMessage()]];
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -560,8 +692,11 @@ class Module
|
|||||||
*/
|
*/
|
||||||
public function resetServerPassword($serviceID)
|
public function resetServerPassword($serviceID)
|
||||||
{
|
{
|
||||||
|
try {
|
||||||
$ctx = $this->resolveServiceContext($serviceID);
|
$ctx = $this->resolveServiceContext($serviceID);
|
||||||
if (!$ctx) return false;
|
if (! $ctx) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
$data = $ctx['request']->post($ctx['cp']['url'] . '/servers/' . $ctx['serverId'] . '/resetPassword');
|
$data = $ctx['request']->post($ctx['cp']['url'] . '/servers/' . $ctx['serverId'] . '/resetPassword');
|
||||||
Log::insert(__FUNCTION__, $ctx['request']->getRequestInfo(), $data);
|
Log::insert(__FUNCTION__, $ctx['request']->getRequestInfo(), $data);
|
||||||
@@ -570,14 +705,31 @@ class Module
|
|||||||
if ($httpCode == 200 || $httpCode == 201) {
|
if ($httpCode == 200 || $httpCode == 201) {
|
||||||
return json_decode($data, true);
|
return json_decode($data, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
Log::insert(__FUNCTION__, [], $e->getMessage());
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reset the VirtFusion panel login password for a user identified by their
|
||||||
|
* WHMCS client ID (used as the external relation ID in VirtFusion).
|
||||||
|
*
|
||||||
|
* @param int $serviceID WHMCS service ID
|
||||||
|
* @param int $clientID WHMCS client ID (mapped to VirtFusion external relation ID)
|
||||||
|
* @return object|false Decoded API response object, or false on failure
|
||||||
|
*/
|
||||||
public function resetUserPassword($serviceID, $clientID)
|
public function resetUserPassword($serviceID, $clientID)
|
||||||
{
|
{
|
||||||
|
try {
|
||||||
$clientID = (int) $clientID;
|
$clientID = (int) $clientID;
|
||||||
$ctx = $this->resolveServiceContext($serviceID);
|
$ctx = $this->resolveServiceContext($serviceID);
|
||||||
if (!$ctx) return false;
|
if (! $ctx) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
$data = $ctx['request']->post($ctx['cp']['url'] . '/users/' . $clientID . '/byExtRelation/resetPassword');
|
$data = $ctx['request']->post($ctx['cp']['url'] . '/users/' . $clientID . '/byExtRelation/resetPassword');
|
||||||
Log::insert(__FUNCTION__, $ctx['request']->getRequestInfo(), $data);
|
Log::insert(__FUNCTION__, $ctx['request']->getRequestInfo(), $data);
|
||||||
@@ -585,14 +737,22 @@ class Module
|
|||||||
if ($ctx['request']->getRequestInfo('http_code') == '201') {
|
if ($ctx['request']->getRequestInfo('http_code') == '201') {
|
||||||
return json_decode($data);
|
return json_decode($data);
|
||||||
}
|
}
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
Log::insert(__FUNCTION__, [], $e->getMessage());
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param $data
|
* Send a JSON or raw response to the client and optionally terminate execution.
|
||||||
* @param bool $json
|
*
|
||||||
* @param bool $exit
|
* @param mixed $data Response payload; encoded as JSON when $json is true
|
||||||
* @param int $rspCode
|
* @param bool $json Whether to JSON-encode $data and set the Content-Type header
|
||||||
|
* @param bool $exit Whether to call exit() after sending the response
|
||||||
|
* @param int $rspCode HTTP status code to send
|
||||||
*/
|
*/
|
||||||
public function output($data, $json = true, $exit = true, $rspCode = 200)
|
public function output($data, $json = true, $exit = true, $rspCode = 200)
|
||||||
{
|
{
|
||||||
@@ -611,11 +771,15 @@ class Module
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param $server
|
* Resolve a WHMCS server record into an API base URL and decrypted Bearer token.
|
||||||
* @return array|false
|
*
|
||||||
|
* @param int|object $server WHMCS server ID or server object
|
||||||
|
* @param bool $any When true, fall back to any available server if the given one is not found
|
||||||
|
* @return array{url: string, base_url: string, token: string}|false
|
||||||
*/
|
*/
|
||||||
public function getCP($server, $any = false)
|
public function getCP($server, $any = false)
|
||||||
{
|
{
|
||||||
|
try {
|
||||||
$cp = Database::getWhmcsServer($server, $any);
|
$cp = Database::getWhmcsServer($server, $any);
|
||||||
|
|
||||||
if ($cp) {
|
if ($cp) {
|
||||||
@@ -624,15 +788,22 @@ class Module
|
|||||||
'base_url' => 'https://' . $cp->hostname,
|
'base_url' => 'https://' . $cp->hostname,
|
||||||
'token' => decrypt($cp->password)];
|
'token' => decrypt($cp->password)];
|
||||||
}
|
}
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
Log::insert(__FUNCTION__, [], $e->getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
* Enforce WHMCS admin authentication. Returns true if the current user is an
|
||||||
|
* authenticated admin; otherwise sends a 401 JSON response and exits.
|
||||||
|
*
|
||||||
* @return bool|void
|
* @return bool|void
|
||||||
*/
|
*/
|
||||||
public function adminOnly()
|
public function adminOnly()
|
||||||
{
|
{
|
||||||
if ((new \WHMCS\Authentication\CurrentUser)->isAuthenticatedAdmin()) {
|
if ((new CurrentUser)->isAuthenticatedAdmin()) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -640,11 +811,14 @@ class Module
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
* Enforce WHMCS client authentication. Returns true if the current user is an
|
||||||
|
* authenticated client; otherwise sends a 401 JSON response and exits.
|
||||||
|
*
|
||||||
* @return bool|void
|
* @return bool|void
|
||||||
*/
|
*/
|
||||||
public function isAuthenticated()
|
public function isAuthenticated()
|
||||||
{
|
{
|
||||||
if ((new \WHMCS\Authentication\CurrentUser)->isAuthenticatedUser()) {
|
if ((new CurrentUser)->isAuthenticatedUser()) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -652,17 +826,20 @@ class Module
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param $token
|
* Create a pre-configured Curl instance with JSON Accept/Content-Type headers
|
||||||
* @return \WHMCS\Module\Server\VirtFusionDirect\Curl
|
* and a Bearer token for authenticating against the VirtFusion API.
|
||||||
|
*
|
||||||
|
* @param string $token VirtFusion API Bearer token
|
||||||
|
* @return Curl
|
||||||
*/
|
*/
|
||||||
public function initCurl($token)
|
public function initCurl($token)
|
||||||
{
|
{
|
||||||
$curl = new Curl();
|
$curl = new Curl;
|
||||||
|
|
||||||
$curl->addOption(CURLOPT_HTTPHEADER, [
|
$curl->addOption(CURLOPT_HTTPHEADER, [
|
||||||
'Accept: application/json',
|
'Accept: application/json',
|
||||||
'Content-type: application/json; charset=utf-8',
|
'Content-type: application/json; charset=utf-8',
|
||||||
'authorization: Bearer ' . $token
|
'authorization: Bearer ' . $token,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
return $curl;
|
return $curl;
|
||||||
@@ -680,12 +857,17 @@ class Module
|
|||||||
*/
|
*/
|
||||||
public function getSelfServiceUsage($serviceID)
|
public function getSelfServiceUsage($serviceID)
|
||||||
{
|
{
|
||||||
|
try {
|
||||||
$serviceID = (int) $serviceID;
|
$serviceID = (int) $serviceID;
|
||||||
$whmcsService = Database::getWhmcsService($serviceID);
|
$whmcsService = Database::getWhmcsService($serviceID);
|
||||||
if (!$whmcsService) return false;
|
if (! $whmcsService) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
$cp = $this->getCP($whmcsService->server);
|
$cp = $this->getCP($whmcsService->server);
|
||||||
if (!$cp) return false;
|
if (! $cp) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
$request = $this->initCurl($cp['token']);
|
$request = $this->initCurl($cp['token']);
|
||||||
$data = $request->get($cp['url'] . '/selfService/usage/byUserExtRelationId/' . (int) $whmcsService->userid);
|
$data = $request->get($cp['url'] . '/selfService/usage/byUserExtRelationId/' . (int) $whmcsService->userid);
|
||||||
@@ -695,7 +877,13 @@ class Module
|
|||||||
if ($request->getRequestInfo('http_code') == 200) {
|
if ($request->getRequestInfo('http_code') == 200) {
|
||||||
return json_decode($data, true);
|
return json_decode($data, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
Log::insert(__FUNCTION__, [], $e->getMessage());
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -706,12 +894,17 @@ class Module
|
|||||||
*/
|
*/
|
||||||
public function getSelfServiceReport($serviceID)
|
public function getSelfServiceReport($serviceID)
|
||||||
{
|
{
|
||||||
|
try {
|
||||||
$serviceID = (int) $serviceID;
|
$serviceID = (int) $serviceID;
|
||||||
$whmcsService = Database::getWhmcsService($serviceID);
|
$whmcsService = Database::getWhmcsService($serviceID);
|
||||||
if (!$whmcsService) return false;
|
if (! $whmcsService) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
$cp = $this->getCP($whmcsService->server);
|
$cp = $this->getCP($whmcsService->server);
|
||||||
if (!$cp) return false;
|
if (! $cp) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
$request = $this->initCurl($cp['token']);
|
$request = $this->initCurl($cp['token']);
|
||||||
$data = $request->get($cp['url'] . '/selfService/report/byUserExtRelationId/' . (int) $whmcsService->userid);
|
$data = $request->get($cp['url'] . '/selfService/report/byUserExtRelationId/' . (int) $whmcsService->userid);
|
||||||
@@ -721,7 +914,13 @@ class Module
|
|||||||
if ($request->getRequestInfo('http_code') == 200) {
|
if ($request->getRequestInfo('http_code') == 200) {
|
||||||
return json_decode($data, true);
|
return json_decode($data, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
Log::insert(__FUNCTION__, [], $e->getMessage());
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -734,6 +933,7 @@ class Module
|
|||||||
*/
|
*/
|
||||||
public function addSelfServiceCredit($serviceID, $tokens, $reference = '')
|
public function addSelfServiceCredit($serviceID, $tokens, $reference = '')
|
||||||
{
|
{
|
||||||
|
try {
|
||||||
$serviceID = (int) $serviceID;
|
$serviceID = (int) $serviceID;
|
||||||
$tokens = (float) $tokens;
|
$tokens = (float) $tokens;
|
||||||
|
|
||||||
@@ -742,10 +942,14 @@ class Module
|
|||||||
}
|
}
|
||||||
|
|
||||||
$whmcsService = Database::getWhmcsService($serviceID);
|
$whmcsService = Database::getWhmcsService($serviceID);
|
||||||
if (!$whmcsService) return false;
|
if (! $whmcsService) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
$cp = $this->getCP($whmcsService->server);
|
$cp = $this->getCP($whmcsService->server);
|
||||||
if (!$cp) return false;
|
if (! $cp) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
$request = $this->initCurl($cp['token']);
|
$request = $this->initCurl($cp['token']);
|
||||||
$request->addOption(CURLOPT_POSTFIELDS, json_encode([
|
$request->addOption(CURLOPT_POSTFIELDS, json_encode([
|
||||||
@@ -761,49 +965,19 @@ class Module
|
|||||||
if ($httpCode == 200 || $httpCode == 201) {
|
if ($httpCode == 200 || $httpCode == 201) {
|
||||||
return json_decode($data, true);
|
return json_decode($data, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
Log::insert(__FUNCTION__, [], $e->getMessage());
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Get available self-service currencies.
|
|
||||||
*
|
|
||||||
* @param int $serviceID
|
|
||||||
* @return array|false
|
|
||||||
*/
|
|
||||||
public function getSelfServiceCurrencies($serviceID)
|
|
||||||
{
|
|
||||||
$cacheKey = 'ss_currencies';
|
|
||||||
$cached = Cache::get($cacheKey);
|
|
||||||
if ($cached !== null) {
|
|
||||||
return $cached;
|
|
||||||
}
|
|
||||||
|
|
||||||
$serviceID = (int) $serviceID;
|
|
||||||
$whmcsService = Database::getWhmcsService($serviceID);
|
|
||||||
if (!$whmcsService) return false;
|
|
||||||
|
|
||||||
$cp = $this->getCP($whmcsService->server);
|
|
||||||
if (!$cp) return false;
|
|
||||||
|
|
||||||
$request = $this->initCurl($cp['token']);
|
|
||||||
$data = $request->get($cp['url'] . '/selfService/currencies');
|
|
||||||
|
|
||||||
Log::insert(__FUNCTION__, $request->getRequestInfo(), $data);
|
|
||||||
|
|
||||||
if ($request->getRequestInfo('http_code') == 200) {
|
|
||||||
$result = json_decode($data, true);
|
|
||||||
Cache::set($cacheKey, $result, 1800);
|
|
||||||
return $result;
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Decodes a response from JSON into an associative array.
|
* Decodes a response from JSON into an associative array.
|
||||||
*
|
*
|
||||||
* @param string $response
|
|
||||||
*
|
*
|
||||||
* @return array
|
|
||||||
* @throws \JsonException
|
* @throws \JsonException
|
||||||
*/
|
*/
|
||||||
public function decodeResponseFromJson(string $response): array
|
public function decodeResponseFromJson(string $response): array
|
||||||
|
|||||||
@@ -2,6 +2,12 @@
|
|||||||
|
|
||||||
namespace WHMCS\Module\Server\VirtFusionDirect;
|
namespace WHMCS\Module\Server\VirtFusionDirect;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Extends Module to handle the WHMCS service lifecycle for VirtFusion servers.
|
||||||
|
*
|
||||||
|
* Responsibilities include: provisioning (create, suspend, unsuspend, terminate),
|
||||||
|
* package changes, usage updates, client area rendering, and admin tab fields.
|
||||||
|
*/
|
||||||
class ModuleFunctions extends Module
|
class ModuleFunctions extends Module
|
||||||
{
|
{
|
||||||
public function __construct()
|
public function __construct()
|
||||||
@@ -10,13 +16,13 @@ class ModuleFunctions extends Module
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
* Provision a new VirtFusion server for a WHMCS service.
|
||||||
*
|
*
|
||||||
* CREATE SERVER
|
* Ensures a matching VirtFusion user exists (creating one if needed), then creates
|
||||||
*
|
* the server and triggers the OS build via ConfigureService::initServerBuild().
|
||||||
* Before creating a server, we check to see if a user exists in VirtFusion that matches
|
|
||||||
* the WHMCS user. If it matches, We move on to create the server, if not, we attempt to
|
|
||||||
* create a user to assign to the new server.
|
|
||||||
*
|
*
|
||||||
|
* @param array $params WHMCS service parameters
|
||||||
|
* @return string 'success' or an error message
|
||||||
*/
|
*/
|
||||||
public function createAccount($params)
|
public function createAccount($params)
|
||||||
{
|
{
|
||||||
@@ -69,9 +75,9 @@ class ModuleFunctions extends Module
|
|||||||
$request = $this->initCurl($cp['token']);
|
$request = $this->initCurl($cp['token']);
|
||||||
|
|
||||||
$userData = [
|
$userData = [
|
||||||
"name" => $user->firstname . ' ' . $user->lastname,
|
'name' => $user->firstname . ' ' . $user->lastname,
|
||||||
"email" => $user->email,
|
'email' => $user->email,
|
||||||
"extRelationId" => $user->id,
|
'extRelationId' => $user->id,
|
||||||
];
|
];
|
||||||
|
|
||||||
// Enable self-service billing if configured
|
// Enable self-service billing if configured
|
||||||
@@ -100,7 +106,6 @@ class ModuleFunctions extends Module
|
|||||||
/**
|
/**
|
||||||
* A user is available. We can now attempt to create a server.
|
* A user is available. We can now attempt to create a server.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
$configOptionDefaultNaming = [
|
$configOptionDefaultNaming = [
|
||||||
'ipv4' => 'IPv4',
|
'ipv4' => 'IPv4',
|
||||||
'packageId' => 'Package',
|
'packageId' => 'Package',
|
||||||
@@ -122,10 +127,10 @@ class ModuleFunctions extends Module
|
|||||||
}
|
}
|
||||||
|
|
||||||
$options = [
|
$options = [
|
||||||
"packageId" => (int) $params['configoption2'],
|
'packageId' => (int) $params['configoption2'],
|
||||||
"userId" => $data->data->id,
|
'userId' => $data->data->id,
|
||||||
"hypervisorId" => (int) $params['configoption1'],
|
'hypervisorId' => (int) $params['configoption1'],
|
||||||
"ipv4" => (int) $params['configoption3'],
|
'ipv4' => (int) $params['configoption3'],
|
||||||
];
|
];
|
||||||
|
|
||||||
if (array_key_exists('configoptions', $params)) {
|
if (array_key_exists('configoptions', $params)) {
|
||||||
@@ -159,7 +164,7 @@ class ModuleFunctions extends Module
|
|||||||
$this->updateWhmcsServiceParamsOnServerObject($params['serviceid'], $data);
|
$this->updateWhmcsServiceParamsOnServerObject($params['serviceid'], $data);
|
||||||
|
|
||||||
// If the server is created successfully, we can initialize the server build.
|
// If the server is created successfully, we can initialize the server build.
|
||||||
$cs = new ConfigureService();
|
$cs = new ConfigureService;
|
||||||
$vfUserId = isset($data->data->owner->id) ? (int) $data->data->owner->id : null;
|
$vfUserId = isset($data->data->owner->id) ? (int) $data->data->owner->id : null;
|
||||||
$cs->initServerBuild($data->data->id, $params, $vfUserId);
|
$cs->initServerBuild($data->data->id, $params, $vfUserId);
|
||||||
|
|
||||||
@@ -171,30 +176,40 @@ class ModuleFunctions extends Module
|
|||||||
if (isset($data->msg)) {
|
if (isset($data->msg)) {
|
||||||
return $data->msg;
|
return $data->msg;
|
||||||
}
|
}
|
||||||
|
|
||||||
return 'Server creation failed. VirtFusion API returned HTTP ' . $request->getRequestInfo('http_code');
|
return 'Server creation failed. VirtFusion API returned HTTP ' . $request->getRequestInfo('http_code');
|
||||||
}
|
}
|
||||||
} catch (\Exception $e) {
|
} catch (\Exception $e) {
|
||||||
Log::insert(__FUNCTION__, $params, $e->getMessage());
|
Log::insert(__FUNCTION__, $params, $e->getMessage());
|
||||||
|
|
||||||
return $e->getMessage();
|
return $e->getMessage();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Allows changing of the package of a server
|
* Change the VirtFusion package assigned to a server and apply resource modifications.
|
||||||
*
|
*
|
||||||
* @param $params
|
* Updates the package via the API, then individually adjusts memory, CPU, and bandwidth
|
||||||
* @return string
|
* if those configurable options are present.
|
||||||
|
*
|
||||||
|
* @param array $params WHMCS service parameters
|
||||||
|
* @return string 'success' or an error message
|
||||||
*/
|
*/
|
||||||
public function changePackage($params)
|
public function changePackage($params)
|
||||||
{
|
{
|
||||||
|
try {
|
||||||
$service = Database::getSystemService($params['serviceid']);
|
$service = Database::getSystemService($params['serviceid']);
|
||||||
|
|
||||||
if ($service) {
|
if ($service) {
|
||||||
$whmcsService = Database::getWhmcsService($params['serviceid']);
|
$whmcsService = Database::getWhmcsService($params['serviceid']);
|
||||||
if (!$whmcsService) return 'WHMCS service record not found.';
|
if (! $whmcsService) {
|
||||||
|
return 'WHMCS service record not found.';
|
||||||
|
}
|
||||||
|
|
||||||
$cp = $this->getCP($whmcsService->server);
|
$cp = $this->getCP($whmcsService->server);
|
||||||
if (!$cp) return 'No control server found.';
|
if (! $cp) {
|
||||||
|
return 'No control server found.';
|
||||||
|
}
|
||||||
|
|
||||||
$request = $this->initCurl($cp['token']);
|
$request = $this->initCurl($cp['token']);
|
||||||
$data = $request->put($cp['url'] . '/servers/' . (int) $service->server_id . '/package/' . (int) $params['configoption2']);
|
$data = $request->put($cp['url'] . '/servers/' . (int) $service->server_id . '/package/' . (int) $params['configoption2']);
|
||||||
@@ -212,6 +227,7 @@ class ModuleFunctions extends Module
|
|||||||
if (isset($data->msg)) {
|
if (isset($data->msg)) {
|
||||||
return $data->msg;
|
return $data->msg;
|
||||||
}
|
}
|
||||||
|
|
||||||
return 'The server is currently locked. Please try again later.';
|
return 'The server is currently locked. Please try again later.';
|
||||||
default:
|
default:
|
||||||
return 'Update package request failed. VirtFusion API returned HTTP ' . $request->getRequestInfo('http_code');
|
return 'Update package request failed. VirtFusion API returned HTTP ' . $request->getRequestInfo('http_code');
|
||||||
@@ -244,29 +260,40 @@ class ModuleFunctions extends Module
|
|||||||
|
|
||||||
return 'success';
|
return 'success';
|
||||||
}
|
}
|
||||||
|
|
||||||
return 'Service not found in module database.';
|
return 'Service not found in module database.';
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
Log::insert(__FUNCTION__, $params, $e->getMessage());
|
||||||
|
|
||||||
|
return $e->getMessage();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
* Delete a VirtFusion server, applying the default 5-minute grace period before destruction.
|
||||||
*
|
*
|
||||||
* TERMINATE SERVER
|
* On success, removes the service record from the module database and clears WHMCS service fields.
|
||||||
*
|
* If VirtFusion reports the server is already gone (404 + "server not found"), treats it as success.
|
||||||
* When requesting to terminate a server in VirtFusion, we leave it set to
|
|
||||||
* the default 5-minute delay allowing to un-terminate in VirtFusion if the
|
|
||||||
* request was done in error.
|
|
||||||
*
|
*
|
||||||
|
* @param array $params WHMCS service parameters
|
||||||
|
* @return string 'success' or an error message
|
||||||
*/
|
*/
|
||||||
public function terminateAccount($params)
|
public function terminateAccount($params)
|
||||||
{
|
{
|
||||||
|
try {
|
||||||
$service = Database::getSystemService($params['serviceid']);
|
$service = Database::getSystemService($params['serviceid']);
|
||||||
|
|
||||||
if ($service) {
|
if ($service) {
|
||||||
|
|
||||||
$whmcsService = Database::getWhmcsService($params['serviceid']);
|
$whmcsService = Database::getWhmcsService($params['serviceid']);
|
||||||
if (!$whmcsService) return 'WHMCS service record not found.';
|
if (! $whmcsService) {
|
||||||
|
return 'WHMCS service record not found.';
|
||||||
|
}
|
||||||
|
|
||||||
$cp = $this->getCP($whmcsService->server);
|
$cp = $this->getCP($whmcsService->server);
|
||||||
if (!$cp) return 'No control server found.';
|
if (! $cp) {
|
||||||
|
return 'No control server found.';
|
||||||
|
}
|
||||||
|
|
||||||
$request = $this->initCurl($cp['token']);
|
$request = $this->initCurl($cp['token']);
|
||||||
$data = $request->delete($cp['url'] . '/servers/' . (int) $service->server_id);
|
$data = $request->delete($cp['url'] . '/servers/' . (int) $service->server_id);
|
||||||
@@ -279,12 +306,14 @@ class ModuleFunctions extends Module
|
|||||||
case 204:
|
case 204:
|
||||||
Database::deleteSystemService($params['serviceid']);
|
Database::deleteSystemService($params['serviceid']);
|
||||||
$this->updateWhmcsServiceParamsOnDestroy($params['serviceid']);
|
$this->updateWhmcsServiceParamsOnDestroy($params['serviceid']);
|
||||||
|
|
||||||
return 'success';
|
return 'success';
|
||||||
|
|
||||||
case 404:
|
case 404:
|
||||||
if (isset($data->msg)) {
|
if (isset($data->msg)) {
|
||||||
if ($data->msg == 'server not found') {
|
if ($data->msg == 'server not found') {
|
||||||
Database::deleteSystemService($params['serviceid']);
|
Database::deleteSystemService($params['serviceid']);
|
||||||
|
|
||||||
return 'success';
|
return 'success';
|
||||||
} else {
|
} else {
|
||||||
return 'VirtFusion returned 404: ' . $data->msg;
|
return 'VirtFusion returned 404: ' . $data->msg;
|
||||||
@@ -297,29 +326,39 @@ class ModuleFunctions extends Module
|
|||||||
return 'Termination request failed. VirtFusion API returned HTTP ' . $request->getRequestInfo('http_code');
|
return 'Termination request failed. VirtFusion API returned HTTP ' . $request->getRequestInfo('http_code');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return 'Service not found in module database. Has termination already been run?';
|
return 'Service not found in module database. Has termination already been run?';
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
Log::insert(__FUNCTION__, $params, $e->getMessage());
|
||||||
|
|
||||||
|
return $e->getMessage();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
* Suspend a VirtFusion server, queuing the action if another operation is in progress.
|
||||||
*
|
*
|
||||||
* SUSPEND SERVER
|
* Returns 'success' whether the server is suspended immediately or queued for suspension.
|
||||||
*
|
|
||||||
* When requesting to suspend a server in VirtFusion it may be delayed if another action
|
|
||||||
* is being processed. This function will return success if the server is either suspended
|
|
||||||
* now or has been queued for suspension.
|
|
||||||
*
|
*
|
||||||
|
* @param array $params WHMCS service parameters
|
||||||
|
* @return string 'success' or an error message
|
||||||
*/
|
*/
|
||||||
public function suspendAccount($params)
|
public function suspendAccount($params)
|
||||||
{
|
{
|
||||||
|
try {
|
||||||
$service = Database::getSystemService($params['serviceid']);
|
$service = Database::getSystemService($params['serviceid']);
|
||||||
|
|
||||||
if ($service) {
|
if ($service) {
|
||||||
|
|
||||||
$whmcsService = Database::getWhmcsService($params['serviceid']);
|
$whmcsService = Database::getWhmcsService($params['serviceid']);
|
||||||
if (!$whmcsService) return 'WHMCS service record not found.';
|
if (! $whmcsService) {
|
||||||
|
return 'WHMCS service record not found.';
|
||||||
|
}
|
||||||
|
|
||||||
$cp = $this->getCP($whmcsService->server);
|
$cp = $this->getCP($whmcsService->server);
|
||||||
if (!$cp) return 'No control server found.';
|
if (! $cp) {
|
||||||
|
return 'No control server found.';
|
||||||
|
}
|
||||||
|
|
||||||
$request = $this->initCurl($cp['token']);
|
$request = $this->initCurl($cp['token']);
|
||||||
$data = $request->post($cp['url'] . '/servers/' . (int) $service->server_id . '/suspend');
|
$data = $request->post($cp['url'] . '/servers/' . (int) $service->server_id . '/suspend');
|
||||||
@@ -336,6 +375,7 @@ class ModuleFunctions extends Module
|
|||||||
if (isset($data->msg)) {
|
if (isset($data->msg)) {
|
||||||
if ($data->msg == 'server not found') {
|
if ($data->msg == 'server not found') {
|
||||||
Database::deleteSystemService($params['serviceid']);
|
Database::deleteSystemService($params['serviceid']);
|
||||||
|
|
||||||
return 'success';
|
return 'success';
|
||||||
} else {
|
} else {
|
||||||
return 'VirtFusion returned 404: ' . $data->msg;
|
return 'VirtFusion returned 404: ' . $data->msg;
|
||||||
@@ -347,26 +387,46 @@ class ModuleFunctions extends Module
|
|||||||
if (isset($data->msg)) {
|
if (isset($data->msg)) {
|
||||||
return $data->msg;
|
return $data->msg;
|
||||||
}
|
}
|
||||||
|
|
||||||
return 'The server is currently locked. Please try again later.';
|
return 'The server is currently locked. Please try again later.';
|
||||||
|
|
||||||
default:
|
default:
|
||||||
return 'Suspend request failed. VirtFusion API returned HTTP ' . $request->getRequestInfo('http_code');
|
return 'Suspend request failed. VirtFusion API returned HTTP ' . $request->getRequestInfo('http_code');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return 'Service not found in module database.';
|
return 'Service not found in module database.';
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
Log::insert(__FUNCTION__, $params, $e->getMessage());
|
||||||
|
|
||||||
|
return $e->getMessage();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function updateServerObject($params)
|
/**
|
||||||
|
* Refresh the cached server object by fetching fresh data from the VirtFusion API.
|
||||||
|
*
|
||||||
|
* Updates both the module database record and the WHMCS service fields (IP, username, etc.).
|
||||||
|
*
|
||||||
|
* @param array $params WHMCS service parameters
|
||||||
|
* @return string 'success' or an error message
|
||||||
|
*/
|
||||||
|
public function updateServerObject($params)
|
||||||
{
|
{
|
||||||
|
try {
|
||||||
$service = Database::getSystemService($params['serviceid']);
|
$service = Database::getSystemService($params['serviceid']);
|
||||||
|
|
||||||
if ($service) {
|
if ($service) {
|
||||||
|
|
||||||
$whmcsService = Database::getWhmcsService($params['serviceid']);
|
$whmcsService = Database::getWhmcsService($params['serviceid']);
|
||||||
if (!$whmcsService) return 'WHMCS service record not found.';
|
if (! $whmcsService) {
|
||||||
|
return 'WHMCS service record not found.';
|
||||||
|
}
|
||||||
|
|
||||||
$cp = $this->getCP($whmcsService->server);
|
$cp = $this->getCP($whmcsService->server);
|
||||||
if (!$cp) return 'No control server found.';
|
if (! $cp) {
|
||||||
|
return 'No control server found.';
|
||||||
|
}
|
||||||
|
|
||||||
$request = $this->initCurl($cp['token']);
|
$request = $this->initCurl($cp['token']);
|
||||||
$data = $request->get($cp['url'] . '/servers/' . (int) $service->server_id);
|
$data = $request->get($cp['url'] . '/servers/' . (int) $service->server_id);
|
||||||
@@ -386,20 +446,38 @@ class ModuleFunctions extends Module
|
|||||||
return 'Request failed. VirtFusion API returned HTTP ' . $request->getRequestInfo('http_code');
|
return 'Request failed. VirtFusion API returned HTTP ' . $request->getRequestInfo('http_code');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return 'Service not found in module database.';
|
return 'Service not found in module database.';
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
Log::insert(__FUNCTION__, $params, $e->getMessage());
|
||||||
|
|
||||||
|
return $e->getMessage();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Unsuspend a VirtFusion server, queuing the action if another operation is in progress.
|
||||||
|
*
|
||||||
|
* Returns 'success' whether the server is unsuspended immediately or queued for unsuspension.
|
||||||
|
*
|
||||||
|
* @param array $params WHMCS service parameters
|
||||||
|
* @return string 'success' or an error message
|
||||||
|
*/
|
||||||
public function unsuspendAccount($params)
|
public function unsuspendAccount($params)
|
||||||
{
|
{
|
||||||
|
try {
|
||||||
$service = Database::getSystemService($params['serviceid']);
|
$service = Database::getSystemService($params['serviceid']);
|
||||||
|
|
||||||
if ($service) {
|
if ($service) {
|
||||||
$whmcsService = Database::getWhmcsService($params['serviceid']);
|
$whmcsService = Database::getWhmcsService($params['serviceid']);
|
||||||
if (!$whmcsService) return 'WHMCS service record not found.';
|
if (! $whmcsService) {
|
||||||
|
return 'WHMCS service record not found.';
|
||||||
|
}
|
||||||
|
|
||||||
$cp = $this->getCP($whmcsService->server);
|
$cp = $this->getCP($whmcsService->server);
|
||||||
if (!$cp) return 'No control server found.';
|
if (! $cp) {
|
||||||
|
return 'No control server found.';
|
||||||
|
}
|
||||||
|
|
||||||
$request = $this->initCurl($cp['token']);
|
$request = $this->initCurl($cp['token']);
|
||||||
$data = $request->post($cp['url'] . '/servers/' . (int) $service->server_id . '/unsuspend');
|
$data = $request->post($cp['url'] . '/servers/' . (int) $service->server_id . '/unsuspend');
|
||||||
@@ -416,6 +494,7 @@ class ModuleFunctions extends Module
|
|||||||
if (isset($data->msg)) {
|
if (isset($data->msg)) {
|
||||||
if ($data->msg == 'server not found') {
|
if ($data->msg == 'server not found') {
|
||||||
Database::deleteSystemService($params['serviceid']);
|
Database::deleteSystemService($params['serviceid']);
|
||||||
|
|
||||||
return 'success';
|
return 'success';
|
||||||
} else {
|
} else {
|
||||||
return 'VirtFusion returned 404: ' . $data->msg;
|
return 'VirtFusion returned 404: ' . $data->msg;
|
||||||
@@ -427,17 +506,34 @@ class ModuleFunctions extends Module
|
|||||||
if (isset($data->msg)) {
|
if (isset($data->msg)) {
|
||||||
return $data->msg;
|
return $data->msg;
|
||||||
}
|
}
|
||||||
|
|
||||||
return 'The server is currently locked. Please try again later.';
|
return 'The server is currently locked. Please try again later.';
|
||||||
|
|
||||||
default:
|
default:
|
||||||
return 'Unsuspend request failed. VirtFusion API returned HTTP ' . $request->getRequestInfo('http_code');
|
return 'Unsuspend request failed. VirtFusion API returned HTTP ' . $request->getRequestInfo('http_code');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return 'Service not found in module database.';
|
return 'Service not found in module database.';
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
Log::insert(__FUNCTION__, $params, $e->getMessage());
|
||||||
|
|
||||||
|
return $e->getMessage();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generate the admin Services tab custom fields for a VirtFusion service.
|
||||||
|
*
|
||||||
|
* Returns fields for Server ID (editable), Server Info, Server Object (JSON viewer),
|
||||||
|
* and Options (action buttons), omitting Options for terminated services.
|
||||||
|
*
|
||||||
|
* @param array $params WHMCS service parameters
|
||||||
|
* @return array Associative array of field label => HTML content
|
||||||
|
*/
|
||||||
public function adminServicesTabFields($params)
|
public function adminServicesTabFields($params)
|
||||||
{
|
{
|
||||||
|
try {
|
||||||
$serverId = '';
|
$serverId = '';
|
||||||
$serverObject = '';
|
$serverObject = '';
|
||||||
|
|
||||||
@@ -459,10 +555,25 @@ class ModuleFunctions extends Module
|
|||||||
}
|
}
|
||||||
|
|
||||||
return $fields;
|
return $fields;
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
Log::insert(__FUNCTION__, $params, $e->getMessage());
|
||||||
|
|
||||||
|
return [];
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Save the admin Services tab custom fields for a VirtFusion service.
|
||||||
|
*
|
||||||
|
* Deletes the module database record if the Server ID field is cleared,
|
||||||
|
* or updates it with the new integer server ID if a value is provided.
|
||||||
|
*
|
||||||
|
* @param array $params WHMCS service parameters
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
public function adminServicesTabFieldsSave($params)
|
public function adminServicesTabFieldsSave($params)
|
||||||
{
|
{
|
||||||
|
try {
|
||||||
if (! isset($_POST['modulefields'][0]) || $_POST['modulefields'][0] === '') {
|
if (! isset($_POST['modulefields'][0]) || $_POST['modulefields'][0] === '') {
|
||||||
Database::deleteSystemService($params['serviceid']);
|
Database::deleteSystemService($params['serviceid']);
|
||||||
} else {
|
} else {
|
||||||
@@ -471,13 +582,19 @@ class ModuleFunctions extends Module
|
|||||||
Database::updateSystemServiceServerId($params['serviceid'], $serverId);
|
Database::updateSystemServiceServerId($params['serviceid'], $serverId);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
Log::insert(__FUNCTION__, $params, $e->getMessage());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Validate server creation parameters via dry run.
|
* Perform a dry-run server creation to validate the current product configuration.
|
||||||
*
|
*
|
||||||
* @param array $params WHMCS service params
|
* Used by the WHMCS "Test Connection" button to confirm that the package, hypervisor,
|
||||||
* @return string 'success' or error message
|
* and IP settings are accepted by the VirtFusion API without creating a server.
|
||||||
|
*
|
||||||
|
* @param array $params WHMCS service parameters
|
||||||
|
* @return string 'success' or an error message
|
||||||
*/
|
*/
|
||||||
public function validateServerConfig($params)
|
public function validateServerConfig($params)
|
||||||
{
|
{
|
||||||
@@ -490,9 +607,9 @@ class ModuleFunctions extends Module
|
|||||||
}
|
}
|
||||||
|
|
||||||
$options = [
|
$options = [
|
||||||
"packageId" => (int) $params['configoption2'],
|
'packageId' => (int) $params['configoption2'],
|
||||||
"hypervisorId" => (int) $params['configoption1'],
|
'hypervisorId' => (int) $params['configoption1'],
|
||||||
"ipv4" => (int) $params['configoption3'],
|
'ipv4' => (int) $params['configoption3'],
|
||||||
];
|
];
|
||||||
|
|
||||||
// We need a userId for dry run - use the service owner
|
// We need a userId for dry run - use the service owner
|
||||||
@@ -517,6 +634,16 @@ class ModuleFunctions extends Module
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Render the client area overview tab for a VirtFusion service.
|
||||||
|
*
|
||||||
|
* Returns the template name and variables (system URL, service status, hostname,
|
||||||
|
* self-service mode) needed by the Smarty overview template. Falls back to an
|
||||||
|
* error template on any exception.
|
||||||
|
*
|
||||||
|
* @param array $params WHMCS service parameters
|
||||||
|
* @return array Template name and variables for WHMCS to render
|
||||||
|
*/
|
||||||
public function clientArea($params)
|
public function clientArea($params)
|
||||||
{
|
{
|
||||||
$serverHostname = null;
|
$serverHostname = null;
|
||||||
|
|||||||
@@ -2,8 +2,17 @@
|
|||||||
|
|
||||||
namespace WHMCS\Module\Server\VirtFusionDirect;
|
namespace WHMCS\Module\Server\VirtFusionDirect;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Transforms a VirtFusion API server response into a flat key-value array for Smarty templates and admin display.
|
||||||
|
*/
|
||||||
class ServerResource
|
class ServerResource
|
||||||
{
|
{
|
||||||
|
/**
|
||||||
|
* Normalise a VirtFusion API server response into a flat associative array.
|
||||||
|
*
|
||||||
|
* @param object $data VirtFusion API server response object (with a `data` property)
|
||||||
|
* @return array Flat associative array containing server name, hostname, resources, network info, and usage
|
||||||
|
*/
|
||||||
public function process($data)
|
public function process($data)
|
||||||
{
|
{
|
||||||
$server = json_decode(json_encode($data->data), true);
|
$server = json_decode(json_encode($data->data), true);
|
||||||
|
|||||||
@@ -9,16 +9,6 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
/* Buttons */
|
/* Buttons */
|
||||||
.vf-button {
|
|
||||||
font-size: 0.8rem;
|
|
||||||
padding: 0.95rem 1.5rem;
|
|
||||||
font-weight: 600;
|
|
||||||
}
|
|
||||||
.vf-button-small {
|
|
||||||
font-size: 0.8rem;
|
|
||||||
padding: 0.75rem 1.3rem;
|
|
||||||
font-weight: 500;
|
|
||||||
}
|
|
||||||
.vf-spinner-margin {
|
.vf-spinner-margin {
|
||||||
margin-right: 7px;
|
margin-right: 7px;
|
||||||
}
|
}
|
||||||
@@ -84,9 +74,7 @@
|
|||||||
}
|
}
|
||||||
#vf-server-info-error {
|
#vf-server-info-error {
|
||||||
display: none;
|
display: none;
|
||||||
}
|
margin: 10px;
|
||||||
#vf-data-server-traffic-sep {
|
|
||||||
display: inline;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Skeleton Loading */
|
/* Skeleton Loading */
|
||||||
@@ -159,11 +147,6 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Error message spacing */
|
|
||||||
#vf-server-info-error {
|
|
||||||
margin: 10px;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Network / IP Management */
|
/* Network / IP Management */
|
||||||
.vf-ip-row {
|
.vf-ip-row {
|
||||||
display: flex;
|
display: flex;
|
||||||
@@ -286,6 +269,8 @@
|
|||||||
.vf-os-category-icon {
|
.vf-os-category-icon {
|
||||||
width: 28px;
|
width: 28px;
|
||||||
height: 28px;
|
height: 28px;
|
||||||
|
min-width: 28px;
|
||||||
|
min-height: 28px;
|
||||||
border-radius: 6px;
|
border-radius: 6px;
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
@@ -294,6 +279,14 @@
|
|||||||
font-weight: 700;
|
font-weight: 700;
|
||||||
font-size: 0.85rem;
|
font-size: 0.85rem;
|
||||||
flex-shrink: 0;
|
flex-shrink: 0;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
.vf-os-category-icon img {
|
||||||
|
max-width: 100%;
|
||||||
|
max-height: 100%;
|
||||||
|
width: auto;
|
||||||
|
height: auto;
|
||||||
|
object-fit: contain;
|
||||||
}
|
}
|
||||||
.vf-os-category-arrow {
|
.vf-os-category-arrow {
|
||||||
margin-left: auto;
|
margin-left: auto;
|
||||||
@@ -314,6 +307,7 @@
|
|||||||
padding: 10px 8px;
|
padding: 10px 8px;
|
||||||
text-align: center;
|
text-align: center;
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
|
overflow: hidden;
|
||||||
transition: border-color 0.15s, background-color 0.15s, box-shadow 0.15s;
|
transition: border-color 0.15s, background-color 0.15s, box-shadow 0.15s;
|
||||||
}
|
}
|
||||||
.vf-os-card:hover {
|
.vf-os-card:hover {
|
||||||
@@ -338,8 +332,12 @@
|
|||||||
color: #fff;
|
color: #fff;
|
||||||
font-weight: 700;
|
font-weight: 700;
|
||||||
font-size: 1.1rem;
|
font-size: 1.1rem;
|
||||||
|
overflow: hidden;
|
||||||
|
flex-shrink: 0;
|
||||||
}
|
}
|
||||||
.vf-os-icon img {
|
.vf-os-icon img {
|
||||||
|
max-width: 100%;
|
||||||
|
max-height: 100%;
|
||||||
width: 24px;
|
width: 24px;
|
||||||
height: 24px;
|
height: 24px;
|
||||||
object-fit: contain;
|
object-fit: contain;
|
||||||
@@ -364,7 +362,7 @@
|
|||||||
border-radius: 3px;
|
border-radius: 3px;
|
||||||
margin-top: 3px;
|
margin-top: 3px;
|
||||||
}
|
}
|
||||||
.vf-os-details {
|
#vf-os-details {
|
||||||
border-top: 1px solid #dee2e6;
|
border-top: 1px solid #dee2e6;
|
||||||
padding-top: 10px;
|
padding-top: 10px;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -328,13 +328,27 @@ function vfRenderOsGallery(container, data, hiddenInput) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var baseUrl = data.baseUrl || "";
|
||||||
|
|
||||||
$.each(data.categories, function (ci, category) {
|
$.each(data.categories, function (ci, category) {
|
||||||
var section = $('<div class="vf-os-category"></div>').attr("data-category", ci);
|
var section = $('<div class="vf-os-category"></div>').attr("data-category", ci);
|
||||||
var brandColor = vfGetBrandColor(category.name);
|
var brandColor = vfGetBrandColor(category.name);
|
||||||
|
|
||||||
// Accordion header
|
// Accordion header
|
||||||
var header = $('<div class="vf-os-category-header"></div>');
|
var header = $('<div class="vf-os-category-header"></div>');
|
||||||
var iconSpan = $('<span class="vf-os-category-icon"></span>').css("background", brandColor).text((category.name || "?")[0].toUpperCase());
|
var iconSpan = $('<span class="vf-os-category-icon"></span>');
|
||||||
|
if (category.icon && baseUrl) {
|
||||||
|
var catImg = $('<img alt="">').attr("src", baseUrl + "/img/logo/" + encodeURIComponent(category.icon));
|
||||||
|
catImg.on("error", function () {
|
||||||
|
$(this).parent().css("background", brandColor);
|
||||||
|
$(this).replaceWith($('<span></span>').text((category.name || "?")[0].toUpperCase()));
|
||||||
|
});
|
||||||
|
iconSpan.append(catImg);
|
||||||
|
} else if (category.name === "Other") {
|
||||||
|
iconSpan.css("background", "#6c757d").html('<svg width="16" height="16" viewBox="0 0 16 16" fill="#fff"><path d="M3 2a1 1 0 0 0-1 1v10a1 1 0 0 0 1 1h10a1 1 0 0 0 1-1V3a1 1 0 0 0-1-1H3zm1 2h8v2H4V4zm0 3h8v1H4V7zm0 2h5v1H4V9z"/></svg>');
|
||||||
|
} else {
|
||||||
|
iconSpan.css("background", brandColor).text((category.name || "?")[0].toUpperCase());
|
||||||
|
}
|
||||||
var titleSpan = $('<span></span>').text(category.name + " (" + category.templates.length + ")");
|
var titleSpan = $('<span></span>').text(category.name + " (" + category.templates.length + ")");
|
||||||
var arrow = $('<span class="vf-os-category-arrow">' + (ci === 0 ? '▼' : '▶') + '</span>');
|
var arrow = $('<span class="vf-os-category-arrow">' + (ci === 0 ? '▼' : '▶') + '</span>');
|
||||||
header.append(iconSpan).append(titleSpan).append(arrow);
|
header.append(iconSpan).append(titleSpan).append(arrow);
|
||||||
@@ -363,8 +377,18 @@ function vfRenderOsGallery(container, data, hiddenInput) {
|
|||||||
.attr("data-search", label.toLowerCase());
|
.attr("data-search", label.toLowerCase());
|
||||||
if (tpl.eol) card.addClass("vf-os-card-eol");
|
if (tpl.eol) card.addClass("vf-os-card-eol");
|
||||||
|
|
||||||
var iconDiv = $('<div class="vf-os-icon"></div>').css("background", brandColor);
|
var iconDiv = $('<div class="vf-os-icon"></div>');
|
||||||
|
if (tpl.icon && baseUrl) {
|
||||||
|
var tplImg = $('<img alt="">').attr("src", baseUrl + "/img/logo/" + encodeURIComponent(tpl.icon));
|
||||||
|
tplImg.on("error", function () {
|
||||||
|
$(this).parent().css("background", brandColor);
|
||||||
|
$(this).replaceWith($('<span></span>').text((tpl.name || "?")[0].toUpperCase()));
|
||||||
|
});
|
||||||
|
iconDiv.append(tplImg);
|
||||||
|
} else {
|
||||||
|
iconDiv.css("background", brandColor);
|
||||||
iconDiv.append($('<span></span>').text((tpl.name || "?")[0].toUpperCase()));
|
iconDiv.append($('<span></span>').text((tpl.name || "?")[0].toUpperCase()));
|
||||||
|
}
|
||||||
|
|
||||||
card.append(iconDiv);
|
card.append(iconDiv);
|
||||||
card.append($('<div class="vf-os-label"></div>').text(tpl.name));
|
card.append($('<div class="vf-os-label"></div>').text(tpl.name));
|
||||||
@@ -639,31 +663,6 @@ function vfLoadSelfServiceUsage(serviceId, systemUrl) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function vfLoadSelfServiceReport(serviceId, systemUrl) {
|
|
||||||
$.ajax({
|
|
||||||
type: "GET",
|
|
||||||
dataType: "json",
|
|
||||||
url: vfUrl(systemUrl, serviceId, "selfServiceReport")
|
|
||||||
}).done(function (response) {
|
|
||||||
if (response.success && response.data) {
|
|
||||||
var data = response.data.data || response.data;
|
|
||||||
var tbody = $("#vf-ss-usage-table");
|
|
||||||
tbody.empty();
|
|
||||||
|
|
||||||
var items = data.items || data.report || [];
|
|
||||||
if (Array.isArray(items) && items.length > 0) {
|
|
||||||
$.each(items, function (i, item) {
|
|
||||||
var desc = item.description || item.name || "Item";
|
|
||||||
var cost = item.cost !== undefined ? parseFloat(item.cost).toFixed(2) : "-";
|
|
||||||
tbody.append('<tr><td>' + $('<span>').text(desc).html() + '</td><td class="text-right">' + $('<span>').text(cost).html() + '</td></tr>');
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
tbody.append('<tr><td colspan="2" class="text-muted">No report data available</td></tr>');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function vfAddCredit(serviceId, systemUrl) {
|
function vfAddCredit(serviceId, systemUrl) {
|
||||||
var amount = $("#vf-ss-credit-amount").val();
|
var amount = $("#vf-ss-credit-amount").val();
|
||||||
var alertDiv = $("#vf-selfservice-alert");
|
var alertDiv = $("#vf-selfservice-alert");
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
<link href="{$systemURL}modules/servers/VirtFusionDirect/templates/css/module.css?v=20260319" rel="stylesheet">
|
<link href="{$systemURL}modules/servers/VirtFusionDirect/templates/css/module.css?v={$smarty.now}" rel="stylesheet">
|
||||||
<script src="{$systemURL}modules/servers/VirtFusionDirect/templates/js/module.js?v=20260319"></script>
|
<script src="{$systemURL}modules/servers/VirtFusionDirect/templates/js/module.js?v={$smarty.now}"></script>
|
||||||
|
|
||||||
{if $serviceStatus eq 'Active'}
|
{if $serviceStatus eq 'Active'}
|
||||||
|
|
||||||
|
|||||||
24
pint.json
Normal file
24
pint.json
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
{
|
||||||
|
"preset": "laravel",
|
||||||
|
"rules": {
|
||||||
|
"declare_strict_types": false,
|
||||||
|
"blank_line_before_statement": {
|
||||||
|
"statements": ["return", "throw", "try"]
|
||||||
|
},
|
||||||
|
"concat_space": {
|
||||||
|
"spacing": "one"
|
||||||
|
},
|
||||||
|
"ordered_imports": {
|
||||||
|
"sort_algorithm": "alpha"
|
||||||
|
},
|
||||||
|
"single_quote": true,
|
||||||
|
"no_unused_imports": true,
|
||||||
|
"trailing_comma_in_multiline": {
|
||||||
|
"elements": ["arrays", "arguments"]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"exclude": [
|
||||||
|
"vendor",
|
||||||
|
"templates"
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -1,33 +0,0 @@
|
|||||||
#!/bin/bash
|
|
||||||
# Generate API endpoint documentation from PHP source files
|
|
||||||
# Usage: bash scripts/generate-endpoint-doc.sh > docs/API-ENDPOINTS.md
|
|
||||||
|
|
||||||
MODULE_DIR="modules/servers/VirtFusionDirect"
|
|
||||||
|
|
||||||
echo "# VirtFusion WHMCS Module — API Endpoints"
|
|
||||||
echo ""
|
|
||||||
echo "Auto-generated from source code. Do not edit manually."
|
|
||||||
echo ""
|
|
||||||
echo "| Endpoint Pattern | HTTP Method | PHP File | Function |"
|
|
||||||
echo "|---|---|---|---|"
|
|
||||||
|
|
||||||
# Extract API URL patterns from PHP files
|
|
||||||
grep -rn "->get\|->post\|->put\|->patch\|->delete" "$MODULE_DIR/lib/" 2>/dev/null | \
|
|
||||||
grep -oP "(?<=>)(get|post|put|patch|delete)\(.*?'[^']*'" | \
|
|
||||||
while IFS= read -r line; do
|
|
||||||
method=$(echo "$line" | grep -oP "^(get|post|put|patch|delete)" | tr '[:lower:]' '[:upper:]')
|
|
||||||
url=$(echo "$line" | grep -oP "'[^']*'" | tr -d "'")
|
|
||||||
echo "| \`$url\` | $method | - | - |"
|
|
||||||
done
|
|
||||||
|
|
||||||
echo ""
|
|
||||||
echo "## Client Endpoints (client.php)"
|
|
||||||
echo ""
|
|
||||||
echo "| Action | Description |"
|
|
||||||
echo "|---|---|"
|
|
||||||
|
|
||||||
grep -n "case '" "$MODULE_DIR/client.php" 2>/dev/null | \
|
|
||||||
while IFS= read -r line; do
|
|
||||||
action=$(echo "$line" | grep -oP "case '\K[^']+")
|
|
||||||
echo "| \`$action\` | - |"
|
|
||||||
done
|
|
||||||
Reference in New Issue
Block a user