/** * Run Telegram plugin. * @return bool */ public function execute() { $build_icon = $this->build->isSuccessful() ? '✅' : '❎'; $buildMsg = $this->build->getLog(); $buildMsg = str_replace(array('[0;32m', '[0;31m', '[0m', '/[0m'), array('', '', ''), $buildMsg); $buildmessages = explode('RUNNING PLUGIN: ', $buildMsg); $buildMsg = ''; foreach ($buildmessages as $bm) { $pos = mb_strpos($bm, "\n"); $firstRow = mb_substr($bm, 0, $pos); //skip long outputs if ($firstRow == 'slack_notify' || $firstRow == 'php_loc' || $firstRow == 'telegram') { continue; } $buildMsg .= '*RUNNING PLUGIN: ' . $firstRow . "*\n"; $buildMsg .= $firstRow == 'composer' ? '' : '```' . mb_substr($bm, $pos) . '```'; } $message = $this->phpci->interpolate(str_replace(array('%ICON_BUILD%'), array($build_icon), $this->message)); $http = new HttpClient('https://api.telegram.org'); $http->setHeaders(array('Content-Type: application/json')); $uri = '/bot' . $this->api_key . '/sendMessage'; foreach ($this->recipients as $chat_id) { $params = array('chat_id' => $chat_id, 'text' => $message, 'parse_mode' => 'Markdown'); $http->post($uri, json_encode($params)); if ($this->send_log) { $params = array('chat_id' => $chat_id, 'text' => $buildMsg, 'parse_mode' => 'Markdown'); $http->post($uri, json_encode($params)); } } return true; }
/** * Copies files from the root of the build directory into the target folder */ public function execute() { if (empty($this->webhookUrl)) { $this->phpci->logFailure('You must specify a webhook URL.'); return false; } $http = new HttpClient(); $response = $http->post($this->webhookUrl, array('reason' => $this->phpci->interpolate($this->reason), 'source' => 'PHPCI', 'url' => $this->phpci->interpolate('%BUILD_URI%'), 'branch' => $this->phpci->interpolate('%BRANCH%'), 'update_only' => $this->updateOnly)); return $response['success']; }
/** * Make all GitHub requests following the Link HTTP headers. * * @param string $url * @param mixed $params * @param array $results * * @return array */ public function makeRecursiveRequest($url, $params, $results = array()) { $http = new HttpClient('https://api.github.com'); $res = $http->get($url, $params); foreach ($res['body'] as $item) { $results[] = $item; } foreach ($res['headers'] as $header) { if (preg_match('/^Link: <([^>]+)>; rel="next"/', $header, $r)) { $host = parse_url($r[1]); parse_str($host['query'], $params); $results = $this->makeRecursiveRequest($host['path'], $params, $results); break; } } return $results; }
/** * Pulls all pending builds from the database and runs them. */ protected function execute(InputInterface $input, OutputInterface $output) { $parser = new Parser(); $yaml = file_get_contents(APPLICATION_PATH . 'PHPCI/config.yml'); $this->settings = $parser->parse($yaml); $token = $this->settings['phpci']['github']['token']; if (!$token) { $this->logger->error(Lang::get('no_token')); return; } $buildStore = Factory::getStore('Build'); $this->logger->addInfo(Lang::get('finding_projects')); $projectStore = Factory::getStore('Project'); $result = $projectStore->getWhere(); $this->logger->addInfo(Lang::get('found_n_projects', count($result['items']))); foreach ($result['items'] as $project) { $http = new HttpClient('https://api.github.com'); $commits = $http->get('/repos/' . $project->getReference() . '/commits', array('access_token' => $token)); $last_commit = $commits['body'][0]['sha']; $last_committer = $commits['body'][0]['commit']['committer']['email']; $message = $commits['body'][0]['commit']['message']; $this->logger->info(Lang::get('last_commit_is', $project->getTitle(), $last_commit)); if ($project->getLastCommit() != $last_commit && $last_commit != "") { $this->logger->info(Lang::get('adding_new_build')); $build = new Build(); $build->setProjectId($project->getId()); $build->setCommitId($last_commit); $build->setStatus(Build::STATUS_NEW); $build->setBranch($project->getBranch()); $build->setCreated(new \DateTime()); $build->setCommitMessage($message); if (!empty($last_committer)) { $build->setCommitterEmail($last_committer); } $buildStore->save($build); $project->setLastCommit($last_commit); $projectStore->save($project); } } $this->logger->addInfo(Lang::get('finished_processing_builds')); }
/** * Pulls all pending builds from the database and runs them. */ protected function execute(InputInterface $input, OutputInterface $output) { $parser = new Parser(); $yaml = file_get_contents(APPLICATION_PATH . 'PHPCI/config.yml'); $this->settings = $parser->parse($yaml); $token = $this->settings['phpci']['github']['token']; if (!$token) { $this->logger->error("No github token found"); exit; } $buildStore = Factory::getStore('Build'); $this->logger->addInfo("Finding projects to poll"); $projectStore = Factory::getStore('Project'); $result = $projectStore->getWhere(); $this->logger->addInfo(sprintf("Found %d projects", count($result['items']))); foreach ($result['items'] as $project) { $http = new HttpClient('https://api.github.com'); $commits = $http->get('/repos/' . $project->getReference() . '/commits', array('access_token' => $token)); $last_commit = $commits['body'][0]['sha']; $last_committer = $commits['body'][0]['commit']['committer']['email']; $this->logger->info("Last commit to github for " . $project->getTitle() . " is " . $last_commit); if ($project->getLastCommit() != $last_commit && $last_commit != "") { $this->logger->info("Last commit is different from database, adding new build for " . $project->getTitle()); $build = new Build(); $build->setProjectId($project->getId()); $build->setCommitId($last_commit); $build->setStatus(Build::STATUS_NEW); $build->setBranch($project->getBranch()); $build->setCreated(new \DateTime()); if (!empty($last_committer)) { $build->setCommitterEmail($last_committer); } $buildStore->save($build); $project->setLastCommit($last_commit); $projectStore->save($project); } } $this->logger->addInfo("Finished processing builds"); }
/** * Handle the payload when Github sends a Pull Request webhook. * * @param Project $project * @param array $payload */ protected function githubPullRequest(Project $project, array $payload) { // We only want to know about open pull requests: if (!in_array($payload['action'], array('opened', 'synchronize', 'reopened'))) { return array('status' => 'ok'); } $headers = array(); $token = \b8\Config::getInstance()->get('phpci.github.token'); if (!empty($token)) { $headers[] = 'Authorization: token ' . $token; } $url = $payload['pull_request']['commits_url']; $http = new \b8\HttpClient(); $http->setHeaders($headers); $response = $http->get($url); // Check we got a success response: if (!$response['success']) { throw new Exception('Could not get commits, failed API request.'); } $results = array(); $status = 'failed'; foreach ($response['body'] as $commit) { // Skip all but the current HEAD commit ID: $id = $commit['sha']; if ($id != $payload['pull_request']['head']['sha']) { $results[$id] = array('status' => 'ignored', 'message' => 'not branch head'); continue; } try { $branch = str_replace('refs/heads/', '', $payload['pull_request']['base']['ref']); $committer = $commit['commit']['author']['email']; $message = $commit['commit']['message']; $remoteUrlKey = $payload['pull_request']['head']['repo']['private'] ? 'ssh_url' : 'clone_url'; $extra = array('build_type' => 'pull_request', 'pull_request_id' => $payload['pull_request']['id'], 'pull_request_number' => $payload['number'], 'remote_branch' => $payload['pull_request']['head']['ref'], 'remote_url' => $payload['pull_request']['head']['repo'][$remoteUrlKey]); $results[$id] = $this->createBuild($project, $id, $branch, $committer, $message, $extra); $status = 'ok'; } catch (Exception $ex) { $results[$id] = array('status' => 'failed', 'error' => $ex->getMessage()); } } return array('status' => $status, 'commits' => $results); }
protected function githubPullRequest($projectId, array $payload) { // We only want to know about open pull requests: if (!in_array($payload['action'], array('opened', 'synchronize', 'reopened'))) { die('OK'); } try { $headers = array(); $token = \b8\Config::getInstance()->get('phpci.github.token'); if (!empty($token)) { $headers[] = 'Authorization: token ' . $token; } $url = $payload['pull_request']['commits_url']; $http = new \b8\HttpClient(); $http->setHeaders($headers); $response = $http->get($url); // Check we got a success response: if (!$response['success']) { header('HTTP/1.1 500 Internal Server Error'); header('Ex: Could not get commits, failed API request.'); die('FAIL'); } foreach ($response['body'] as $commit) { $branch = str_replace('refs/heads/', '', $payload['pull_request']['base']['ref']); $committer = $commit['commit']['author']['email']; $message = $commit['commit']['message']; $extra = array('build_type' => 'pull_request', 'pull_request_id' => $payload['pull_request']['id'], 'pull_request_number' => $payload['number'], 'remote_branch' => $payload['pull_request']['head']['ref'], 'remote_url' => $payload['pull_request']['head']['repo']['clone_url']); $this->createBuild($projectId, $commit['sha'], $branch, $committer, $message, $extra); } } catch (\Exception $ex) { header('HTTP/1.1 500 Internal Server Error'); header('Ex: ' . $ex->getMessage()); die('FAIL'); } die('OK'); }
/** * Look up available versions of a given package on packagist.org */ public function packagistVersions() { $name = $this->getParam('p', ''); $http = new \b8\HttpClient(); $http->setHeaders(array('User-Agent: PHPCI/1.0 (+https://www.phptesting.org)')); $res = $http->get('https://packagist.org/packages/' . $name . '.json'); $response = new b8\Http\Response\JsonResponse(); $response->setContent($res['body']); return $response; }
/** * Call Github API for our Github user object. * @param $token * @return mixed */ protected function getGithubUser($token) { $http = new HttpClient('https://api.github.com'); $user = $http->get('/user', array('access_token' => $token)); return $user['body']; }
public function packagistVersions() { $name = $this->getParam('p', ''); $http = new \b8\HttpClient(); $http->setHeaders(array('User-Agent: PHPCI/1.0 (+https://www.phptesting.org)')); $res = $http->get('https://packagist.org/packages/' . $name . '.json'); die(json_encode($res['body'])); }
public function testDelete() { $http = new HttpClient('http://echo.jsontest.com'); $data = $http->delete('/key/value', array('test' => 'x')); $this->assertTrue(is_array($data)); }
/** * Create a comment on a Github commit. * @param $repo * @param $commitId * @param $file * @param $line * @param $comment * @return null */ public function createCommitComment($repo, $commitId, $file, $line, $comment) { $token = Config::getInstance()->get('phpci.github.token'); if (!$token) { return null; } $url = '/repos/' . strtolower($repo) . '/commits/' . $commitId . '/comments'; $params = array('body' => $comment, 'path' => $file, 'position' => $line); $http = new HttpClient('https://api.github.com'); $http->setHeaders(array('Content-Type: application/x-www-form-urlencoded', 'Authorization: Basic ' . base64_encode($token . ':x-oauth-basic'))); $http->post($url, json_encode($params)); }