commit f17b9ccb98aaf3c9a57ed051dacbc827858497c6 Author: Matt Batchelder Date: Thu Feb 19 16:05:43 2026 -0500 Add Oribi Sync plugin for syncing WordPress pages and theme files from a Git repository - Implement encryption helpers for storing and retrieving the Personal Access Token (PAT). - Create REST API endpoints for triggering sync, checking sync status, and handling webhooks. - Develop the sync engine to fetch pages from the Git repository, create/update WordPress pages, and trash removed pages. - Add functionality for previewing and applying theme files from the repository. - Set up plugin activation and deactivation hooks to manage default options and scheduled tasks. - Implement uninstall routine to clean up plugin options and metadata from posts. diff --git a/.vscode/tasks.json b/.vscode/tasks.json new file mode 100644 index 0000000..44cd847 --- /dev/null +++ b/.vscode/tasks.json @@ -0,0 +1,23 @@ +{ + "version": "2.0.0", + "tasks": [ + { + "label": "Package Plugin (zip)", + "type": "shell", + "command": "mkdir -p \"${workspaceFolder}/dist\" /tmp/oribi-tech-sync && rsync -a --exclude='.git' --exclude='.vscode' --exclude='dist' --exclude='*.zip' --exclude='.DS_Store' --exclude='node_modules' \"${workspaceFolder}/\" /tmp/oribi-tech-sync/ && cd /tmp && zip -r \"${workspaceFolder}/dist/oribi-tech-sync.zip\" oribi-tech-sync && rm -rf /tmp/oribi-tech-sync && echo \"✓ Created dist/oribi-tech-sync.zip\"", + "group": { + "kind": "build", + "isDefault": true + }, + "presentation": { + "echo": true, + "reveal": "always", + "focus": false, + "panel": "shared", + "showReuseMessage": false, + "clear": true + }, + "problemMatcher": [] + } + ] +} diff --git a/README.md b/README.md new file mode 100644 index 0000000..7ab30c0 --- /dev/null +++ b/README.md @@ -0,0 +1,139 @@ +# Oribi Tech Sync + +WordPress plugin that syncs pages and theme files from a remote Git repository. + +## Features + +- **Page sync** — Reads Gutenberg HTML files from the repo's `pages/` directory and creates/updates WordPress pages automatically. +- **Theme file preview & apply** — Fetches files from the repo's `theme/` directory, shows a side-by-side preview against the active theme, and lets an admin selectively apply changes. +- **Encrypted PAT storage** — Personal Access Tokens are stored encrypted (AES-256-CBC) in the database with `autoload=false`. +- **Dry-run mode** — Preview what a sync would do without making any changes. +- **Sync log** — Keeps a history of the last 20 syncs with details on created, updated, trashed, and skipped pages. +- **REST API & webhook** — Trigger syncs programmatically or via Git host webhooks. +- **Trash policy** — Pages removed from the repo are moved to Trash for manual review. + +## Repository Layout + +The plugin expects the following structure in the remote Git repository: + +``` +repo/ +├── pages/ +│ ├── home.php +│ ├── about.php +│ ├── contact.php +│ ├── managed-it.php +│ └── ... +├── theme/ +│ ├── style.css +│ ├── theme.json +│ └── assets/ +│ ├── css/ +│ │ └── main.css +│ └── js/ +│ └── main.js +└── (other files — ignored) +``` + +### `pages/` directory +- **PHP files** (`.php`) — Use the `oribi_b()`, `oribi_b_open()`, and `oribi_b_close()` block helpers to build Gutenberg markup and `return` the result (same format as the theme's `page-data/*.php` files). Requires the **Oribi Tech Setup** plugin to be active for the helper functions. +- **HTML files** (`.html`) — Contain raw Gutenberg block markup (``) and are used directly as page content. +- The filename (without extension) becomes the page slug: `home.php` → slug `home`. +- Page title is derived from the slug: `managed-it` → "Managed It". +- Only direct children of `pages/` are processed (no subdirectories). + +### `theme/` directory +- Contains theme style/asset files (CSS, JS, JSON, PHP, HTML, SVG, TXT). +- Subdirectories are supported — e.g., `theme/assets/css/main.css` maps to `/assets/css/main.css`. +- Files are **not** applied automatically — they are fetched for preview. +- Admin can review each file, compare against the active theme, and selectively apply. +- Applied files are written directly into the active theme directory. + +## Supported Git Providers + +| Provider | Auth method | PAT format | +|---|---|---| +| **GitHub** (github.com + GHE) | `Bearer` token | Fine-grained PAT with `Contents: Read` | +| **GitLab** (gitlab.com + self-hosted) | `PRIVATE-TOKEN` header | Project/personal access token with `read_repository` | +| **Bitbucket Cloud** | Basic or Bearer | App password (`username:app_password`) or repository token | +| **Gitea / Forgejo** | `token` header | Application token with repo read access | +| **Azure DevOps** | Basic (`:PAT`) | Personal access token with `Code: Read` scope | + +Select your provider on the settings page, or leave it on "Auto-detect" to infer from the URL. + +## Setup + +1. Install and activate the plugin on your WordPress site. +2. Go to **Settings → Oribi Sync**. +3. Enter the **Repository URL** (HTTPS format, e.g., `https://github.com/owner/repo`, `https://gitlab.com/owner/repo`, `https://bitbucket.org/owner/repo`, `https://gitea.example.com/owner/repo`, or `https://dev.azure.com/org/project/_git/repo`). +4. Select the **Provider** (or leave on auto-detect). +5. Enter the **Branch** (defaults to `main`). +6. Enter a **Personal Access Token** with read access to the repository (see table above for format). +7. Click **Save Settings**. + +## Usage + +### Manual Sync +- Click **Sync Now** on the settings page to sync pages immediately. +- Click **Dry Run** to preview changes without modifying anything. +- Click **Preview Theme Files** to fetch and review theme files from the repo. + +### REST API + +All REST endpoints require `manage_options` capability (authenticated admin). + +```bash +# Trigger sync +curl -X POST https://yoursite.com/wp-json/oribi-sync/v1/sync \ + -H "X-WP-Nonce: " \ + --cookie "wordpress_logged_in_...=..." + +# Trigger dry-run +curl -X POST "https://yoursite.com/wp-json/oribi-sync/v1/sync?dry_run=1" \ + -H "X-WP-Nonce: " \ + --cookie "wordpress_logged_in_...=..." + +# Get status +curl https://yoursite.com/wp-json/oribi-sync/v1/status \ + -H "X-WP-Nonce: " \ + --cookie "wordpress_logged_in_...=..." +``` + +### Webhook + +Set up a webhook on your Git host to trigger syncs on push: + +**Endpoint:** `POST https://yoursite.com/wp-json/oribi-sync/v1/webhook` + +**Authentication** (one of): +- `Authorization: Bearer ` header +- GitHub `X-Hub-Signature-256` header (HMAC-SHA256) + +**Secret configuration** (one of): +- Define `ORIBI_SYNC_WEBHOOK_SECRET` in `wp-config.php` +- Store in WP option `oribi_sync_webhook_secret` + +## Security + +- PAT is encrypted with AES-256-CBC using a key derived from `AUTH_SALT`. +- All admin actions require `manage_options` capability and nonce verification. +- REST endpoints require authenticated admin user. +- Webhook endpoint validates shared secret or HMAC signature. +- Theme file writes are restricted to allowed extensions (CSS, JS, JSON, PHP, HTML, SVG, TXT). + +## Sync Behavior + +| Scenario | Action | +|---|---| +| New file in `pages/` | Create new WP page (published) | +| Changed file in `pages/` | Overwrite page content | +| Unchanged file in `pages/` | Skip (no unnecessary revisions) | +| File removed from `pages/` | Move corresponding WP page to Trash | +| New file in `theme/` | Available for preview & manual apply | +| Changed file in `theme/` | Available for preview & manual apply | + +## Requirements + +- WordPress 6.0+ +- PHP 7.4+ with `openssl` extension +- Git host with API access (GitHub or GitLab supported) diff --git a/assets/admin.css b/assets/admin.css new file mode 100644 index 0000000..3396c5c --- /dev/null +++ b/assets/admin.css @@ -0,0 +1,37 @@ +/** + * Oribi Sync — Admin styles + */ + +.oribi-sync-wrap .form-table th { + width: 200px; +} + +.oribi-sync-wrap .button { + margin-right: 6px; +} + +.oribi-sync-wrap hr { + margin: 24px 0; + border: none; + border-top: 1px solid #ddd; +} + +.oribi-sync-log td, +.oribi-sync-log th { + font-size: 13px; + padding: 6px 8px; +} + +.oribi-sync-wrap details summary { + cursor: pointer; + color: #2271b1; + font-size: 13px; +} + +.oribi-sync-wrap details summary:hover { + text-decoration: underline; +} + +.oribi-sync-wrap .description code { + font-size: 12px; +} diff --git a/dist/oribi-tech-sync.zip b/dist/oribi-tech-sync.zip new file mode 100644 index 0000000..54d6f44 Binary files /dev/null and b/dist/oribi-tech-sync.zip differ diff --git a/includes/admin.php b/includes/admin.php new file mode 100644 index 0000000..8a6e0f1 --- /dev/null +++ b/includes/admin.php @@ -0,0 +1,265 @@ + +
+

Oribi Sync

+ + +

Settings saved.

+ +

PAT has been cleared.

+ + + +
+

+ +

+
    + +
  • Created:
  • + + +
  • Updated:
  • + + +
  • Trashed:
  • + + +
  • Skipped:
  • + + +
  • Errors:
  • + +
+
+ + + +
+ + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + +

Sync Actions

+

+ The plugin reads two folders from the repo: pages/ (PHP or HTML files → WP pages) + and theme/ (theme style files → preview & manual apply). Everything else is ignored.
+ PHP files are executed using the oribi_b() block helpers (requires Oribi Tech Setup plugin). + HTML files are used as raw Gutenberg block markup. +

+

+ + 🔄 Sync Now + + + + 🔍 Dry Run + + + + 🎨 Preview Theme Files + +

+ + +

Last sync:

+ + + + +
+

Theme Files Preview

+ + + + + +
+

Sync Log

+ + + + + + + + + + + + + + + + + + + + + +
TimeCreatedUpdatedTrashedSkippedErrors
+ +
+ 'GitHub', + 'gitlab' => 'GitLab', + 'bitbucket' => 'Bitbucket Cloud', + 'gitea' => 'Gitea / Forgejo', + 'azure' => 'Azure DevOps', + ]; +} + +/** + * Get the configured provider (stored in options). + */ +function oribi_sync_get_provider(): string { + $provider = get_option( 'oribi_sync_provider', '' ); + if ( ! empty( $provider ) && array_key_exists( $provider, oribi_sync_providers() ) ) { + return $provider; + } + // Auto-detect fallback for existing installs without the option + $repo = get_option( 'oribi_sync_repo', '' ); + return oribi_sync_detect_provider( $repo ); +} + +/** + * Auto-detect the Git provider from the repo URL. + * Used as fallback when no explicit provider is set. + * + * @return string Provider key. + */ +function oribi_sync_detect_provider( string $repo_url ): string { + if ( stripos( $repo_url, 'github.com' ) !== false ) return 'github'; + if ( stripos( $repo_url, 'gitlab.com' ) !== false ) return 'gitlab'; + if ( stripos( $repo_url, 'gitlab' ) !== false ) return 'gitlab'; + if ( stripos( $repo_url, 'bitbucket.org' ) !== false ) return 'bitbucket'; + if ( stripos( $repo_url, 'dev.azure.com' ) !== false ) return 'azure'; + if ( stripos( $repo_url, 'visualstudio.com' ) !== false ) return 'azure'; + // Assume Gitea for unknown self-hosted (most compatible generic API) + return 'gitea'; +} + +// ─── URL parsing ────────────────────────────────────────────────────────────── + +/** + * Parse owner/repo (and optionally project) from a Git URL. + * + * Accepts HTTPS and SSH styles for all providers. + * + * @return array{owner: string, repo: string, host?: string, project?: string}|WP_Error + */ +function oribi_sync_parse_repo_url( string $url ) { + // Azure DevOps: https://dev.azure.com/{org}/{project}/_git/{repo} + if ( preg_match( '#https?://dev\.azure\.com/([^/]+)/([^/]+)/_git/([^/\s]+?)(?:\.git)?$#i', $url, $m ) ) { + return [ 'owner' => $m[1], 'project' => $m[2], 'repo' => $m[3], 'host' => 'dev.azure.com' ]; + } + // Azure DevOps legacy: https://{org}.visualstudio.com/{project}/_git/{repo} + if ( preg_match( '#https?://([^.]+)\.visualstudio\.com/([^/]+)/_git/([^/\s]+?)(?:\.git)?$#i', $url, $m ) ) { + return [ 'owner' => $m[1], 'project' => $m[2], 'repo' => $m[3], 'host' => $m[1] . '.visualstudio.com' ]; + } + // Generic HTTPS: https://host/owner/repo + if ( preg_match( '#https?://([^/]+)/([^/]+)/([^/\s.]+?)(?:\.git)?(?:/)?$#i', $url, $m ) ) { + return [ 'owner' => $m[2], 'repo' => $m[3], 'host' => $m[1] ]; + } + // SSH: git@host:owner/repo.git + if ( preg_match( '#[^@]+@([^:]+):([^/]+)/([^/\s.]+?)(?:\.git)?$#i', $url, $m ) ) { + return [ 'owner' => $m[2], 'repo' => $m[3], 'host' => $m[1] ]; + } + return new WP_Error( 'oribi_sync_bad_url', 'Could not parse owner/repo from the repository URL.' ); +} + +// ─── API base URLs ──────────────────────────────────────────────────────────── + +/** + * Build the base API URL for the configured provider. + */ +function oribi_sync_api_base( string $provider, array $parsed ): string { + $owner = $parsed['owner']; + $repo = $parsed['repo']; + $host = $parsed['host'] ?? ''; + + switch ( $provider ) { + case 'gitlab': + $api_host = ( $host && $host !== 'gitlab.com' ) ? $host : 'gitlab.com'; + $encoded = rawurlencode( $owner . '/' . $repo ); + return "https://{$api_host}/api/v4/projects/{$encoded}"; + + case 'bitbucket': + return "https://api.bitbucket.org/2.0/repositories/{$owner}/{$repo}"; + + case 'azure': + $project = $parsed['project'] ?? $repo; + $org = $owner; + return "https://dev.azure.com/{$org}/{$project}/_apis/git/repositories/{$repo}"; + + case 'gitea': + // Works for Gitea, Forgejo, and most Gitea-compatible hosts + $api_host = $host ?: 'localhost:3000'; + return "https://{$api_host}/api/v1/repos/{$owner}/{$repo}"; + + case 'github': + default: + $api_host = ( $host && $host !== 'github.com' ) ? $host . '/api/v3' : 'api.github.com'; + return "https://{$api_host}/repos/{$owner}/{$repo}"; + } +} + +// ─── Auth headers ───────────────────────────────────────────────────────────── + +/** + * Build authorization headers for the provider. + * + * @return array Headers array to merge into request. + */ +function oribi_sync_auth_headers( string $provider, string $pat ): array { + switch ( $provider ) { + case 'bitbucket': + // Bitbucket Cloud app passwords use Basic auth (username:app_password) + // If PAT contains ':', treat as username:password; otherwise Bearer + if ( strpos( $pat, ':' ) !== false ) { + return [ 'Authorization' => 'Basic ' . base64_encode( $pat ) ]; + } + return [ 'Authorization' => 'Bearer ' . $pat ]; + + case 'azure': + // Azure DevOps PATs use Basic auth with empty username + return [ 'Authorization' => 'Basic ' . base64_encode( ':' . $pat ) ]; + + case 'gitlab': + return [ 'PRIVATE-TOKEN' => $pat ]; + + case 'gitea': + return [ 'Authorization' => 'token ' . $pat ]; + + case 'github': + default: + return [ 'Authorization' => 'Bearer ' . $pat ]; + } +} + +// ─── API request ────────────────────────────────────────────────────────────── + +/** + * Perform an authenticated GET request to the Git API. + * + * @return array|WP_Error Decoded JSON body or WP_Error. + */ +function oribi_sync_api_get( string $url, string $provider, string $pat ) { + $headers = array_merge( + oribi_sync_auth_headers( $provider, $pat ), + [ + 'Accept' => 'application/json', + 'User-Agent' => 'Oribi-Sync-WP/' . ORIBI_SYNC_VERSION, + ] + ); + + // Provider-specific Accept overrides + if ( $provider === 'github' ) { + $headers['Accept'] = 'application/vnd.github+json'; + } elseif ( $provider === 'azure' ) { + $headers['Accept'] = 'application/json'; + } + + $response = wp_remote_get( $url, [ + 'timeout' => 30, + 'headers' => $headers, + ] ); + + if ( is_wp_error( $response ) ) { + return $response; + } + + $code = wp_remote_retrieve_response_code( $response ); + $body = wp_remote_retrieve_body( $response ); + + if ( $code < 200 || $code >= 300 ) { + return new WP_Error( + 'oribi_sync_api_error', + sprintf( 'Git API returned HTTP %d: %s', $code, wp_trim_words( $body, 30, '…' ) ) + ); + } + + $decoded = json_decode( $body, true ); + if ( json_last_error() !== JSON_ERROR_NONE ) { + return new WP_Error( 'oribi_sync_json_error', 'Failed to parse API JSON response.' ); + } + + return $decoded; +} + +// ─── Tree fetching ──────────────────────────────────────────────────────────── + +/** + * Fetch the repository tree (recursive) for the given branch. + * + * Returns a flat list of file entries with 'path' and 'type'. + * + * @return array|WP_Error + */ +function oribi_sync_fetch_tree( string $api_base, string $branch, string $provider, string $pat ) { + switch ( $provider ) { + + // ── GitLab ────────────────────────────────────────────────────── + case 'gitlab': + $entries = []; + $page = 1; + do { + $url = $api_base . '/repository/tree?' . http_build_query( [ + 'ref' => $branch, + 'recursive' => 'true', + 'per_page' => 100, + 'page' => $page, + ] ); + $result = oribi_sync_api_get( $url, $provider, $pat ); + if ( is_wp_error( $result ) ) return $result; + if ( empty( $result ) ) break; + + foreach ( $result as $item ) { + $entries[] = [ + 'path' => $item['path'], + 'type' => $item['type'] === 'blob' ? 'blob' : $item['type'], + 'sha' => $item['id'] ?? '', // GitLab uses 'id' for blob SHA + ]; + } + $page++; + } while ( count( $result ) === 100 ); + return $entries; + + // ── Bitbucket Cloud ───────────────────────────────────────────── + case 'bitbucket': + $entries = []; + $url = $api_base . '/src/' . rawurlencode( $branch ) . '/?pagelen=100&max_depth=10'; + // Bitbucket returns directory listings; we recurse via 'next' links + while ( $url ) { + $result = oribi_sync_api_get( $url, $provider, $pat ); + if ( is_wp_error( $result ) ) return $result; + + foreach ( $result['values'] ?? [] as $item ) { + if ( ( $item['type'] ?? '' ) === 'commit_file' ) { + $entries[] = [ 'path' => $item['path'], 'type' => 'blob' ]; + } + } + $url = $result['next'] ?? null; + } + return $entries; + + // ── Azure DevOps ─────────────────────────────────────────────── + case 'azure': + $url = $api_base . '/items?' . http_build_query( [ + 'recursionLevel' => 'full', + 'versionDescriptor.version' => $branch, + 'versionDescriptor.versionType' => 'branch', + 'api-version' => '7.0', + ] ); + $result = oribi_sync_api_get( $url, $provider, $pat ); + if ( is_wp_error( $result ) ) return $result; + + $entries = []; + foreach ( $result['value'] ?? [] as $item ) { + if ( ! $item['isFolder'] ) { + // Azure paths start with '/' — strip leading slash + $path = ltrim( $item['path'], '/' ); + $entries[] = [ 'path' => $path, 'type' => 'blob' ]; + } + } + return $entries; + + // ── Gitea / Forgejo ───────────────────────────────────────────── + case 'gitea': + $url = $api_base . '/git/trees/' . rawurlencode( $branch ) . '?recursive=true'; + $result = oribi_sync_api_get( $url, $provider, $pat ); + if ( is_wp_error( $result ) ) return $result; + + if ( ! isset( $result['tree'] ) ) { + return new WP_Error( 'oribi_sync_tree_error', 'Unexpected tree response from Gitea.' ); + } + return array_map( function ( $item ) { + return [ 'path' => $item['path'], 'type' => $item['type'], 'sha' => $item['sha'] ?? '' ]; + }, $result['tree'] ); + + // ── GitHub (default) ─────────────────────────────────────────── + case 'github': + default: + $url = $api_base . '/git/trees/' . rawurlencode( $branch ) . '?recursive=1'; + $result = oribi_sync_api_get( $url, $provider, $pat ); + if ( is_wp_error( $result ) ) return $result; + + if ( ! isset( $result['tree'] ) ) { + return new WP_Error( 'oribi_sync_tree_error', 'Unexpected tree response structure.' ); + } + return array_map( function ( $item ) { + return [ 'path' => $item['path'], 'type' => $item['type'], 'sha' => $item['sha'] ?? '' ]; + }, $result['tree'] ); + } +} + +// ─── File fetching ──────────────────────────────────────────────────────────── + +/** + * Fetch raw file content from the repository. + * + * @return string|WP_Error Raw file content. + */ +function oribi_sync_fetch_file( string $api_base, string $branch, string $file_path, string $provider, string $pat ) { + $encoded_path = implode( '/', array_map( 'rawurlencode', explode( '/', $file_path ) ) ); + + switch ( $provider ) { + case 'gitlab': + $url = $api_base . '/repository/files/' . rawurlencode( $file_path ) . '/raw?' . http_build_query( [ 'ref' => $branch ] ); + $accept = 'text/plain'; + break; + + case 'bitbucket': + $url = $api_base . '/src/' . rawurlencode( $branch ) . '/' . $encoded_path; + $accept = 'text/plain'; + break; + + case 'azure': + $url = $api_base . '/items?' . http_build_query( [ + 'path' => '/' . $file_path, + 'versionDescriptor.version' => $branch, + 'versionDescriptor.versionType' => 'branch', + 'api-version' => '7.0', + '\$format' => 'octetStream', + ] ); + $accept = 'application/octet-stream'; + break; + + case 'gitea': + $url = $api_base . '/raw/' . $encoded_path . '?ref=' . rawurlencode( $branch ); + $accept = 'text/plain'; + break; + + case 'github': + default: + $url = $api_base . '/contents/' . $encoded_path . '?ref=' . rawurlencode( $branch ); + $accept = 'application/vnd.github.raw+json'; + break; + } + + $headers = array_merge( + oribi_sync_auth_headers( $provider, $pat ), + [ + 'Accept' => $accept, + 'User-Agent' => 'Oribi-Sync-WP/' . ORIBI_SYNC_VERSION, + ] + ); + + $response = wp_remote_get( $url, [ + 'timeout' => 30, + 'headers' => $headers, + ] ); + + if ( is_wp_error( $response ) ) { + return $response; + } + + $code = wp_remote_retrieve_response_code( $response ); + if ( $code < 200 || $code >= 300 ) { + return new WP_Error( + 'oribi_sync_file_error', + sprintf( 'Failed to fetch %s (HTTP %d)', $file_path, $code ) + ); + } + + return wp_remote_retrieve_body( $response ); +} + +// ─── Tree filtering ─────────────────────────────────────────────────────────── + +/** + * Filter tree entries to only those under a given directory prefix. + * + * @param array $tree Tree from oribi_sync_fetch_tree(). + * @param string $prefix Directory prefix (e.g. 'pages/'). + * @param bool $recursive Whether to include files in subdirectories (default: false). + * + * @return array Filtered entries (blobs only). + */ +function oribi_sync_filter_tree( array $tree, string $prefix, bool $recursive = false ): array { + $prefix = rtrim( $prefix, '/' ) . '/'; + $out = []; + + foreach ( $tree as $entry ) { + if ( $entry['type'] !== 'blob' ) continue; + if ( strpos( $entry['path'], $prefix ) !== 0 ) continue; + $relative = substr( $entry['path'], strlen( $prefix ) ); + // Skip sub-directory files unless recursive is enabled + if ( ! $recursive && strpos( $relative, '/' ) !== false ) continue; + $out[] = $entry; + } + + return $out; +} diff --git a/includes/crypto.php b/includes/crypto.php new file mode 100644 index 0000000..870fac8 --- /dev/null +++ b/includes/crypto.php @@ -0,0 +1,70 @@ + 'POST', + 'callback' => 'oribi_sync_rest_sync', + 'permission_callback' => function () { + return current_user_can( 'manage_options' ); + }, + ] ); + + // ── Sync status ─────────────────────────────────────────────────────── + register_rest_route( 'oribi-sync/v1', '/status', [ + 'methods' => 'GET', + 'callback' => 'oribi_sync_rest_status', + 'permission_callback' => function () { + return current_user_can( 'manage_options' ); + }, + ] ); + + // ── Webhook (secret-based auth, no WP login required) ───────────────── + register_rest_route( 'oribi-sync/v1', '/webhook', [ + 'methods' => 'POST', + 'callback' => 'oribi_sync_rest_webhook', + 'permission_callback' => '__return_true', // Auth handled in callback + ] ); +} ); + +/** + * REST: Trigger sync. + */ +function oribi_sync_rest_sync( WP_REST_Request $request ): WP_REST_Response { + $dry_run = (bool) $request->get_param( 'dry_run' ); + $result = oribi_sync_run( $dry_run ); + + return new WP_REST_Response( $result, $result['ok'] ? 200 : 500 ); +} + +/** + * REST: Get last sync status. + */ +function oribi_sync_rest_status(): WP_REST_Response { + return new WP_REST_Response( [ + 'last_run' => get_option( 'oribi_sync_last_run', null ), + 'log' => array_slice( get_option( 'oribi_sync_log', [] ), 0, 5 ), + 'repo' => get_option( 'oribi_sync_repo', '' ), + 'branch' => get_option( 'oribi_sync_branch', 'main' ), + 'provider' => oribi_sync_get_provider(), + 'has_pat' => ! empty( get_option( 'oribi_sync_pat', '' ) ), + ] ); +} + +/** + * REST: Webhook trigger. + * + * Validates using a shared secret stored in the WP option oribi_sync_webhook_secret + * or the constant ORIBI_SYNC_WEBHOOK_SECRET. + * + * Accepts GitHub-style X-Hub-Signature-256 header, or a simple + * Authorization: Bearer header. + */ +function oribi_sync_rest_webhook( WP_REST_Request $request ): WP_REST_Response { + $secret = defined( 'ORIBI_SYNC_WEBHOOK_SECRET' ) + ? ORIBI_SYNC_WEBHOOK_SECRET + : get_option( 'oribi_sync_webhook_secret', '' ); + + if ( empty( $secret ) ) { + return new WP_REST_Response( [ 'error' => 'Webhook secret not configured.' ], 403 ); + } + + // Check Authorization: Bearer + $auth = $request->get_header( 'Authorization' ); + if ( $auth && preg_match( '/^Bearer\s+(.+)$/i', $auth, $m ) ) { + if ( ! hash_equals( $secret, $m[1] ) ) { + return new WP_REST_Response( [ 'error' => 'Invalid secret.' ], 403 ); + } + } + // Check GitHub X-Hub-Signature-256 + elseif ( $sig = $request->get_header( 'X-Hub-Signature-256' ) ) { + $body = $request->get_body(); + $expected = 'sha256=' . hash_hmac( 'sha256', $body, $secret ); + if ( ! hash_equals( $expected, $sig ) ) { + return new WP_REST_Response( [ 'error' => 'Invalid signature.' ], 403 ); + } + } else { + return new WP_REST_Response( [ 'error' => 'Missing authentication.' ], 403 ); + } + + // Run sync + $result = oribi_sync_run(); + + return new WP_REST_Response( $result, $result['ok'] ? 200 : 500 ); +} diff --git a/includes/sync-engine.php b/includes/sync-engine.php new file mode 100644 index 0000000..035012e --- /dev/null +++ b/includes/sync-engine.php @@ -0,0 +1,417 @@ +getMessage() ); + } + + @unlink( $tmp ); + + // Prefer the return value; fall back to echoed output + if ( is_string( $returned ) && ! empty( trim( $returned ) ) ) { + return trim( $returned ); + } + if ( ! empty( trim( $echoed ) ) ) { + return trim( $echoed ); + } + + return new WP_Error( 'oribi_sync_empty_output', $slug . ': PHP file produced no output.' ); +} + +/** + * Run the full page sync. + * + * @param bool $dry_run If true, returns what would happen without making changes. + * + * @return array{ok: bool, created: string[], updated: string[], trashed: string[], skipped: string[], errors: string[]} + */ +function oribi_sync_run( bool $dry_run = false ): array { + $result = [ + 'ok' => true, + 'created' => [], + 'updated' => [], + 'trashed' => [], + 'skipped' => [], + 'errors' => [], + ]; + + // ── Gather settings ──────────────────────────────────────────────────── + $repo_url = get_option( 'oribi_sync_repo', '' ); + $branch = get_option( 'oribi_sync_branch', 'main' ) ?: 'main'; + $pat = oribi_sync_get_pat(); + + if ( empty( $repo_url ) || empty( $pat ) ) { + $result['ok'] = false; + $result['errors'][] = 'Repository URL or PAT is not configured.'; + return $result; + } + + // ── Parse repo URL ───────────────────────────────────────────────────── + $parsed = oribi_sync_parse_repo_url( $repo_url ); + if ( is_wp_error( $parsed ) ) { + $result['ok'] = false; + $result['errors'][] = $parsed->get_error_message(); + return $result; + } + + $provider = oribi_sync_get_provider(); + $api_base = oribi_sync_api_base( $provider, $parsed ); + + // ── Fetch tree ───────────────────────────────────────────────────────── + $tree = oribi_sync_fetch_tree( $api_base, $branch, $provider, $pat ); + if ( is_wp_error( $tree ) ) { + $result['ok'] = false; + $result['errors'][] = 'Tree fetch failed: ' . $tree->get_error_message(); + return $result; + } + + // ── Filter to pages/ directory ───────────────────────────────────────── + $page_files = oribi_sync_filter_tree( $tree, 'pages' ); + + if ( empty( $page_files ) ) { + $result['errors'][] = 'No files found under pages/ in the repository.'; + $result['ok'] = false; + return $result; + } + + // ── Process each page file ───────────────────────────────────────────── + $synced_slugs = []; + + foreach ( $page_files as $entry ) { + $filename = basename( $entry['path'] ); + $slug = oribi_sync_filename_to_slug( $filename ); + + if ( empty( $slug ) ) { + $result['skipped'][] = $entry['path'] . ' (could not derive slug)'; + continue; + } + + $synced_slugs[] = $slug; + + // Find existing page early so we can do change detection before fetching content + $existing = get_page_by_path( $slug ); + + // ── Fast-path change detection via git blob SHA ──────────────────── + // The tree API returns the blob SHA for GitHub, GitLab and Gitea. + // This SHA changes whenever the file content changes, so we can skip + // the (potentially cached) file-content fetch entirely when it matches. + $git_sha = $entry['sha'] ?? ''; + $stored_git_sha = $existing ? get_post_meta( $existing->ID, '_oribi_sync_git_sha', true ) : ''; + + if ( $existing && ! empty( $git_sha ) && $git_sha === $stored_git_sha ) { + $result['skipped'][] = $slug . ' (unchanged)'; + if ( ! $dry_run ) { + update_post_meta( $existing->ID, '_oribi_sync_last_run', current_time( 'mysql' ) ); + } + continue; + } + + // Fetch raw file from repo + $raw_content = oribi_sync_fetch_file( $api_base, $branch, $entry['path'], $provider, $pat ); + if ( is_wp_error( $raw_content ) ) { + $result['errors'][] = $entry['path'] . ': ' . $raw_content->get_error_message(); + continue; + } + + $raw_content = trim( $raw_content ); + + // Determine file type and resolve to block markup + $ext = strtolower( pathinfo( $filename, PATHINFO_EXTENSION ) ); + + if ( $ext === 'php' ) { + // Execute the PHP file to produce Gutenberg block markup + $content = oribi_sync_execute_php( $raw_content, $slug ); + if ( is_wp_error( $content ) ) { + $result['errors'][] = $entry['path'] . ': ' . $content->get_error_message(); + continue; + } + } else { + // HTML or other — use raw content directly as block markup + $content = $raw_content; + } + + // Checksum based on raw source — used as fallback for providers without tree SHA + $checksum = hash( 'sha256', $raw_content ); + + if ( $dry_run ) { + if ( $existing ) { + // git SHA already differs (or wasn't available) — report as updated + $old_checksum = get_post_meta( $existing->ID, '_oribi_sync_checksum', true ); + if ( empty( $git_sha ) && $old_checksum === $checksum ) { + $result['skipped'][] = $slug . ' (unchanged)'; + } else { + $result['updated'][] = $slug; + } + } else { + $result['created'][] = $slug; + } + continue; + } + + if ( $existing ) { + // For providers without a tree SHA, fall back to content checksum comparison + if ( empty( $git_sha ) ) { + $old_checksum = get_post_meta( $existing->ID, '_oribi_sync_checksum', true ); + if ( $old_checksum === $checksum ) { + $result['skipped'][] = $slug . ' (unchanged)'; + update_post_meta( $existing->ID, '_oribi_sync_last_run', current_time( 'mysql' ) ); + continue; + } + } + + $update_result = wp_update_post( [ + 'ID' => $existing->ID, + 'post_content' => $content, + 'post_status' => 'publish', + ], true ); + + if ( is_wp_error( $update_result ) ) { + $result['errors'][] = $slug . ': ' . $update_result->get_error_message(); + continue; + } + + update_post_meta( $existing->ID, '_oribi_sync_checksum', $checksum ); + update_post_meta( $existing->ID, '_oribi_sync_git_sha', $git_sha ); + update_post_meta( $existing->ID, '_oribi_sync_source', $repo_url . '@' . $branch . ':' . $entry['path'] ); + update_post_meta( $existing->ID, '_oribi_sync_last_run', current_time( 'mysql' ) ); + update_post_meta( $existing->ID, '_wp_page_template', 'default' ); + + $result['updated'][] = $slug; + } else { + // Create new page + $title = oribi_sync_slug_to_title( $slug ); + + $post_id = wp_insert_post( [ + 'post_title' => $title, + 'post_name' => $slug, + 'post_status' => 'publish', + 'post_type' => 'page', + 'post_content' => $content, + ], true ); + + if ( is_wp_error( $post_id ) ) { + $result['errors'][] = $slug . ': ' . $post_id->get_error_message(); + continue; + } + + update_post_meta( $post_id, '_oribi_sync_checksum', $checksum ); + update_post_meta( $post_id, '_oribi_sync_git_sha', $git_sha ); + update_post_meta( $post_id, '_oribi_sync_source', $repo_url . '@' . $branch . ':' . $entry['path'] ); + update_post_meta( $post_id, '_oribi_sync_last_run', current_time( 'mysql' ) ); + update_post_meta( $post_id, '_wp_page_template', 'default' ); + + $result['created'][] = $slug; + } + } + + // ── Trash pages removed from repo ────────────────────────────────────── + if ( ! $dry_run ) { + $trashed = oribi_sync_trash_removed_pages( $synced_slugs ); + $result['trashed'] = $trashed; + } + + // ── Record run ───────────────────────────────────────────────────────── + if ( ! $dry_run ) { + oribi_sync_record_run( $result ); + } + + return $result; +} + +/** + * Trash WP pages that were previously synced but are no longer in the repo. + * + * A page is considered "synced" if it has the _oribi_sync_checksum meta key. + * + * @param string[] $current_slugs Slugs found in the current repo tree. + * + * @return string[] Slugs of pages moved to trash. + */ +function oribi_sync_trash_removed_pages( array $current_slugs ): array { + $trashed = []; + + $query = new WP_Query( [ + 'post_type' => 'page', + 'post_status' => 'publish', + 'meta_key' => '_oribi_sync_checksum', + 'posts_per_page' => -1, + 'fields' => 'ids', + ] ); + + foreach ( $query->posts as $post_id ) { + $page = get_post( $post_id ); + if ( ! $page ) continue; + + $slug = $page->post_name; + + if ( ! in_array( $slug, $current_slugs, true ) ) { + wp_trash_post( $page->ID ); + $trashed[] = $slug; + } + } + + return $trashed; +} + +/** + * Convert a filename to a page slug. + * + * Examples: + * home.php → home + * managed-it.php → managed-it + * home.html → home + * My Page.html → my-page + * + * @return string Sanitized slug (empty on failure). + */ +function oribi_sync_filename_to_slug( string $filename ): string { + // Strip extension + $slug = pathinfo( $filename, PATHINFO_FILENAME ); + // Sanitize + $slug = sanitize_title( $slug ); + return $slug; +} + +/** + * Convert a slug to a human-readable page title. + * + * Examples: + * home → Home + * managed-it → Managed It + * 365care → 365care + */ +function oribi_sync_slug_to_title( string $slug ): string { + return ucwords( str_replace( '-', ' ', $slug ) ); +} + +/** + * Record a sync run in the options table. + */ +function oribi_sync_record_run( array $result ): void { + update_option( 'oribi_sync_last_run', current_time( 'mysql' ), 'no' ); + + $log = get_option( 'oribi_sync_log', [] ); + if ( ! is_array( $log ) ) $log = []; + + array_unshift( $log, [ + 'time' => current_time( 'mysql' ), + 'created' => $result['created'], + 'updated' => $result['updated'], + 'trashed' => $result['trashed'], + 'skipped' => $result['skipped'], + 'errors' => $result['errors'], + ] ); + + // Keep last 20 entries + $log = array_slice( $log, 0, 20 ); + update_option( 'oribi_sync_log', $log, 'no' ); +} + +/** + * Fetch theme files from the repo (for preview / apply). + * + * @return array{files: array, errors: string[]} + */ +function oribi_sync_fetch_theme_files(): array { + $out = [ 'files' => [], 'errors' => [] ]; + + $repo_url = get_option( 'oribi_sync_repo', '' ); + $branch = get_option( 'oribi_sync_branch', 'main' ) ?: 'main'; + $pat = oribi_sync_get_pat(); + + if ( empty( $repo_url ) || empty( $pat ) ) { + $out['errors'][] = 'Repository URL or PAT is not configured.'; + return $out; + } + + $parsed = oribi_sync_parse_repo_url( $repo_url ); + if ( is_wp_error( $parsed ) ) { + $out['errors'][] = $parsed->get_error_message(); + return $out; + } + + $provider = oribi_sync_get_provider(); + $api_base = oribi_sync_api_base( $provider, $parsed ); + + $tree = oribi_sync_fetch_tree( $api_base, $branch, $provider, $pat ); + if ( is_wp_error( $tree ) ) { + $out['errors'][] = 'Tree fetch failed: ' . $tree->get_error_message(); + return $out; + } + + $theme_entries = oribi_sync_filter_tree( $tree, 'theme', true ); + + foreach ( $theme_entries as $entry ) { + // Derive relative path by stripping the 'theme/' prefix + $relative = substr( $entry['path'], strlen( 'theme/' ) ); + $content = oribi_sync_fetch_file( $api_base, $branch, $entry['path'], $provider, $pat ); + + if ( is_wp_error( $content ) ) { + $out['errors'][] = $entry['path'] . ': ' . $content->get_error_message(); + continue; + } + + // Check if a matching file exists in the active theme + $theme_file = get_template_directory() . '/' . $relative; + $local_exists = file_exists( $theme_file ); + $local_content = $local_exists ? file_get_contents( $theme_file ) : null; + + $out['files'][] = [ + 'repo_path' => $entry['path'], + 'relative' => $relative, + 'content' => $content, + 'local_exists' => $local_exists, + 'local_content' => $local_content, + 'changed' => $local_exists ? ( $local_content !== $content ) : true, + ]; + } + + return $out; +} diff --git a/includes/theme-preview.php b/includes/theme-preview.php new file mode 100644 index 0000000..8a84179 --- /dev/null +++ b/includes/theme-preview.php @@ -0,0 +1,233 @@ + 'theme', + 'oribi_sync_saved' => 'no_files', + ], admin_url( 'options-general.php?page=oribi-sync' ) ) ); + exit; + } + + $theme_data = get_transient( 'oribi_sync_theme_preview' ); + if ( ! $theme_data || empty( $theme_data['files'] ) ) { + wp_redirect( add_query_arg( [ + 'oribi_sync_tab' => 'theme', + 'oribi_sync_saved' => 'expired', + ], admin_url( 'options-general.php?page=oribi-sync' ) ) ); + exit; + } + + $applied = []; + $errors = []; + $theme_dir = get_template_directory(); + + foreach ( $theme_data['files'] as $file ) { + $relative = $file['relative']; + + if ( ! in_array( $relative, $selected, true ) ) continue; + + $dest = $theme_dir . '/' . $relative; + + // Safety: only allow CSS, JS, JSON, PHP, HTML extensions + $ext = strtolower( pathinfo( $relative, PATHINFO_EXTENSION ) ); + $allowed = [ 'css', 'js', 'json', 'php', 'html', 'htm', 'svg', 'txt' ]; + if ( ! in_array( $ext, $allowed, true ) ) { + $errors[] = $relative . ' — file type not allowed.'; + continue; + } + + // Create subdirectory if needed + $dir = dirname( $dest ); + if ( ! is_dir( $dir ) ) { + if ( ! wp_mkdir_p( $dir ) ) { + $errors[] = $relative . ' — could not create directory.'; + continue; + } + } + + // Write file + $written = file_put_contents( $dest, $file['content'] ); + if ( $written === false ) { + $errors[] = $relative . ' — write failed (check permissions).'; + } else { + $applied[] = $relative; + } + } + + // Record + update_option( 'oribi_sync_theme_applied', [ + 'time' => current_time( 'mysql' ), + 'applied' => $applied, + 'errors' => $errors, + ], 'no' ); + + set_transient( 'oribi_sync_theme_result', [ + 'applied' => $applied, + 'errors' => $errors, + ], 60 ); + + wp_redirect( add_query_arg( [ + 'oribi_sync_tab' => 'theme', + 'oribi_sync_saved' => 'theme_applied', + ], admin_url( 'options-general.php?page=oribi-sync' ) ) ); + exit; +} ); + +// ─── Render theme preview panel (called from settings page) ────────────────── + +/** + * Render the theme preview panel within the settings page. + */ +function oribi_sync_render_theme_preview(): void { + $theme_data = get_transient( 'oribi_sync_theme_preview' ); + $theme_result = get_transient( 'oribi_sync_theme_result' ); + if ( $theme_result ) delete_transient( 'oribi_sync_theme_result' ); + + $saved = $_GET['oribi_sync_saved'] ?? ''; + ?> + + +
+

Theme files applied:

+ +
    + +
  • + +
+ + +
    + +
  • + +
+ +
+ +

No theme files were selected.

+ +

Theme preview data expired. Please preview again.

+ + + +

Click Preview Theme Files above to fetch files from the repo's theme/ directory.

+ + + + +
+

Errors fetching theme files:

+
    + +
  • + +
+
+ + + +

No files found under theme/ in the repository.

+ + + +
+ + + + + + + + + + + + + + + + + + + + +
FileStatusPreview
+ /> + + + New + + Changed + + Unchanged + + + +
+ View content +
+ +
+ Current local content +
+
+ +
+ + — + +
+ +

+ + + Files will be written directly into the active theme: + +

+
+ + + Settings'; + return $links; +} ); diff --git a/uninstall.php b/uninstall.php new file mode 100644 index 0000000..b7c7cef --- /dev/null +++ b/uninstall.php @@ -0,0 +1,36 @@ + 'page', + 'post_status' => 'any', + 'posts_per_page' => -1, + 'meta_key' => '_oribi_sync_checksum', + 'fields' => 'ids', +] ); + +foreach ( $posts as $post_id ) { + delete_post_meta( $post_id, '_oribi_sync_checksum' ); + delete_post_meta( $post_id, '_oribi_sync_source' ); + delete_post_meta( $post_id, '_oribi_sync_last_run' ); +} + +// Clear any scheduled cron +wp_clear_scheduled_hook( 'oribi_sync_cron_run' );