'', 'baseDomain' => 'd.git.verstaem.com/', 'baseDomainFolder' => '', 'token' => 'qefwegwegerhrtherhw' ]; protected $data; function __construct() { if (!isset($_SERVER['HTTP_X_GITLAB_TOKEN']) || $_SERVER['HTTP_X_GITLAB_TOKEN'] != $this->config['token']) { echo 'Wrong token given'; return; } $this->config['root'] = realpath(__DIR__ . '/..') . '/'; $this->data = json_decode(file_get_contents('php://input'), true); if (empty($this->data)) { echo 'No data given'; return; } if (empty($this->data['ref'])) { echo 'No ref'; return; } $branch = str_replace('refs/heads/', '', $this->data['ref']); if ($branch == 'dev') { $domain = $this->config['baseDomain']; } else { $subDomains = explode('/', $branch); $subDomains = array_reverse($subDomains); $domain = implode('.', $subDomains) . '.' . $this->config['baseDomain']; } echo "Branch $branch\r\n"; $folder = $this->config['root'] . $domain; $this->config['baseDomainFolder'] = realpath($this->config['root'] . $this->config['baseDomain']) . '/'; switch ($branch) { case 'master': break; case 'dev': $command = 'cd ' . $folder . ' && git reset --hard && git pull 2>&1'; echo exec($command, $output, $return_var); break; default: if ($this->data['after'] == '0000000000000000000000000000000000000000') { $this->deleteSite($folder, $branch); } else { $this->updateSite($folder, $branch); } } } public function updateSite($folder, $branch) { if (!is_dir($folder)) { mkdir($folder); echo "Start site folder copy\r\n"; if (strpos($this->config['baseDomainFolder'], $this->config['root']) === 0) { $command = 'rsync -a ' . $this->config['baseDomainFolder'] . ' ' . $folder . ' --exclude=bitrix/ --exclude=upload/ 2>&1'; echo exec($command, $output, $return_var); echo "Folder copied\r\n"; symlink($this->config['baseDomainFolder'] . 'bitrix', $folder . 'bitrix'); symlink($this->config['baseDomainFolder'] . 'upload', $folder . 'upload'); echo "Symlinks created\r\n"; echo "Pulling changes from repository:\r\n"; $command = 'cd ' . $folder . ' && git fetch && git checkout ' . $branch . ' && git reset --hard && git pull 2>&1'; echo exec($command, $output, $return_var); } } else { $command = 'cd ' . $folder . ' && git reset --hard && git pull 2>&1'; echo exec($command, $output, $return_var); } } public function deleteSite($folder, $branch) { if (is_dir($folder)) { $command = 'cd ' . $this->config['baseDomainFolder']; $command .= ' && git branch -d ' . $branch . ' 2>&1'; echo exec($command, $output, $return_var); $command = 'rm -R ' . $folder . ' 2>&1'; echo exec($command, $output, $return_var); } else { echo "Site don't exist\r\n"; } } } $webHook = new WebHook();