Running commands). * manual any other panel (Plesk, CyberPanel, ...), or when the customer would rather not give API access: * they create the database themselves and enter it, and the installer lists what's left to do by hand * * It needs: PHP 7.4+ that may run commands (proc_open), Python 3.12+ on the server (CloudLinux's Python Selector * provides it), Passenger reading .htaccess (cPanel's Application Manager, CloudLinux, or LiteSpeed), MySQL 8 or * MariaDB 10.5+, and HTTPS. Every value that reaches a shell command goes through escapeshellarg(). * * It asks for a license number and checks it with the license server at clientharbor.org (LICENSE_URL) before it * installs anything; the installed app then checks it every hour (apps/core/license.py). * * deploy/cpanel/build_release.py stamps the release manifest URL, the license server's URL and the logo into this * file. */ const RELEASE_URL = 'https://clientharbor.org/releases/latest.json'; const LICENSE_URL = 'https://clientharbor.org/api/license.php'; const LOGO_PNG = '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'; const MIN_PYTHON = '3.12'; const JOB_TIMEOUT = 2400; // seconds a background step may run before it counts as stuck const HTACCESS_BEGIN = '# BEGIN Client Harbor'; const HTACCESS_END = '# END Client Harbor'; const CPANEL_BIN = '/usr/local/cpanel/bin/'; const DIRECTADMIN_PORT = 2222; error_reporting(E_ALL); ini_set('display_errors', '0'); @set_time_limit(300); ignore_user_abort(true); class InstallError extends Exception { } // ── The steps, in order ──────────────────────────────────────────────────────────────────────────────────── const STEPS = [ 'download' => 'Downloading Client Harbor', 'extract' => 'Unpacking the files', 'database' => 'Creating the database', 'settings' => 'Writing the settings', 'python' => 'Installing the Python packages (a few minutes)', 'setup' => 'Creating the tables and your administrator', 'cron' => 'Scheduling the background tasks', 'golive' => 'Turning on the website', ]; // ── Requests ─────────────────────────────────────────────────────────────────────────────────────────────── $action = $_GET['action'] ?? ''; if ($_SERVER['REQUEST_METHOD'] === 'POST' && $action !== '') { try { if ($action === 'start') { json_out(start_install($_POST)); } elseif ($action === 'step') { json_out(run_step((string) ($_POST['step'] ?? ''), (string) ($_POST['token'] ?? ''))); } throw new InstallError('Unknown action.'); } catch (InstallError $e) { json_out(['status' => 'error', 'message' => $e->getMessage()]); } catch (Throwable $e) { json_out(['status' => 'error', 'message' => 'Unexpected error: ' . $e->getMessage() . ' (' . basename($e->getFile()) . ':' . $e->getLine() . ')']); } } render_page(); exit; // ── Starting ─────────────────────────────────────────────────────────────────────────────────────────────── function start_install(array $in): array { if (!installer_stamped()) { throw new InstallError('This installer was not prepared for download.'); } $state = load_state(); foreach (array_keys($state['jobs'] ?? []) as $name) { if (job_status($name)['state'] === 'running') { throw new InstallError('An install is already running here. Wait a few minutes and try again.'); } } $token = trim((string) ($in['api_token'] ?? '')); if ($token !== '') { $state['api_token'] = $token; } $GLOBALS['api_token'] = $state['api_token'] ?? ''; $GLOBALS['mode'] = panel() === 'other' || (!empty($in['manual_db']) && panel() !== 'hostsecure') ? 'manual' : panel(); foreach (preflight() as $c) { if ($c['level'] === 'fail' || $c['level'] === 'token') { throw new InstallError($c['label'] . ': ' . strip_tags($c['detail'])); } } if (!empty(site_files()) && empty($in['replace_site'])) { throw new InstallError('Tick the box to confirm Client Harbor should replace the website at this address.'); } $email = trim((string) ($in['email'] ?? '')); if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { throw new InstallError('Enter a valid email address for the administrator.'); } $company = trim((string) ($in['company'] ?? '')); if ($company === '' || strlen($company) > 200) { throw new InstallError('Enter your company name.'); } $tz = (string) ($in['timezone'] ?? ''); if (!in_array($tz, DateTimeZone::listIdentifiers(), true)) { throw new InstallError('Choose a time zone.'); } $host = request_host(); $manual = mode() === 'manual'; $domains = $manual ? null : account_domains(); $base = $manual ? registrable_domain($host) : base_domain($host, $domains); if ($base === '') { throw new InstallError("$host isn't a domain in this " . panel_name() . ' account.'); } $portal = ''; if (!empty($in['client_area'])) { $portal = strtolower(trim((string) ($in['portal_host'] ?? ''))); if (!preg_match('/^[a-z0-9-]+(\.[a-z0-9-]+)+$/', $portal) || $portal === $host) { throw new InstallError('Enter the client area address, like clients.' . $base . '.'); } if (!$manual && base_domain($portal, $domains) === '') { throw new InstallError("$portal isn't on a domain in this " . panel_name() . ' account.'); } } // A database the customer made: check it before anything else happens if ($manual) { $state['db'] = manual_database($in); } elseif (!empty($state['db']['manual'])) { unset($state['db']); } $license = strtoupper((string) preg_replace('/\s+/', '', (string) ($in['license'] ?? ''))); if ($license === '') { throw new InstallError('Enter your license number.'); } activate_license($license, $host, $portal); $python = find_python(); $state = array_merge($state, [ 'mode' => mode(), 'notes' => [], 'license' => $license, 'token' => bin2hex(random_bytes(16)), 'started' => time(), 'done' => [], 'host' => $host, 'base' => $base, 'portal' => $portal, 'app' => $state['app'] ?? free_app_dir(), 'python' => $python['path'], 'admin' => [ 'email' => $email, 'first_name' => mb_substr(trim((string) ($in['first_name'] ?? '')), 0, 150), 'last_name' => mb_substr(trim((string) ($in['last_name'] ?? '')), 0, 150), 'company' => $company, 'timezone' => $tz, ], ]); unset($state['jobs']); save_state($state); return ['status' => 'done', 'token' => $state['token'], 'steps' => STEPS]; } function run_step(string $step, string $token): array { $state = load_state(); if (empty($state['token']) || !hash_equals($state['token'], $token)) { throw new InstallError('This install session has ended. Reload the page to start again.'); } if (!isset(STEPS[$step])) { throw new InstallError('Unknown step.'); } foreach (array_keys(STEPS) as $earlier) { if ($earlier === $step) { break; } if (empty($state['done'][$earlier])) { throw new InstallError('"' . STEPS[$earlier] . '" has to finish first.'); } } $GLOBALS['api_token'] = $state['api_token'] ?? ''; $GLOBALS['mode'] = $state['mode'] ?? panel(); try { $result = call_user_func_array('step_' . $step, [&$state]); } catch (InstallError $e) { save_state($state); // keep what the step did before failing (a started job, a created database) throw $e; } if ($result['status'] === 'done') { $state['done'][$step] = true; } if ($step !== 'golive' || $result['status'] !== 'done') { // golive deletes the state when it's done save_state($state); } return $result; } // ── The steps ────────────────────────────────────────────────────────────────────────────────────────────── function step_download(array &$s): array { $local = glob(__DIR__ . '/clientharbor-*.zip') ?: []; if ($local) { // uploaded next to the installer: no download needed usort($local, function ($a, $b) { return version_compare(zip_version($b), zip_version($a)); }); $s['zip'] = $local[0]; $s['version'] = zip_version($local[0]); return done('Using ' . basename($local[0]) . '.'); } $manifest = json_decode(http_get(RELEASE_URL), true); if (!is_array($manifest) || empty($manifest['url']) || empty($manifest['sha256'])) { throw new InstallError('The release information at ' . RELEASE_URL . " can't be read."); } $zip = state_dir() . '/release.zip'; http_download($manifest['url'], $zip); if (!hash_equals(strtolower($manifest['sha256']), (string) hash_file('sha256', $zip))) { @unlink($zip); throw new InstallError('The download was damaged (its checksum is wrong). Try again.'); } $s['zip'] = $zip; $s['version'] = (string) ($manifest['version'] ?? ''); return done('Downloaded version ' . $s['version'] . '.'); } function step_extract(array &$s): array { $app = $s['app']; if (!is_dir($app) && !@mkdir($app, 0755, true)) { throw new InstallError("Can't create the folder $app."); } if (class_exists('ZipArchive')) { $zip = new ZipArchive(); if ($zip->open($s['zip']) !== true || !$zip->extractTo($app)) { throw new InstallError("Can't unpack " . basename($s['zip']) . '.'); } $zip->close(); } else { [$code, $out] = run('unzip -oq ' . escapeshellarg($s['zip']) . ' -d ' . escapeshellarg($app)); if ($code !== 0) { throw new InstallError("Can't unpack " . basename($s['zip']) . ": $out"); } } if (!is_file("$app/manage.py") || !is_file("$app/passenger_wsgi.py")) { throw new InstallError(basename($s['zip']) . " isn't a Client Harbor release."); } foreach (['logs', 'media', 'private', 'tmp'] as $dir) { if (!is_dir("$app/$dir")) { @mkdir("$app/$dir", 0755); } } @chmod("$app/private", 0700); return done("Unpacked into $app."); } function step_database(array &$s): array { if (!empty($s['db']['ready'])) { return done('Using the ' . engine_name($s['db']['engine']) . ' database ' . $s['db']['name'] . '.'); } if (mode() === 'directadmin') { return database_directadmin($s); } if (mode() === 'hostsecure') { return database_hostsecure($s); } if (mode() !== 'cpanel') { throw new InstallError('No database was entered. Reload the page to start again.'); } // PostgreSQL when the account offers it, else MySQL/MariaDB. Decided once, so a retry doesn't switch halfway. if (empty($s['db']['engine'])) { $s['db'] = ['engine' => cpanel_has_postgres() ? 'postgres' : 'mysql']; } return $s['db']['engine'] === 'postgres' ? database_cpanel_postgres($s) : database_cpanel_mysql($s); } function cpanel_has_postgres(): bool { try { cpanel('Postgresql', 'list_databases'); // fails when the host doesn't run PostgreSQL or turned the feature off return true; } catch (InstallError $e) { return false; } } function database_cpanel_mysql(array &$s): array { $limits = cpanel('Mysql', 'get_restrictions'); $prefix = (string) ($limits['prefix'] ?? ''); if (empty($s['db']['name'])) { check_database_server(); $existing = array_column(cpanel('Mysql', 'list_databases') ?: [], 'database'); $s['db']['name'] = free_database_name($prefix, $existing, (int) ($limits['max_database_name_length'] ?? 64)); cpanel('Mysql', 'create_database', ['name' => $s['db']['name']]); save_state($s); // even if a later call fails, so trying again doesn't make another } if (empty($s['db']['user'])) { $user = new_database_user($prefix, (int) ($limits['max_username_length'] ?? 16)); $password = random_text(32); cpanel('Mysql', 'create_user', ['name' => $user, 'password' => $password]); $s['db'] += ['user' => $user, 'password' => $password, 'host' => database_host()]; } cpanel('Mysql', 'set_privileges_on_database', ['user' => $s['db']['user'], 'database' => $s['db']['name'], 'privileges' => 'ALL PRIVILEGES']); $s['db']['ready'] = true; return done('Created the MySQL database ' . $s['db']['name'] . ' and its user ' . $s['db']['user'] . '.'); } function database_cpanel_postgres(array &$s): array { $limits = cpanel('Postgresql', 'get_restrictions'); $prefix = (string) ($limits['prefix'] ?? ''); if (empty($s['db']['name'])) { $existing = array_column(cpanel('Postgresql', 'list_databases') ?: [], 'database'); $s['db']['name'] = free_database_name($prefix, $existing, (int) ($limits['max_database_name_length'] ?? 63)); cpanel('Postgresql', 'create_database', ['name' => $s['db']['name']]); save_state($s); } if (empty($s['db']['user'])) { $user = new_database_user($prefix, (int) ($limits['max_username_length'] ?? 63)); $password = random_text(32); cpanel('Postgresql', 'create_user', ['name' => $user, 'password' => $password]); $s['db'] += ['user' => $user, 'password' => $password, 'host' => 'localhost']; } cpanel('Postgresql', 'grant_all_privileges', ['user' => $s['db']['user'], 'database' => $s['db']['name']]); $s['db']['ready'] = true; return done('Created the PostgreSQL database ' . $s['db']['name'] . ' and its user ' . $s['db']['user'] . '.'); } /** DirectAdmin offers only MySQL/MariaDB. It prefixes the names with the account's user name and an underscore. */ function database_directadmin(array &$s): array { $prefix = account_user() . '_'; $existing = (array) (directadmin('CMD_API_DATABASES')['list'] ?? []); $suffix = substr(free_database_name($prefix, $existing, 64), strlen($prefix)); $user = substr(new_database_user($prefix, 32), strlen($prefix)); $password = random_text(32); // Creates the database, and the user with all privileges on it, in one call directadmin('CMD_API_DATABASES', ['action' => 'create', 'name' => $suffix, 'user' => $user, 'passwd' => $password, 'passwd2' => $password], true); $s['db'] = ['engine' => 'mysql', 'name' => $prefix . $suffix, 'user' => $prefix . $user, 'password' => $password, 'host' => database_host(), 'ready' => true]; return done('Created the MySQL database ' . $s['db']['name'] . ' and its user ' . $s['db']['user'] . '.'); } /** * HostSecure: a PostgreSQL database and its user in one call. HostSecure adds the account's prefix ("myacct_") to both * names itself and answers with the full ones. */ function database_hostsecure(array &$s): array { $existing = array_column((array) (hostsecure('GET', 'databases')['databases'] ?? []), 'name'); $name = 'clientharbor'; for ($i = 2; preg_grep('/_' . preg_quote($name, '/') . '$|^' . preg_quote($name, '/') . '$/', $existing); $i++) { $name = 'clientharbor' . $i; } $password = random_text(32); $made = hostsecure('POST', 'databases', ['engine' => 'postgresql', 'name' => $name, 'user' => 'ch' . strtolower(random_text(6)), 'password' => $password]); $db = (array) ($made['database'] ?? []); if (empty($db['name']) || empty($db['user'])) { throw new InstallError("HostSecure didn't say which database it created."); } $s['db'] = ['engine' => 'postgres', 'name' => (string) $db['name'], 'user' => (string) $db['user'], 'password' => $password, 'host' => 'localhost', 'ready' => true]; return done('Created the PostgreSQL database ' . $s['db']['name'] . ' and its user ' . $s['db']['user'] . '.'); } /** prefix + clientharbor, or clientharbor2... when that's taken. */ function free_database_name(string $prefix, array $existing, int $max): string { $name = $prefix . 'clientharbor'; for ($i = 2; in_array($name, $existing, true); $i++) { $name = $prefix . 'clientharbor' . $i; } return substr($name, 0, $max); } function new_database_user(string $prefix, int $max): string { $room = $max - strlen($prefix); if ($room < 4) { throw new InstallError("The hosting panel's database user names are too short to add one here."); } return $prefix . substr('ch' . strtolower(random_text(6)), 0, min($room, 8)); } /** The database the customer made and entered in the form (manual mode), once it's been checked. */ function manual_database(array $in): array { $engine = ($in['db_engine'] ?? '') === 'mysql' ? 'mysql' : 'postgres'; $name = trim((string) ($in['db_name'] ?? '')); $user = trim((string) ($in['db_user'] ?? '')); $password = (string) ($in['db_password'] ?? ''); $host = strtolower(trim((string) ($in['db_host'] ?? ''))) ?: 'localhost'; if (!preg_match('/^[A-Za-z0-9_-]{1,64}$/', $name)) { throw new InstallError('Enter the database name (letters, numbers, _ and - only).'); } if (!preg_match('/^[A-Za-z0-9_.-]{1,80}$/', $user)) { throw new InstallError('Enter the database user name.'); } if ($password === '') { throw new InstallError('Enter the database password.'); } if (!preg_match('/^[a-z0-9.-]+(:\d{1,5})?$/', $host)) { throw new InstallError('Enter the database server, like localhost.'); } if ($engine === 'mysql' && $host === 'localhost') { $host = database_host(); } check_manual_database($engine, $host, $name, $user, $password); return ['engine' => $engine, 'name' => $name, 'user' => $user, 'password' => $password, 'host' => $host, 'ready' => true, 'manual' => true]; } /** Connect with PHP's driver for the engine, when it has one, so wrong details show up before installing. */ function check_manual_database(string $engine, string $host, string $name, string $user, string $password): void { [$server, $port] = array_pad(explode(':', $host, 2), 2, null); $what = engine_name($engine); if ($engine === 'postgres') { if (!function_exists('pg_connect')) { return; // no driver here: Python checks it when the tables are made } $link = @pg_connect(sprintf("host='%s' port='%s' dbname='%s' user='%s' password='%s' connect_timeout=10", addcslashes($server, "'\\"), $port ?: '5432', addcslashes($name, "'\\"), addcslashes($user, "'\\"), addcslashes($password, "'\\"))); if (!$link) { throw new InstallError("Can't connect to the $what database $name as $user. Check the details " . '(and that this is a PostgreSQL database, not MySQL).'); } $version = (string) (pg_version($link)['server'] ?? ''); pg_close($link); if ($version !== '' && version_compare($version, '13', '<')) { throw new InstallError("Client Harbor needs PostgreSQL 13 or later, and this server has $version."); } return; } if (!class_exists('mysqli')) { return; } mysqli_report(MYSQLI_REPORT_OFF); $link = mysqli_init(); $socket = $server[0] === '/' ? $server : null; if (!@$link->real_connect($socket ? 'localhost' : $server, $user, $password, $name, $port ? (int) $port : null, $socket)) { throw new InstallError("Can't connect to the $what database $name as $user: " . mysqli_connect_error()); } $version = (string) $link->server_info; $link->close(); check_database_version($version); } function engine_name(string $engine): string { return $engine === 'postgres' ? 'PostgreSQL' : 'MySQL'; } function step_settings(array &$s): array { if (empty($s['secrets'])) { // kept across retries: the encryption key must never change once used $s['secrets'] = [ 'secret_key' => random_text(64), 'encryption_key' => strtr(base64_encode(random_bytes(32)), '+/', '-_'), ]; } $db = $s['db']; $hosts = [$s['host']]; if ($s['host'] === $s['base']) { $hosts[] = 'www.' . $s['base']; } $portal = $s['portal'] ?: 'clients.' . $s['base']; $values = [ 'DJANGO_SETTINGS_MODULE' => 'config.settings.cpanel', 'DEBUG' => 'False', 'SECRET_KEY' => $s['secrets']['secret_key'], 'ALLOWED_HOSTS' => implode(',', $hosts), 'SITE_URL' => 'https://' . $s['host'], 'PORTAL_HOST' => $portal, 'PORTAL_URL' => 'https://' . $portal, 'DATABASE_URL' => database_url($db), 'FIELD_ENCRYPTION_KEY' => $s['secrets']['encryption_key'], 'LICENSE_KEY' => $s['license'], 'LICENSE_URL' => LICENSE_URL, 'DEFAULT_FROM_EMAIL' => 'noreply@' . $s['base'], 'EMAIL_HOST' => 'localhost', 'EMAIL_PORT' => '25', 'EMAIL_USE_TLS' => 'False', 'SENTRY_DSN' => '', ]; $env = '# Client Harbor settings, written by the installer on ' . date('Y-m-d') . ". Keep this file private.\n" . "# Back up FIELD_ENCRYPTION_KEY: stored email passwords can't be read without it.\n" . "# After changing anything here, restart the app: touch tmp/restart.txt\n"; foreach ($values as $k => $v) { $env .= "$k=$v\n"; } write_private($s['app'] . '/.env', $env); return done('Wrote ' . $s['app'] . '/.env.'); } function database_url(array $db): string { // A socket path (MySQL on localhost) is URL-encoded whole; dj-database-url decodes it and Django sees the path $host = $db['host'][0] === '/' ? rawurlencode($db['host']) : $db['host']; return sprintf('%s://%s:%s@%s/%s', $db['engine'] === 'postgres' ? 'postgres' : 'mysql', rawurlencode($db['user']), rawurlencode($db['password']), $host, $db['name']); } function step_python(array &$s): array { $app = escapeshellarg($s['app']); $python = escapeshellarg($s['python']); $pip = 'venv/bin/python -m pip install --no-cache-dir --disable-pip-version-check'; return job_step($s, 'python', "cd $app\n" . "echo \"Using \$($python --version) at $python\"\n" . "$python -m venv venv\n" . "$pip --upgrade pip\n" . "$pip -r requirements/cpanel.txt\n", 'The Python packages are installed.'); } function step_setup(array &$s): array { $a = $s['admin']; $script = 'cd ' . escapeshellarg($s['app']) . "\n"; if ($s['db']['engine'] === 'mysql') { $script .= <<<'SH' echo "== Preparing the database" venv/bin/python manage.py shell <<'PY' from django.db import connection with connection.cursor() as cursor: # hosting panels make databases in the server's default character set cursor.execute("ALTER DATABASE `%s` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci" % connection.settings_dict["NAME"]) PY SH; } $script .= <<<'SH' echo "== Creating the tables" venv/bin/python manage.py migrate --no-input echo "== Collecting the static files" venv/bin/python manage.py collectstatic --no-input -v 0 SH; if (empty($s['admin_password'])) { $script .= "echo \"== Creating your administrator\"\n" . 'venv/bin/python manage.py setup_instance --no-input' . ' --email ' . escapeshellarg($a['email']) . ' --company ' . escapeshellarg($a['company']) . ' --timezone ' . escapeshellarg($a['timezone']) . ($a['first_name'] !== '' ? ' --first-name ' . escapeshellarg($a['first_name']) : '') . ($a['last_name'] !== '' ? ' --last-name ' . escapeshellarg($a['last_name']) : '') . "\n"; } $result = job_step($s, 'setup', $script, 'The database is ready.'); if ($result['status'] === 'done' && empty($s['admin_password'])) { $log = (string) @file_get_contents(state_dir() . '/setup.log'); if (!preg_match('/Temporary password: (\S+)/', $log, $m)) { throw new InstallError("The administrator was created, but its password couldn't be read from the log."); } $s['admin_password'] = $m[1]; } return $result; } function step_cron(array &$s): array { $command = 'cd ' . escapeshellarg($s['app']) . ' && venv/bin/python manage.py run_scheduled >> logs/scheduled.log 2>&1'; $by_hand = function ($where) use (&$s, $command) { $s['notes'][] = "Add a cron job $where that runs every minute (* in every field), with the command: $command"; return done("Couldn't add the cron job, so you'll add it yourself (the last page shows how)."); }; if (mode() === 'hostsecure') { // Through the panel, so the job shows in its Cron Jobs page like any other try { foreach ((array) (hostsecure('GET', 'cron')['cron_jobs'] ?? []) as $job) { if (($job['command'] ?? '') === $command) { return done('The cron job is already there.'); } } hostsecure('POST', 'cron', ['schedule' => '* * * * *', 'command' => $command]); return done('Added a cron job that runs every minute.'); } catch (InstallError $e) { return $by_hand("in HostSecure's Cron Jobs"); } } if (mode() === 'directadmin') { // DirectAdmin rewrites the crontab from its own list, so a line added with crontab wouldn't last try { return cron_directadmin($command); } catch (InstallError $e) { return $by_hand("in DirectAdmin's Cron Jobs"); } } $result = cron_by_crontab($command); if ($result !== null) { return $result; } if (mode() === 'cpanel') { return cron_by_api($command); } return $by_hand("in your hosting panel's cron jobs"); } /** Add the line with the crontab command; null when crontab can't be used here. */ function cron_by_crontab(string $command): ?array { [$code, $current] = run('crontab -l'); if ($code !== 0 && stripos($current, 'no crontab') === false) { return null; } if ($code !== 0) { $current = ''; } if (strpos($current, $command) !== false) { return done('The cron job is already there.'); } $file = state_dir() . '/crontab'; file_put_contents($file, ($current === '' ? '' : rtrim($current) . "\n") . "# Client Harbor: scheduled tasks (reminders, mailbox checks, recurring invoices)\n" . "* * * * * $command\n"); [$code] = run('crontab ' . escapeshellarg($file)); @unlink($file); return $code === 0 ? done('Added a cron job that runs every minute.') : null; } function cron_directadmin(string $command): array { foreach (directadmin('CMD_API_CRON_JOBS') as $line) { // id => "minute hour ... command" if (is_string($line) && strpos($line, $command) !== false) { return done('The cron job is already there.'); } } directadmin('CMD_API_CRON_JOBS', ['action' => 'create', 'minute' => '*', 'hour' => '*', 'dayofmonth' => '*', 'month' => '*', 'dayofweek' => '*', 'command' => $command], true); return done('Added a cron job that runs every minute.'); } function cron_by_api(string $command): array { try { foreach (cpanel('Cron', 'listcron', [], 2) ?: [] as $job) { if (($job['command'] ?? '') === $command) { return done('The cron job is already there.'); } } } catch (InstallError $e) { // can't list them: add it anyway } cpanel('Cron', 'add_line', ['command' => $command, 'minute' => '*', 'hour' => '*', 'day' => '*', 'month' => '*', 'weekday' => '*'], 2); return done('Added a cron job that runs every minute.'); } function step_golive(array &$s): array { $app = $s['app']; $notes = $s['notes'] ?? []; // Send this address's requests to the Python app if (mode() === 'hostsecure') { golive_hostsecure($s['host'], $app); } else { point_folder_at_app(__DIR__, $app); } // The client area: a subdomain the same app answers if ($s['portal'] !== '') { try { if (mode() === 'hostsecure') { $notes[] = add_portal_subdomain_hostsecure($s['portal'], $app); } elseif (mode() === 'cpanel') { $notes[] = add_portal_subdomain($s['portal']); } elseif (mode() === 'directadmin') { $notes[] = add_portal_subdomain_directadmin($s['portal'], $app); } else { $notes[] = 'In your hosting panel, add the subdomain ' . $s['portal'] . ' with the folder ' . home_relative(__DIR__) . ' and an SSL certificate. If the panel picks the folder itself, ' . 'copy the .htaccess file from ' . home_relative(__DIR__) . ' into it.'; } } catch (InstallError $e) { $notes[] = 'The client area subdomain could not be added (' . $e->getMessage() . '). In ' . panel_name() . ', add ' . $s['portal'] . ' with the folder ' . home_relative(__DIR__) . '.'; } } if (mode() === 'cpanel') { try { cpanel('SSL', 'start_autossl_check'); } catch (InstallError $e) { // AutoSSL runs on its own schedule anyway } } @touch("$app/tmp/restart.txt"); file_put_contents("$app/logs/install.log", sprintf("Installed Client Harbor %s on %s for %s\nPanel: %s\n" . "Python: %s\nDatabase: %s %s (user %s)\nSite folder: %s\n", $s['version'], date('c'), $s['host'], mode(), $s['python'], engine_name($s['db']['engine']), $s['db']['name'], $s['db']['user'], __DIR__)); $result = done('Client Harbor is installed.'); $result['summary'] = [ 'url' => 'https://' . $s['host'] . '/login/', 'email' => $s['admin']['email'], 'password' => $s['admin_password'], 'encryption_key' => $s['secrets']['encryption_key'], 'app' => $app, 'portal' => $s['portal'] !== '' ? 'https://' . $s['portal'] . '/' : '', 'database' => engine_name($s['db']['engine']) . ' ' . $s['db']['name'], 'notes' => $notes, 'api_token_used' => !empty($s['api_token']) && mode() !== 'manual' ? credential_name() : '', ]; // Clean up: the state (with its passwords), the download, and this installer foreach (array_merge(glob(state_dir() . '/*') ?: [], glob(state_dir() . '/.*') ?: []) as $file) { if (is_file($file)) { @unlink($file); } } @rmdir(state_dir()); foreach (glob(__DIR__ . '/clientharbor-*.zip') ?: [] as $zip) { @unlink($zip); } @unlink(__FILE__); return $result; } function add_portal_subdomain(string $portal): string { $domains = account_domains(); if (in_array($portal, $domains['all'], true)) { return "$portal was already in cPanel: make sure its folder is " . home_relative(__DIR__) . '.'; } $root = base_domain($portal, $domains); cpanel('SubDomain', 'addsubdomain', [ 'domain' => substr($portal, 0, -strlen($root) - 1), 'rootdomain' => $root, 'dir' => home_relative(__DIR__), 'disallowdot' => 0, ]); return "Added the client area at $portal. Its SSL certificate can take a few minutes to arrive."; } /** DirectAdmin puts a subdomain's folder inside its domain's public_html, so that folder gets the .htaccess too. */ function add_portal_subdomain_directadmin(string $portal, string $app): string { $domains = account_domains(); $root = base_domain($portal, $domains); $label = substr($portal, 0, -strlen($root) - 1); if (!in_array($portal, $domains['all'], true)) { directadmin('CMD_API_SUBDOMAINS', ['action' => 'create', 'domain' => $root, 'subdomain' => $label], true); } $folder = home_dir() . "/domains/$root/public_html/$label"; if (!is_dir($folder) && !@mkdir($folder, 0755, true)) { throw new InstallError("can't create $folder"); } point_folder_at_app($folder, $app); return "Added the client area at $portal. In DirectAdmin, under SSL Certificates, add $portal to your " . "Let's Encrypt certificate."; } /** * HostSecure serves a Python app through its App Manager: the domain's web site (http and https) is switched to the * app, which stays in the account's folder beside public_html, where no site serves it as files. */ function golive_hostsecure(string $host, string $app): void { @chmod($app, 0755); // the web server only passes through; .env and private/ keep their own modes if (!is_dir("$app/public")) { @mkdir("$app/public", 0755); } hostsecure('POST', 'hosted-apps', ['domain' => $host, 'type' => 'python', 'app_root' => '~/' . basename($app)]); } /** The client area on HostSecure: the subdomain, then the same app on it. */ function add_portal_subdomain_hostsecure(string $portal, string $app): string { $domains = account_domains(); if (!in_array($portal, $domains['all'], true)) { $root = base_domain($portal, $domains); hostsecure('POST', 'subdomains', ['label' => substr($portal, 0, -strlen($root) - 1), 'parent' => $root]); } hostsecure('POST', 'hosted-apps', ['domain' => $portal, 'type' => 'python', 'app_root' => '~/' . basename($app)]); return "Added the client area at $portal. Its SSL certificate can take a few minutes to arrive."; } /** Passenger lines at the top of the folder's .htaccess, keeping (and backing up) what was there. */ function point_folder_at_app(string $folder, string $app): void { $htaccess = "$folder/.htaccess"; $current = is_file($htaccess) ? (string) file_get_contents($htaccess) : ''; if ($current !== '' && !is_file("$htaccess.before-clientharbor")) { copy($htaccess, "$htaccess.before-clientharbor"); } $current = trim((string) preg_replace('/' . preg_quote(HTACCESS_BEGIN, '/') . '.*?' . preg_quote(HTACCESS_END, '/') . '\R?/s', '', $current)); $block = HTACCESS_BEGIN . " (added by the installer: this site is the Python app in $app)\n" . "PassengerAppRoot \"$app\"\n" . "PassengerBaseURI \"/\"\n" . "PassengerPython \"$app/venv/bin/python\"\n" . HTACCESS_END . "\n"; if (file_put_contents($htaccess, $block . ($current === '' ? '' : "\n$current\n")) === false) { throw new InstallError("Can't write $htaccess."); } foreach (['index.html', 'index.htm', 'index.php'] as $index) { // they'd be served instead of the app if (is_file("$folder/$index")) { rename("$folder/$index", "$folder/$index.before-clientharbor"); } } } // ── Background jobs (steps that take longer than a web request may) ──────────────────────────────────────── /** Start the job on the first call, then report on it each time the page polls. */ function job_step(array &$s, string $name, string $script, string $doneMessage): array { if (empty($s['jobs'][$name])) { start_job($name, $script); $s['jobs'][$name] = ['started' => time()]; return ['status' => 'running', 'message' => 'Started.', 'log' => '']; } $job = job_status($name); if ($job['state'] === 'done') { unset($s['jobs'][$name]); return done($doneMessage); } if ($job['state'] !== 'running' || time() - $s['jobs'][$name]['started'] > JOB_TIMEOUT) { unset($s['jobs'][$name]); // so trying again starts it afresh throw new InstallError(($job['state'] === 'failed' ? 'This step failed.' : 'This step stopped responding.') . ($job['log'] !== '' ? "\n\n" . $job['log'] : '')); } return ['status' => 'running', 'message' => '', 'log' => $job['log']]; } function start_job(string $name, string $script): void { $dir = state_dir(); @unlink("$dir/$name.exit"); @unlink("$dir/$name.log"); file_put_contents("$dir/$name.sh", "set -e\nexport LANG=C.UTF-8 PYTHONIOENCODING=utf-8 PYTHONUNBUFFERED=1\n" . $script); $inner = escapeshellarg("sh $name.sh > $name.log 2>&1; echo \$? > $name.exit"); // Detached, so it carries on after this request ends run('cd ' . escapeshellarg($dir) . ' && if command -v setsid >/dev/null 2>&1; then setsid sh -c ' . $inner . ' /dev/null 2>&1 & else nohup sh -c ' . $inner . ' /dev/null 2>&1 & fi'); } /** ['state' => running|done|failed|none, 'log' => the log's last lines] */ function job_status(string $name): array { $dir = state_dir(); $log = is_file("$dir/$name.log") ? tail((string) file_get_contents("$dir/$name.log"), 15) : ''; if (!is_file("$dir/$name.exit")) { return ['state' => is_file("$dir/$name.sh") ? 'running' : 'none', 'log' => $log]; } $code = (int) trim((string) file_get_contents("$dir/$name.exit")); return ['state' => $code === 0 ? 'done' : 'failed', 'log' => $log]; } // ── Checks shown before installing ───────────────────────────────────────────────────────────────────────── /** Each: ['level' => ok|warn|token|fail, 'label' => ..., 'detail' => HTML]. "token": needs a cPanel API token. */ function preflight(): array { $checks = []; $add = function ($level, $label, $detail = '') use (&$checks) { $checks[] = ['level' => $level, 'label' => $label, 'detail' => $detail]; }; if (!installer_stamped()) { $add('fail', 'Installer', 'This copy was not prepared for download. Build it with deploy/cpanel/build_release.py.'); } if (PHP_VERSION_ID < 70400) { $add('fail', 'PHP', 'PHP 7.4 or later is needed (this is ' . PHP_VERSION . '). Choose a newer one in MultiPHP Manager.'); } if (!exec_available()) { $add('fail', 'Running commands', 'PHP is not allowed to run commands here (proc_open is disabled). ' . (panel() === 'hostsecure' ? 'Ask your host to turn on Running commands for this account (in HostSecure: Edit Panel → Running commands). It can be turned off again once Client Harbor is installed.' : 'Ask your host to allow it for this account.')); return $checks; } $add('ok', 'Running commands'); if (!is_https()) { $https = 'https://' . request_host() . strtok((string) $_SERVER['REQUEST_URI'], '?'); $add('fail', 'HTTPS', 'Open the installer over HTTPS: ' . h($https) . '. ' . "If that doesn't load, the address has no SSL certificate yet: " . ([ 'cpanel' => 'in cPanel, open SSL/TLS Status and click Run AutoSSL.', 'directadmin' => "in DirectAdmin, open SSL Certificates and get a free Let's Encrypt certificate.", ][panel()] ?? "get one in your hosting panel (most offer free Let's Encrypt certificates).")); } else { $add('ok', 'HTTPS'); } $docroot = realpath((string) ($_SERVER['DOCUMENT_ROOT'] ?? '')); if ($docroot && $docroot !== realpath(__DIR__)) { $where = ['cpanel' => 'In cPanel, under Domains,', 'directadmin' => 'In DirectAdmin, under Subdomain Management,']; $add('fail', 'Folder', 'The installer has to be in the top folder of the address it runs on, but it is in a subfolder. ' . ($where[panel()] ?? 'In your hosting panel,') . ' create a subdomain such as crm.' . h(request_host()) . ' with a folder of its own, and upload the installer there.'); } elseif ($files = site_files()) { $add('warn', 'Folder', 'This folder already has a website (' . h(implode(', ', array_slice($files, 0, 5))) . (count($files) > 5 ? ', ...' : '') . '). Client Harbor will take over this address.'); } else { $add('ok', 'Folder', h(home_relative(__DIR__))); } if (mode() === 'manual') { $add('ok', 'Hosting panel', panel() === 'other' ? "Neither cPanel nor DirectAdmin: you'll enter a database you've made, and the installer does the rest." : "You'll enter a database you've made yourself."); } else { $label = panel_name() . ' API'; try { account_domains(); $add('ok', $label, mode() === 'cpanel' && api_mode() === 'cli' ? '' : 'Using your ' . credential_name() . '.'); if (mode() === 'hostsecure' || (mode() === 'cpanel' && cpanel_has_postgres())) { $add('ok', 'Database', 'PostgreSQL'); } else { $add('ok', 'Database', 'MySQL or MariaDB (' . h(panel_name()) . " doesn't offer PostgreSQL here)"); } } catch (InstallError $e) { if (!empty($GLOBALS['api_token'])) { $add('fail', $label, 'Your ' . credential_name() . ' was not accepted: ' . h($e->getMessage())); } elseif (mode() === 'hostsecure') { $add('token', $label, 'The installer needs a HostSecure API token to create the database and the cron job ' . 'and to switch this address over to Client Harbor. In your HostSecure panel, open API Tokens, ' . 'create one, and paste it below.'); } elseif (mode() === 'directadmin') { $add('token', $label, 'To create the database for you, the installer needs a DirectAdmin Login Key. ' . 'In DirectAdmin, open Login Keys, create one, and paste it below. Or make the database yourself.'); } else { $add('token', $label, 'To create the database for you, the installer needs a cPanel API token. ' . 'In cPanel, open Manage API Tokens, create one, and paste it below. Or make the database yourself.'); } } } try { $python = find_python(); $add('ok', 'Python', 'Python ' . h($python['version'])); } catch (InstallError $e) { $add('fail', 'Python', h($e->getMessage())); } if (!glob(__DIR__ . '/clientharbor-*.zip') && !function_exists('curl_init') && !ini_get('allow_url_fopen') && !command_exists('curl')) { $add('fail', 'Downloading', "PHP can't download files here. Upload the Client Harbor zip next to the installer instead."); } if (!class_exists('ZipArchive') && !command_exists('unzip')) { $add('fail', 'Unpacking', "Neither PHP's zip extension nor the unzip command is available. Turn on the zip extension in Select PHP Version."); } if (!is_writable(__DIR__) || !is_writable(home_dir())) { $add('fail', 'Permissions', "The installer can't write to your home folder or this folder."); } return $checks; } function check_database_server(): void { try { $info = cpanel('Mysql', 'get_server_information'); } catch (InstallError $e) { return; // older cPanel: Django checks the version itself when it connects } check_database_version((string) ($info['version'] ?? ''), (string) ($info['type'] ?? '')); } /** InstallError when the MySQL or MariaDB server is older than Django supports. */ function check_database_version(string $version, string $type = ''): void { $version = (string) preg_replace('/^5\.5\.5-/', '', $version); // how MariaDB reports itself to MySQL clients if (!preg_match('/^(\d+)\.(\d+)(?:\.(\d+))?/', $version, $m)) { return; } $mariadb = stripos("$version $type", 'mariadb') !== false; $needed = $mariadb ? '10.5' : '8.0.11'; if (version_compare("$m[1].$m[2]." . ($m[3] ?? '0'), $needed, '<')) { throw new InstallError(sprintf('Client Harbor needs %s %s or later, and this server has %s. Ask your host to upgrade it.', $mariadb ? 'MariaDB' : 'MySQL', $needed, $version)); } } function find_python(): array { static $found = null; if ($found !== null) { return $found; } $candidates = []; foreach (['3.12', '3.13', '3.14'] as $v) { $short = str_replace('.', '', $v); $candidates[] = "/opt/alt/python$short/bin/python$v"; // CloudLinux's Python Selector $candidates[] = "/usr/local/bin/python$v"; $candidates[] = "/usr/bin/python$v"; $candidates[] = "python$v"; } $candidates[] = 'python3'; $check = escapeshellarg('import sys, venv, ensurepip; print("%d.%d" % sys.version_info[:2])'); $seen = []; foreach ($candidates as $python) { [$code, $out] = run(escapeshellarg($python) . " -c $check"); $version = trim($out); if ($code !== 0 || !preg_match('/^\d+\.\d+$/', $version)) { continue; } $seen[$version] = true; if (version_compare($version, MIN_PYTHON, '>=')) { if (strpos($python, '/') === false) { [, $where] = run('command -v ' . escapeshellarg($python)); $python = trim($where) ?: $python; } return $found = ['path' => $python, 'version' => $version]; } } throw new InstallError('Python ' . MIN_PYTHON . ' or later is needed but was not found' . ($seen ? ' (found ' . implode(', ', array_keys($seen)) . ')' : '') . '. Ask your host for Python ' . MIN_PYTHON . ' (CloudLinux hosts provide it through Setup Python App).'); } /** Files in this folder other than the installer and what cPanel puts in every site folder. */ function site_files(): array { $ignore = ['.', '..', basename(__FILE__), '.htaccess', 'cgi-bin', '.well-known', 'error_log', '.user.ini', 'php.ini']; $files = []; foreach (scandir(__DIR__) ?: [] as $f) { if (!in_array($f, $ignore, true) && !preg_match('/^clientharbor-.*\.zip$|\.before-clientharbor$/', $f)) { $files[] = $f; } } return $files; } // ── Hosting panels ───────────────────────────────────────────────────────────────────────────────────────── /** The hosting panel on this server: cpanel, directadmin or other. */ function panel(): string { static $panel = null; if ($panel === null) { $panel = 'other'; if (@is_dir('/usr/local/cpanel') || @is_file(CPANEL_BIN . 'uapi')) { $panel = 'cpanel'; } elseif (hostsecure_detected()) { $panel = 'hostsecure'; } elseif (@is_dir('/usr/local/directadmin') || preg_match('#^/home\d*/[^/]+/domains/[^/]+/public_html#', __DIR__)) { $panel = 'directadmin'; } } return $panel; } /** How this install talks to the panel: cpanel, directadmin, or manual (the customer made the database). */ function mode(): string { return $GLOBALS['mode'] ?? (panel() === 'other' ? 'manual' : panel()); } function panel_name(): string { return ['cpanel' => 'cPanel', 'directadmin' => 'DirectAdmin', 'hostsecure' => 'HostSecure'][panel()] ?? 'hosting panel'; } function credential_name(): string { return ['directadmin' => 'DirectAdmin Login Key', 'hostsecure' => 'HostSecure API token'][panel()] ?? 'cPanel API token'; } /** * Call DirectAdmin's API as this account, with a Login Key (or the account's password), and return its answer. * The API answers in URL-encoded form: error=1&text=...&details=..., or list[]=a&list[]=b for lists. */ function directadmin(string $command, array $args = [], bool $post = false): array { static $base = null; $key = (string) ($GLOBALS['api_token'] ?? ''); if ($key === '') { throw new InstallError('A DirectAdmin Login Key is needed.'); } $headers = ['Authorization: Basic ' . base64_encode(account_user() . ':' . $key)]; $status = 0; $body = ''; // DirectAdmin's own port on this server, over HTTPS or plain HTTP; its certificate is for the hostname foreach ($base !== null ? [$base] : ['https://127.0.0.1:' . DIRECTADMIN_PORT, 'http://127.0.0.1:' . DIRECTADMIN_PORT] as $try) { $url = "$try/$command" . (!$post && $args ? '?' . http_build_query($args) : ''); [$status, $body] = http_request($url, $post ? $args : null, $headers, false); if ($status !== 0) { $base = $try; break; } } if ($status === 0) { throw new InstallError("Can't reach DirectAdmin on port " . DIRECTADMIN_PORT . '.'); } if ($status === 401 || $status === 403 || stripos($body, '= 400) { throw new InstallError("DirectAdmin answered $command with HTTP $status."); } parse_str(trim($body), $data); if (($data['error'] ?? '0') !== '0') { throw new InstallError(trim(($data['text'] ?? "$command failed.") . ' ' . ($data['details'] ?? ''))); } return $data; } // ── HostSecure ───────────────────────────────────────────────────────────────────────────────────────────── /** A HostSecure account's folder (/var/www/html/) when this file is in its public_html, else ''. */ function hostsecure_account_dir(): string { return preg_match('#^(/var/www/html/[a-z0-9_]+)/public_html(/|$)#', __DIR__ . '/', $m) ? $m[1] : ''; } /** HostSecure keeps sites in /var/www/html//public_html, and its API on this server asks for a token. */ function hostsecure_detected(): bool { if (hostsecure_account_dir() === '') { return false; } [$status, $body] = http_request('https://127.0.0.1/api/v1.php/index', null, ['Accept: application/json'], false); $json = json_decode($body, true); return $status === 401 && is_array($json) && ($json['error'] ?? '') === 'missing_token'; } /** Call HostSecure's API on this server as this account; InstallError with HostSecure's message. */ function hostsecure(string $method, string $path, ?array $body = null): array { $token = (string) ($GLOBALS['api_token'] ?? ''); if ($token === '') { throw new InstallError('A HostSecure API token is needed.'); } $url = 'https://127.0.0.1/api/v1.php/' . $path; $headers = ['Authorization: Bearer ' . $token, 'Accept: application/json', 'Content-Type: application/json']; $data = $body === null ? null : json_encode($body); if (function_exists('curl_init')) { // The panel's own vhost on this server: its certificate is for the hostname, not 127.0.0.1 $ch = curl_init($url); curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 300, CURLOPT_HTTPHEADER => $headers, CURLOPT_CUSTOMREQUEST => $method, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_SSL_VERIFYHOST => 0]); if ($data !== null) { curl_setopt($ch, CURLOPT_POSTFIELDS, $data); } $raw = curl_exec($ch); $status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); $raw = $raw === false ? '' : (string) $raw; } else { $context = stream_context_create(['http' => ['method' => $method, 'timeout' => 300, 'ignore_errors' => true, 'header' => implode("\r\n", $headers), 'content' => (string) $data], 'ssl' => ['verify_peer' => false, 'verify_peer_name' => false]]); $raw = (string) @file_get_contents($url, false, $context); $status = isset($http_response_header[0]) && preg_match('/\s(\d{3})\s?/', $http_response_header[0], $m) ? (int) $m[1] : 0; } $json = json_decode($raw, true); if ($status === 0) { throw new InstallError("Can't reach HostSecure's API on this server."); } if (!is_array($json)) { throw new InstallError("HostSecure answered $method $path with HTTP $status."); } if ($status >= 400 || ($json['ok'] ?? true) === false) { $why = trim((string) ($json['detail'] ?? '') ?: (string) ($json['error'] ?? "HTTP $status")); if ($status === 401) { $why = 'HostSecure did not accept the API token' . ($why !== '' ? " ($why)" : '') . '.'; } elseif ($status === 403) { $why = "The API token isn't allowed to do this ($why). Give it the Databases, Cron jobs and Applications " . '(and, for a client area, Domains) permissions.'; } throw new InstallError($why); } return $json; } /** The domain someone registered, for a host on a panel that can't list its domains: crm.example.co.uk → example.co.uk */ function registrable_domain(string $host): string { $labels = explode('.', $host); $n = count($labels); $keep = $n >= 3 && strlen($labels[$n - 1]) === 2 && in_array($labels[$n - 2], ['co', 'com', 'net', 'org', 'ac', 'gov', 'edu'], true) ? 3 : 2; return implode('.', array_slice($labels, -min($keep, $n))); } // ── cPanel ───────────────────────────────────────────────────────────────────────────────────────────────── /** 'cli' when this account can run cPanel's uapi command, else 'token' (an API token over HTTPS). */ function api_mode(): string { static $mode = null; if ($mode === null) { $mode = 'token'; if (empty($GLOBALS['api_token']) && exec_available()) { [$code, $out] = run(CPANEL_BIN . 'uapi --output=json Variables get_user_information'); $json = json_decode(json_part($out), true); if ($code === 0 && !empty($json['result']['status'])) { $mode = 'cli'; } } } return $mode; } /** Call cPanel's API (UAPI, or API 2 for cron jobs) and return its data; InstallError with cPanel's message. */ function cpanel(string $module, string $function, array $args = [], int $version = 3) { if (api_mode() === 'cli') { $command = CPANEL_BIN . ($version === 3 ? 'uapi' : 'cpapi2') . ' --output=json ' . escapeshellarg($module) . ' ' . escapeshellarg($function); foreach ($args as $k => $v) { $command .= ' ' . escapeshellarg($k . '=' . rawurlencode((string) $v)); } [, $out] = run($command); $json = json_decode(json_part($out), true); $result = $version === 3 ? ($json['result'] ?? null) : ($json['cpanelresult'] ?? null); } else { $token = $GLOBALS['api_token'] ?? ''; if ($token === '') { throw new InstallError('A cPanel API token is needed.'); } $url = 'https://127.0.0.1:2083/' . ($version === 3 ? "execute/$module/$function?" . http_build_query($args) : 'json-api/cpanel?' . http_build_query(['cpanel_jsonapi_user' => account_user(), 'cpanel_jsonapi_apiversion' => 2, 'cpanel_jsonapi_module' => $module, 'cpanel_jsonapi_func' => $function] + $args)); // cPanel's own port on this server: its certificate is for the hostname, not 127.0.0.1 $json = json_decode(http_get($url, ['Authorization: cpanel ' . account_user() . ':' . $token], false), true); $result = $version === 3 ? $json : ($json['cpanelresult'] ?? null); } if (!is_array($result)) { throw new InstallError("cPanel didn't answer $module::$function."); } if ($version === 3 && empty($result['status'])) { throw new InstallError(implode(' ', (array) ($result['errors'] ?? ["$module::$function failed."]))); } if ($version === 2 && (!empty($result['error']) || empty($result['event']['result']))) { throw new InstallError((string) ($result['error'] ?? "$module::$function failed.")); } return $result['data'] ?? null; } /** The account's domains: ['roots' => main, addon and parked domains, 'all' => the roots and subdomains] (cPanel or DirectAdmin) */ function account_domains(): array { static $domains = null; if ($domains === null && mode() === 'hostsecure') { $roots = []; $all = []; foreach ((array) (hostsecure('GET', 'domains')['domains'] ?? []) as $d) { $name = strtolower((string) ($d['domain'] ?? '')); if ($name === '') { continue; } $all[] = $name; if (($d['type'] ?? '') !== 'subdomain') { $roots[] = $name; } } $domains = ['roots' => $roots, 'all' => $all]; } elseif ($domains === null && mode() === 'directadmin') { $roots = array_values((array) (directadmin('CMD_API_SHOW_DOMAINS')['list'] ?? [])); $all = $roots; foreach ($roots as $root) { foreach ((array) (directadmin('CMD_API_SUBDOMAINS', ['domain' => $root])['list'] ?? []) as $sub) { $all[] = "$sub.$root"; } } $domains = ['roots' => $roots, 'all' => $all]; } elseif ($domains === null) { $d = cpanel('DomainInfo', 'list_domains'); $roots = array_merge([(string) $d['main_domain']], (array) ($d['addon_domains'] ?? []), (array) ($d['parked_domains'] ?? [])); $domains = ['roots' => $roots, 'all' => array_merge($roots, (array) ($d['sub_domains'] ?? []))]; } return $domains; } /** The account domain that host is, or is under ('' when none). */ function base_domain(string $host, array $domains): string { $best = ''; foreach ($domains['roots'] as $root) { if (($host === $root || substr($host, -strlen($root) - 1) === ".$root") && strlen($root) > strlen($best)) { $best = $root; } } return $best; } function database_host(): string { foreach (['/var/lib/mysql/mysql.sock', '/var/run/mysqld/mysqld.sock', '/tmp/mysql.sock'] as $socket) { if (@file_exists($socket)) { return $socket; // cPanel's database users are for "localhost", which a TCP connection may not match } } return 'localhost'; } // ── Helpers ──────────────────────────────────────────────────────────────────────────────────────────────── function exec_available(): bool { $disabled = array_map('trim', explode(',', (string) ini_get('disable_functions'))); return function_exists('proc_open') && !in_array('proc_open', $disabled, true); } /** Run a shell command; returns [exit code, its output (stdout and stderr)]. */ function run(string $command): array { $env = ['HOME' => home_dir(), 'USER' => account_user(), 'LANG' => 'C.UTF-8', 'PATH' => '/usr/local/bin:/usr/bin:/bin:' . rtrim(CPANEL_BIN, '/')]; $proc = @proc_open(['/bin/sh', '-c', "$command 2>&1"], [0 => ['file', '/dev/null', 'r'], 1 => ['pipe', 'w']], $pipes, home_dir(), $env); if (!is_resource($proc)) { return [127, 'Could not run the command.']; } $out = (string) stream_get_contents($pipes[1]); fclose($pipes[1]); return [proc_close($proc), trim($out)]; } function command_exists(string $name): bool { return exec_available() && run('command -v ' . escapeshellarg($name))[0] === 0; } function http_get(string $url, array $headers = [], bool $verify = true): string { if (function_exists('curl_init')) { $ch = curl_init($url); curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => true, CURLOPT_TIMEOUT => 60, CURLOPT_HTTPHEADER => $headers, CURLOPT_SSL_VERIFYPEER => $verify, CURLOPT_SSL_VERIFYHOST => $verify ? 2 : 0]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_HTTP_CODE); $error = curl_error($ch); curl_close($ch); if ($body === false || $status >= 400) { throw new InstallError("Couldn't fetch $url: " . ($error ?: "HTTP $status")); } return (string) $body; } $context = stream_context_create(['http' => ['header' => implode("\r\n", $headers), 'timeout' => 60], 'ssl' => ['verify_peer' => $verify, 'verify_peer_name' => $verify]]); $body = @file_get_contents($url, false, $context); if ($body === false) { throw new InstallError("Couldn't fetch $url."); } return $body; } /** * Register this install with the license server, before anything is installed. Sends the address Client Harbor will * run at, this server's address and the address of whoever is running the installer. */ function activate_license(string $license, string $host, string $portal): void { [$status, $body] = http_post(LICENSE_URL, [ 'action' => 'activate', 'license' => $license, 'domain' => $host, 'portal' => $portal, 'server_ip' => (string) ($_SERVER['SERVER_ADDR'] ?? ''), 'installer_ip' => (string) ($_SERVER['REMOTE_ADDR'] ?? ''), 'version' => release_version(), // the license server refuses a version the license doesn't cover ]); $answer = json_decode($body, true); if (!is_array($answer) || !isset($answer['status'])) { throw new InstallError("The license server didn't answer (HTTP $status). Try again in a few minutes."); } if ($answer['status'] !== 'active') { throw new InstallError((string) ($answer['message'] ?? 'The license server refused this license.')); } } /** The version about to be installed (the newest release), or '' when the release information can't be read. */ function release_version(): string { [$status, $body] = http_request(RELEASE_URL, null, ['Accept: application/json']); $manifest = $status === 200 ? json_decode($body, true) : null; return is_array($manifest) ? (string) ($manifest['version'] ?? '') : ''; } /** POST a form; returns [HTTP status, body] whatever the status (0 when the server can't be reached). */ function http_post(string $url, array $fields): array { return http_request($url, $fields, ['Accept: application/json']); } /** GET (no fields) or POST a form; returns [HTTP status, body] whatever the status (0 when unreachable). */ function http_request(string $url, ?array $fields, array $headers = [], bool $verify = true): array { $data = $fields === null ? null : http_build_query($fields); if (function_exists('curl_init')) { $ch = curl_init($url); curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, CURLOPT_HTTPHEADER => $headers, CURLOPT_SSL_VERIFYPEER => $verify, CURLOPT_SSL_VERIFYHOST => $verify ? 2 : 0]); if ($data !== null) { curl_setopt_array($ch, [CURLOPT_POST => true, CURLOPT_POSTFIELDS => $data]); } $body = curl_exec($ch); $status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); return [$status, $body === false ? '' : (string) $body]; } if ($data !== null) { $headers[] = 'Content-Type: application/x-www-form-urlencoded'; } $context = stream_context_create(['http' => ['method' => $data === null ? 'GET' : 'POST', 'timeout' => 30, 'ignore_errors' => true, 'header' => implode("\r\n", $headers), 'content' => (string) $data], 'ssl' => ['verify_peer' => $verify, 'verify_peer_name' => $verify]]); $body = @file_get_contents($url, false, $context); $status = isset($http_response_header[0]) && preg_match('/\s(\d{3})\s?/', $http_response_header[0], $m) ? (int) $m[1] : 0; return [$status, $body === false ? '' : $body]; } function http_download(string $url, string $dest): void { if (function_exists('curl_init')) { $fp = fopen($dest, 'wb'); $ch = curl_init($url); curl_setopt_array($ch, [CURLOPT_FILE => $fp, CURLOPT_FOLLOWLOCATION => true, CURLOPT_TIMEOUT => 240]); $ok = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_HTTP_CODE); $error = curl_error($ch); curl_close($ch); fclose($fp); if (!$ok || $status >= 400) { throw new InstallError("Couldn't download $url: " . ($error ?: "HTTP $status")); } return; } [$code, $out] = run('curl -fsSL -o ' . escapeshellarg($dest) . ' ' . escapeshellarg($url)); if ($code !== 0 && !@copy($url, $dest)) { throw new InstallError("Couldn't download $url: $out"); } } function home_dir(): string { static $home = null; if ($home === null && hostsecure_account_dir() !== '') { $home = hostsecure_account_dir(); } if ($home === null) { $home = (string) getenv('HOME'); if (($home === '' || $home === '/') && function_exists('posix_getpwuid')) { $home = (string) (posix_getpwuid(posix_geteuid())['dir'] ?? ''); } if (($home === '' || $home === '/') && preg_match('#^(/home\d*/[^/]+)/#', __DIR__ . '/', $m)) { $home = $m[1]; } $home = rtrim($home, '/'); } return $home; } function account_user(): string { if (function_exists('posix_getpwuid')) { return (string) (posix_getpwuid(posix_geteuid())['name'] ?? get_current_user()); } return get_current_user(); } function home_relative(string $path): string { $home = home_dir() . '/'; return strpos($path, $home) === 0 ? substr($path, strlen($home)) : $path; } /** ~/clientharbor, or ~/clientharbor2... when another install is already there. */ function free_app_dir(): string { for ($i = 1; ; $i++) { $dir = home_dir() . '/clientharbor' . ($i > 1 ? $i : ''); if (!file_exists($dir) || (is_dir($dir) && count(scandir($dir) ?: []) <= 2)) { return $dir; } } } function state_dir(): string { $dir = home_dir() . '/.clientharbor-install'; if (!is_dir($dir)) { @mkdir($dir, 0700); } return $dir; } function load_state(): array { $file = state_dir() . '/state.json'; return is_file($file) ? (json_decode((string) file_get_contents($file), true) ?: []) : []; } function save_state(array $state): void { write_private(state_dir() . '/state.json', (string) json_encode($state, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)); } function write_private(string $path, string $content): void { $tmp = $path . '.tmp'; if (file_put_contents($tmp, $content) === false) { throw new InstallError("Can't write $path."); } chmod($tmp, 0600); rename($tmp, $path); } function installer_stamped(): bool { return strpos(LICENSE_URL, '{{') !== 0 && strpos(RELEASE_URL, '{{') !== 0; } function zip_version(string $path): string { return preg_match('/clientharbor-(.+)\.zip$/', $path, $m) ? $m[1] : ''; } function request_host(): string { return strtolower((string) preg_replace('/:\d+$/', '', (string) ($_SERVER['HTTP_HOST'] ?? $_SERVER['SERVER_NAME'] ?? ''))); } function is_https(): bool { return (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || (int) ($_SERVER['SERVER_PORT'] ?? 0) === 443 || strtolower((string) ($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '')) === 'https'; } function random_text(int $length): string { $chars = 'abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789'; $text = ''; for ($i = 0; $i < $length; $i++) { $text .= $chars[random_int(0, strlen($chars) - 1)]; } return $text; } function json_part(string $out): string { $start = strpos($out, '{'); return $start === false ? '' : substr($out, $start); } function tail(string $text, int $lines): string { return implode("\n", array_slice(preg_split('/\R/', rtrim($text)) ?: [], -$lines)); } function done(string $message): array { return ['status' => 'done', 'message' => $message]; } function json_out(array $data): void { header('Content-Type: application/json'); header('Cache-Control: no-store'); echo json_encode($data); exit; } function h($text): string { return htmlspecialchars((string) $text, ENT_QUOTES, 'UTF-8'); } // ── The page ─────────────────────────────────────────────────────────────────────────────────────────────── function render_page(): void { header('Cache-Control: no-store'); header('X-Frame-Options: DENY'); $state = load_state(); $GLOBALS['api_token'] = $state['api_token'] ?? ''; $checks = preflight(); $blocked = (bool) array_filter($checks, function ($c) { return $c['level'] === 'fail'; }); $needs_token = (bool) array_filter($checks, function ($c) { return $c['level'] === 'token'; }); $host = request_host(); try { $base = mode() === 'manual' ? registrable_domain($host) : (base_domain($host, account_domains()) ?: $host); } catch (InstallError $e) { $base = registrable_domain($host); } $manual_only = panel() === 'other'; ?> Install Client Harbor

Install Client Harbor

Checking this hosting account

Fix the items marked ✗, then reload this page.

Your Client Harbor

Client Harbor will run at https://.

Easier: in HostSecure, open Software → Websites and choose Client Harbor. It installs without an API token, without turning on Running commands and without this file (HostSecure 0.221 with patch 4 or later). Use this installer only if that isn't there yet.

From your Client Harbor order. Don't have one? Contact us.
'In DirectAdmin: Login Keys → Create Key. Allow it at least CMD_API_SHOW_DOMAINS, CMD_API_SUBDOMAINS, CMD_API_DATABASES and CMD_API_CRON_JOBS. You can delete it once the install is done.', 'hostsecure' => 'In HostSecure: Security → API Tokens → Create. Tick Databases, Cron jobs and Applications (and Domains, for a client area). You can delete it once the install is done.', ][panel()] ?? 'In cPanel: Security → Manage API Tokens → Create. You can delete it once the install is done.' ?>

Database

In your hosting panel, create a database and a user with all privileges on it, then enter them here. Choose PostgreSQL if your panel offers it, else MySQL or MariaDB.

The installer creates the database for you: PostgreSQL if offers it here, else MySQL or MariaDB.

About you

You'll sign in with it.