예제 #1
0
 /**
  * undocumented function
  *
  * @return void
  * @author 
  **/
 public function takeCare()
 {
     $req = Request::instance();
     $token = $this->client->getAccessToken('authorizationCode', ['code' => $req->get('code')]);
     $github = new \Github\Client();
     $github->authenticate($token->accessToken, 'http_token');
     $response = $github->getHttpClient()->get('user');
     $user = \Github\HttpClient\Message\ResponseMediator::getContent($response);
     $verifiedEmails = $this->getVerifiedEmails($token->accessToken);
     $email = $this->getPrimaryEmail($verifiedEmails);
     $result['uid'] = $user['id'];
     $result['email'] = $email;
     $result['username'] = $user['login'];
     $result['url'] = $user['html_url'];
     $result['location'] = isset($user['location']) ? $user['location'] : null;
     $fresult = $this->findUser($result['email']);
     if ($fresult['found']) {
         $fuser = $fresult['user'];
         $result['first_name'] = $fuser->first_name;
         $result['last_name'] = $fuser->last_name;
     } else {
         if (isset($user['name'])) {
             $name = explode(' ', $user['name']);
             $result['first_name'] = $name[0];
             $result['last_name'] = isset($name[1]) ? $name[1] : $name[0];
         } else {
             $result['first_name'] = $result['last_name'] = $result['username'];
         }
     }
     $result['access_token'] = $token->accessToken;
     return $result;
 }
 public function progress($offset, $limit)
 {
     $source = $this->connection->fetchAll("\n            SELECT `id`, `name`\n            FROM `s_names`\n            WHERE `github_response_code` = 0\n            LIMIT {$offset}, {$limit};\n        ");
     $names = array_column($source, 'name', 'id');
     $responseCodeIdMap = [];
     /* @var $api \Github\Api\User */
     $client = new \Github\Client();
     $client->authenticate($this->authToken, \Github\Client::AUTH_HTTP_PASSWORD);
     $api = $client->api('user');
     foreach ($names as $id => $name) {
         try {
             $api->show($name);
             $code = 200;
         } catch (\Github\Exception\RuntimeException $e) {
             // "You have reached GitHub hour limit! Actual limit is: 5000"
             if (empty($code = $e->getCode())) {
                 break;
             }
         }
         $responseCodeIdMap[$code][] = $id;
     }
     foreach ($responseCodeIdMap as $code => $idList) {
         $idStringList = join(',', $idList);
         $this->connection->executeUpdate("\n                UPDATE `s_names`\n                SET `github_response_code` = {$code}\n                WHERE `id` IN ({$idStringList})\n            ");
     }
 }
예제 #3
0
 protected function fetchExtensionsFromRepository()
 {
     $token = $_SESSION['github.token'];
     if (!$token) {
         throw new \Exception('no github token setup');
     }
     $client = new \Github\Client(new \Github\HttpClient\CachedHttpClient(array('cache_dir' => $this->app->config('cache_dir') . 'githubapi-cache')));
     $this->client = $client;
     $client->authenticate($token, null, \GitHub\Client::AUTH_URL_TOKEN);
     $pager = new \Github\ResultPager($client);
     $api = $client->api('repo');
     $method = 'branches';
     $params = ['php', 'php-src'];
     $branches = $pager->fetchAll($api, $method, $params);
     $branchesToFetch = [];
     foreach ($branches as $branch) {
         $currentBranchName = $branch['name'];
         if (strlen($currentBranchName) == 7) {
             if (preg_match('$PHP-([0-9])\\.([0-9])$', $currentBranchName, $matches)) {
                 if ((int) $matches[1] < 5 || (int) $matches[2] < 4) {
                     continue;
                 }
                 $branchesToFetch[$matches[0]] = $branch;
             }
         }
     }
     $this->branches = $branchesToFetch;
     $extensions = $this->fetchExtensionPerBranch();
     return $extensions;
 }
 /**
  * @param array  $pull_request_data
  * @param string $reject_reason
  */
 private function rejectPullRequest(array $pull_request_data, $reject_reason)
 {
     $client = new \Github\Client();
     $params = array();
     $params['state'] = 'closed';
     $base = $pull_request_data['base'];
     $head = $pull_request_data['head'];
     $user = $head['user'];
     $repo = $base['repo'];
     $owner = $repo['owner'];
     $id = $pull_request_data['number'];
     if (!defined('GITHUB_API_OAUTH2TOKEN')) {
         throw new InvalidArgumentException();
     }
     $client->authenticate(GITHUB_API_OAUTH2TOKEN, null, \Github\Client::AUTH_HTTP_TOKEN);
     $client->api('pull_request')->update($owner['login'], $repo['name'], $id, $params);
     $params = array();
     $comment_body = '';
     switch ($reject_reason) {
         case self::NON_MEMBER_REJECT_REASON:
         case self::NON_FOUNDATION_MEMBER_REJECT_REASON:
             $comment_body = sprintf('User %s is not an OpenStack Foundation Member. Please go to https://www.openstack.org/join/register/ and complete the registration form in order to become a Foundation Member. After that, please take a look at How to Contribute to Openstack (https://wiki.openstack.org/wiki/How_To_Contribute) and make sure you sign the Contributer License Agreement (http://docs.openstack.org/infra/manual/developers.html#account-setup).', $user['login']);
             break;
         case self::NON_SIGNED_CLA_REJECT_REASON:
             $comment_body = sprintf('User %s has not signed the Contributer License Agreement. Please take a look at How to Contribute to Openstack (https://wiki.openstack.org/wiki/How_To_Contribute) and make sure you sign the CLA (http://docs.openstack.org/infra/manual/developers.html#account-setup).', $user['login']);
             break;
     }
     $params['body'] = $comment_body;
     $client->api('issue')->comments()->create($owner['login'], $repo['name'], $id, $params);
 }
예제 #5
0
function getGithubClient()
{
    $token = getenv('GITHUB_TOKEN');
    $client = new \Github\Client();
    $client->authenticate($token, $token, Github\Client::AUTH_HTTP_TOKEN);
    return $client;
}
 public function __construct(\Github\Client $client)
 {
     $client = new \Github\Client();
     $auth = new Oauth();
     $user = $auth::where('user_id', Auth::id())->first();
     $client->authenticate($user->access_token, null, \Github\Client::AUTH_HTTP_TOKEN);
     $this->client = $client;
 }
예제 #7
0
function umc_github_client_connect($owner, $repo)
{
    require_once '/home/includes/composer/vendor/autoload.php';
    $cache_dir = "/tmp/github-{$repo}-{$owner}-cache";
    $token_file = __DIR__ . "/github-{$repo}-{$owner}.token";
    $client = new \Github\Client(new \Github\HttpClient\CachedHttpClient(array('cache_dir' => $cache_dir)));
    $token = file_get_contents($token_file);
    $client->authenticate($token, \Github\Client::AUTH_HTTP_TOKEN);
    return $client;
}
예제 #8
0
 /**
  * Obtain the user information from GitHub.
  *
  * @return Response
  */
 public function callback(Request $request)
 {
     $user = Socialite::with('github')->user();
     // TODO: Nice error page
     $request->session()->set('github', ['token' => $user->token, 'id' => $user->getId(), 'nickname' => $user->getNickname(), 'name' => $user->getName(), 'email' => $user->getEmail(), 'avatar' => $user->getAvatar()]);
     $client = new \Github\Client();
     $client->authenticate($user->token, false, \Github\Client::AUTH_HTTP_TOKEN);
     //$repos = $client->api('user')->repositories($user->getNickname()); // Get this users repos
     $content = $client->api('repo')->contents()->show('ashleyhindle', 'fodor-example', 'fodor.json', 'master');
     dd(base64_decode($content['content']));
 }
예제 #9
0
 public static function check($token, $user, $repo, $branch)
 {
     //TODO probar más cosas
     try {
         $client = new \Github\Client();
         $client->authenticate($token, false, Github\Client::AUTH_URL_TOKEN);
     } catch (Exception $e) {
         return false;
     }
     return true;
 }
예제 #10
0
 public function sendScreenshot($cloudName, $apiKey, $apiSecret, $authToken)
 {
     $this->say('Sending image');
     // Upload image
     Cloudinary::config(array('cloud_name' => $cloudName, 'api_key' => $apiKey, 'api_secret' => $apiSecret));
     $result = \Cloudinary\Uploader::upload(realpath(dirname(__FILE__) . '/tests/_output/InstallNenoCest.installNeno.fail.png'));
     $this->say('Image sent');
     $this->say('Creating Github issue');
     $client = new \Github\Client();
     $client->authenticate($authToken, \Github\Client::AUTH_HTTP_TOKEN);
     $client->api('issue')->create('Jensen-Technologies', 'neno', array('title' => 'Test error', 'body' => '![Screenshot](' . $result['secure_url'] . ')'));
 }
예제 #11
0
파일: index.php 프로젝트: teenscode/invite
 public function githubinvite()
 {
     global $admin_token;
     $admin = new \Github\Client();
     $admin->authenticate($admin_token, null, \Github\Client::AUTH_HTTP_TOKEN);
     // Check if already in the org
     $rawmembers = $admin->organization()->members()->all("teenscode");
     for ($i = 0; $i < count($rawmembers); $i++) {
         if ($rawmembers[$i]["login"] == $this->username) {
             echo "Already a member of org";
             return;
         }
     }
     // Not in org so add to org
     $admin->organization()->members()->add("teenscode", $this->username);
 }
예제 #12
0
 /**
  * @return \Github\Client
  */
 public function client()
 {
     // create client
     $client = new \Github\HttpClient\CachedHttpClient();
     $client->setCache(new \Github\HttpClient\Cache\FilesystemCache(__DIR__ . '/../tmp/github-cache'));
     $client = new \Github\Client($client);
     if (empty(Yii::$app->params['github_token'])) {
         throw new Exception('Config param "github_token" is not configured!');
     }
     if (empty(Yii::$app->params['github_username'])) {
         throw new Exception('Config param "github_username" is not configured!');
     }
     // authenticate
     $client->authenticate(Yii::$app->params['github_token'], '', \Github\Client::AUTH_HTTP_TOKEN);
     return $client;
 }
예제 #13
0
 /**
  * Closes any open pull requests on mirrored repositories.
  *
  * Since these are mirrored repos, any pull requests submitted are not
  * monitored or handled. Since GitHub does not support turning off pull
  * requests, it is inevitable that users will submit them anyway.
  *
  * Note: GitHub supports turning off issues, but not pull requests.
  *
  * This utility will simply auto-close any opened pull requests while
  * directing author to a (hopefully) more appropriate location to submit
  * changes to.
  *
  * @return int Shell return code.
  */
 function main()
 {
     $this->out(__('Fetching list of open issues...'));
     try {
         $client = new Github\Client();
         $client->getHttpClient()->setOption('user_agent', Configure::read('GitHub.user_agent'));
         $client->authenticate(GITHUB_USERNAME, GITHUB_PASSWORD, Github\Client::AUTH_HTTP_PASSWORD);
     } catch (Exception $exception) {
         $this->out(__('<error>Failed to authenticate with GitHub: %s</error>', $exception->getMessage()));
         $this->_unlock();
         return 1;
     }
     try {
         $response = $client->getHttpClient()->get('search/issues', array('q' => sprintf('user:%s state:open', Configure::read('GitHub.org_name'))));
         $issues = $response->getContent();
     } catch (Exception $exception) {
         $this->out(__('<error>Failed to fetch list of open issues: %s</error>', $exception->getMessage()));
         $this->_unlock();
         return 1;
     }
     if ($issues['total_count'] == 0) {
         $this->out(__('<info>No open pull requests were found.</info>'));
         $this->_unlock();
         return 0;
     }
     foreach ($issues['items'] as $pull_request) {
         $parts = explode('/', $pull_request['html_url']);
         $user = $parts[3];
         $plugin = $parts[4];
         $issue_number = $parts[6];
         $plugin_page = sprintf(Configure::read('App.plugin_http_url'), $plugin);
         $support_page = sprintf(Configure::read('App.plugin_support_url'), $plugin);
         $pull_request_url = sprintf('repos/%s/%s/pulls/%d', $user, $plugin, $issue_number);
         try {
             $client->getHttpClient()->post($pull_request['comments_url'], array('body' => sprintf($this->close_reply, $plugin_page, $support_page)));
             $client->getHttpClient()->patch($pull_request_url, array('state' => 'closed'));
         } catch (Exception $exception) {
             $this->out(__('<error>Failed to close pull request <%s>: %s</error>', $pull_request['html_url'], $exception->getMessage()));
             continue;
         }
         $this->out(__('Closed pull request: %s', $pull_request['html_url']));
     }
     $this->out(__('<info>Finished closing open issues on GitHub.</info>'));
     $this->_unlock();
     return 0;
 }
예제 #14
0
}
if (!$githubToken) {
    echo "Github token is not set\n";
    exit(1);
}
$dependenciesNames = getDependenciesNames($composerJsonPath);
$packagistClient = new Packagist\Api\Client();
$githubRepositories = array();
foreach ($dependenciesNames as $packageName) {
    try {
        $githubRepository = getGithubRepository($packagistClient, $packageName);
    } catch (\Guzzle\Http\Exception\ClientErrorResponseException $e) {
        if (strpos($e->getMessage(), '[reason phrase] Not Found') === false) {
            throw $e;
        }
    }
    if (!$githubRepository) {
        echo "Github repository for package {$packageName} is not found\n";
        continue;
    }
    $githubRepositories[] = $githubRepository;
}
if (empty($githubRepositories)) {
    exit;
}
$client = new \Github\Client();
$client->authenticate($githubToken, '', Github\Client::AUTH_URL_TOKEN);
foreach ($githubRepositories as $githubRepository) {
    $client->api('current_user')->starring()->star($githubRepository['author'], $githubRepository['name']);
    echo $githubRepository['url'] . "\n";
}
예제 #15
0
<?php

// Initialize SimpleCache
$cache = new Gilbitron\Util\SimpleCache();
$cache->cache_path = HW_CACHE_DIR . '/';
// Initialize GitHub-API
$client = new \Github\Client(new \Github\HttpClient\CachedHttpClient(array('cache_dir' => HW_CACHE_DIR)));
if (HW_GITHUB_API != '') {
    $client->authenticate(HW_GITHUB_API, null, Github\Client::AUTH_HTTP_TOKEN);
}
$paginator = new Github\ResultPager($client);
예제 #16
0
        foreach ($client->api('repo')->hooks()->all($session->getUsername(), $args['repository']) as $hook) {
            if ($hook['name'] == 'web' && strpos($hook['config']['url'], 'redports.org') !== false) {
                $client->api('repo')->hooks()->remove($session->getUsername(), $args['repository'], $hook['id']);
            }
        }
        $webhook = $client->api('repo')->hooks()->create($session->getUsername(), $args['repository'], array('name' => 'web', 'active' => true, 'events' => array('push'), 'config' => array('url' => 'https://api.redports.org/github/', 'content_type' => 'json')));
    } catch (\Github\Exception\RuntimeException $e) {
        return $response->withStatus(500)->write($e->getMessage());
    }
    /* TODO: register repository at master */
    return $response->withRedirect('/repositories');
});
/* GitHub repository uninstall */
$app->get('/repositories/{repository}/uninstall', function ($request, $response, $args) use($session) {
    if (!$session->getUsername()) {
        return $response->withStatus(403)->write('Not authenticated');
    }
    $client = new \Github\Client();
    $client->authenticate($_SESSION['token'], null, \Github\Client::AUTH_HTTP_TOKEN);
    try {
        foreach ($client->api('repo')->hooks()->all($session->getUsername(), $args['repository']) as $hook) {
            if ($hook['name'] == 'web' && strpos($hook['config']['url'], 'redports.org') !== false) {
                $client->api('repo')->hooks()->remove($session->getUsername(), $args['repository'], $hook['id']);
            }
        }
    } catch (\Github\Exception\RuntimeException $e) {
        return $response->withStatus(500)->write($e->getMessage());
    }
    return $response->withRedirect('/repositories');
});
$app->run();
if (isset($_GET['code'])) {
    $data = 'client_id=' . 'd12c2803a9453ba44900' . '&' . 'client_secret=' . '76a1c2f9c3d9229af028ee6b890e1c21de8cb926' . '&' . 'code=' . urlencode($_GET['code']);
    $ch = curl_init('https://github.com/login/oauth/access_token');
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    preg_match('/access_token=([0-9a-f]+)/', $response, $out);
    curl_close($ch);
    if ($out[1]) {
        $fgmembersite->insertToken($out[1]);
    }
}
$token = $fgmembersite->getusertoken();
if ($token != NULL) {
    $client = new Github\Client();
    $client->authenticate($token, $password = NULL, Github\Client::AUTH_HTTP_TOKEN);
    $general_info = $client->api('current_user')->show();
    $fggitclass->cleanRepos();
    $fggitclass->cloneRepos();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8"/>
	<title>EasyDoc</title>

	<link rel="stylesheet" href="css/layout.css" type="text/css" media="screen" />
	<!--[if lt IE 9]>
	<link rel="stylesheet" href="css/ie.css" type="text/css" media="screen" />
	<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
예제 #18
0
/**
 * Upload a local file to a GitHub repository
 * @param string $ps_user GitHub username
 * @param string $ps_token access token. Global account password can be used here but it's recommended to create a personal access token instead.
 * @param string $ps_owner The repository owner
 * @param string $ps_repo repository name
 * @param string $ps_git_path path for the file destination inside the repository, e.g. "/exports/from_collectiveaccess/export.xml."
 * @param string $ps_local_filepath file to upload as absolute local path. Note that the file must be loaded in memory to be committed to GitHub.
 * @param string $ps_branch branch to commit to. defaults to 'master'
 * @param bool $pb_update_on_conflict Determines what happens if file already exists in GitHub repository.
 * 		true means the file is updated in place for. false means we abort. default is true
 * @param string $ps_commit_msg commit message
 * @return bool success state
 */
function caUploadFileToGitHub($ps_user, $ps_token, $ps_owner, $ps_repo, $ps_git_path, $ps_local_filepath, $ps_branch = 'master', $pb_update_on_conflict = true, $ps_commit_msg = null)
{
    // check mandatory params
    if (!$ps_user || !$ps_token || !$ps_owner || !$ps_repo || !$ps_git_path || !$ps_local_filepath) {
        caLogEvent('DEBG', "Invalid parameters for GitHub file upload. Check your configuration!", 'caUploadFileToGitHub');
        return false;
    }
    if (!$ps_commit_msg) {
        $ps_commit_msg = 'Commit created by CollectiveAccess on ' . date('c');
    }
    $o_client = new \Github\Client();
    $o_client->authenticate($ps_user, $ps_token);
    $vs_content = @file_get_contents($ps_local_filepath);
    try {
        $o_client->repositories()->contents()->create($ps_owner, $ps_repo, $ps_git_path, $vs_content, $ps_commit_msg, $ps_branch);
    } catch (Github\Exception\RuntimeException $e) {
        switch ($e->getCode()) {
            case 401:
                caLogEvent('DEBG', "Could not authenticate with GitHub. Error message was: " . $e->getMessage() . " - Code was: " . $e->getCode(), 'caUploadFileToGitHub');
                break;
            case 422:
                if ($pb_update_on_conflict) {
                    try {
                        $va_content = $o_client->repositories()->contents()->show($ps_owner, $ps_repo, $ps_git_path);
                        if (isset($va_content['sha'])) {
                            $o_client->repositories()->contents()->update($ps_owner, $ps_repo, $ps_git_path, $vs_content, $ps_commit_msg, $va_content['sha'], $ps_branch);
                        }
                        return true;
                        // overwrite was successful if there was no exception in above statement
                    } catch (Github\Exception\RuntimeException $ex) {
                        caLogEvent('DEBG', "Could not update exiting file in GitHub. Error message was: " . $ex->getMessage() . " - Code was: " . $ex->getCode(), 'caUploadFileToGitHub');
                        break;
                    }
                } else {
                    caLogEvent('DEBG', "Could not upload file to GitHub. It looks like a file already exists at {$ps_git_path}.", 'caUploadFileToGitHub');
                }
                break;
            default:
                caLogEvent('DEBG', "Could not upload file to GitHub. A generic error occurred. Error message was: " . $e->getMessage() . " - Code was: " . $e->getCode(), 'caUploadFileToGitHub');
                break;
        }
        return false;
    } catch (Github\Exception\ValidationFailedException $e) {
        caLogEvent('DEBG', "Could not upload file to GitHub. The parameter validation failed. Error message was: " . $e->getMessage() . " - Code was: " . $e->getCode(), 'caUploadFileToGitHub');
        return false;
    } catch (Exception $e) {
        caLogEvent('DEBG', "Could not upload file to GitHub. A generic error occurred. Error message was: " . $e->getMessage() . " - Code was: " . $e->getCode(), 'caUploadFileToGitHub');
        return false;
    }
    return true;
}
예제 #19
0
}
function milestoneSort($a, $b)
{
    return strnatcasecmp($a['title'], $b['title']);
}
function labelSort($a, $b)
{
    return strnatcasecmp($a['name'], $b['name']);
}
function skipBecauseOfVersionConstraint($versionAdded, $milestoneOrLabelName)
{
    $version = explode('-', $milestoneOrLabelName)[0];
    return version_compare($versionAdded, $version) === 1;
}
$authentication = json_decode(file_get_contents('credentials.json'));
$client->authenticate($authentication->apikey, Github\Client::AUTH_URL_TOKEN);
$paginator = new Github\ResultPager($client);
$config = json_decode(file_get_contents('config.json'));
$repositories = [];
$updateDueDate = [];
$SHOW_MILESTONE = true;
$SHOW_LABEL = true;
foreach ($config->repos as $repo) {
    $repositories[$repo] = ['milestones' => [], 'labels' => []];
    print 'Repo ' . $config->org . '/' . $repo . PHP_EOL;
    if ($SHOW_MILESTONE) {
        print "  Milestones" . PHP_EOL;
    }
    $milestones = $client->api('issue')->milestones()->all($config->org, $repo);
    uasort($milestones, 'milestoneSort');
    foreach ($milestones as $milestone) {
예제 #20
0
 /**
  * @param string $url
  * @param string $token
  * @param bool   $cacheDir
  * @param null   $bufferIO
  *
  * @throws \Exception
  */
 public function __construct($url, $token = '', $cacheDir = false, $bufferIO = null)
 {
     $this->url = $url;
     $this->io = new NullIO();
     $this->log = $bufferIO ? $bufferIO : new BufferIO();
     $config = Factory::createConfig();
     $cfg = ['config' => []];
     if ($cacheDir) {
         $cfg['config']['cache-dir'] = $cacheDir;
     }
     if ($token) {
         $cfg['config']['github-oauth'] = ['github.com' => $token];
     }
     $config->merge($cfg);
     $this->cacheDir = $cacheDir;
     $this->io->loadConfiguration($config);
     $this->repository = new Repository\VcsRepository(['url' => $url, 'no-api' => false], $this->io, $config);
     $driver = $this->vcsDriver = $this->repository->getDriver();
     if (!$driver) {
         throw new \Exception('No driver found for <' . $url . '>');
     }
     $this->driver = $driver;
     $composerInfoMaster = $this->driver->getComposerInformation($this->driver->getRootIdentifier());
     if (!$composerInfoMaster) {
         throw new \Exception('master must have a valid composer.json');
     }
     $this->name = $composerInfoMaster['name'];
     list($this->vendorName, $this->packageName) = explode('/', $this->name);
     preg_match('#^(?:(?:https?|git)://([^/]+)/|git@([^:]+):)([^/]+)/(.+?)(?:\\.git|/)?$#', $this->url, $match);
     $this->gitHubVendorName = $match[3];
     $this->gitHubRepositoryName = $match[4];
     $client = new \Github\Client();
     $client->authenticate($token, null, \GitHub\Client::AUTH_URL_TOKEN);
     $this->client = $client;
 }
 /**
  * Generates contributor data and avatars
  * @return success or fail
  */
 public function actionGenerate()
 {
     if (!$this->acquireMutex()) {
         $this->stderr("Execution terminated: command is already running.\n", Console::FG_RED);
         return self::EXIT_CODE_ERROR;
     }
     $members = Yii::$app->params['members'];
     $contributors = array();
     $raw_contributors = array();
     $contributorLimit = 1000;
     // getting contributors from github
     try {
         $client = new \Github\Client();
         $token_file = Yii::getAlias('@app/data') . '/github.token';
         if (file_exists($token_file)) {
             $this->stdout("Authenticating with Github token.\n");
             $token = file_get_contents($token_file);
             $client->authenticate($token, null, \Github\Client::AUTH_URL_TOKEN);
         }
         $api = $client->api('repo');
         $paginator = new \Github\ResultPager($client);
         $parameters = ['yiisoft', 'yii2'];
         $raw_contributors = $paginator->fetch($api, 'contributors', $parameters);
         while ($paginator->hasNext() && count($raw_contributors) < $contributorLimit) {
             $raw_contributors = array_merge($raw_contributors, $paginator->fetchNext());
         }
         // remove team members
         $teamGithubs = array_filter(array_map(function ($member) {
             return isset($member['github']) ? $member['github'] : false;
         }, $members));
         foreach ($raw_contributors as $key => $raw_contributor) {
             if (in_array($raw_contributor['login'], $teamGithubs)) {
                 unset($raw_contributors[$key]);
             }
         }
         $raw_contributors = array_slice($raw_contributors, 0, $contributorLimit);
     } catch (\Exception $e) {
         $raw_contributors = false;
     }
     if ($raw_contributors) {
         foreach ($raw_contributors as $raw_contributor) {
             $contributor = array();
             $contributor['login'] = $raw_contributor['login'];
             $contributor['avatar_url'] = $raw_contributor['avatar_url'];
             $contributor['html_url'] = $raw_contributor['html_url'];
             $contributor['contributions'] = $raw_contributor['contributions'];
             $contributors[] = $contributor;
         }
     }
     // save 'contributors.json' in the data directory
     $data_dir = Yii::getAlias('@app/data');
     file_put_contents($data_dir . DIRECTORY_SEPARATOR . 'contributors.json', json_encode($contributors, JSON_PRETTY_PRINT));
     // Generate avatar thumbnails and store them in data/avatars
     $thumbnail_dir = $data_dir . DIRECTORY_SEPARATOR . 'avatars';
     if (!is_dir($thumbnail_dir)) {
         FileHelper::createDirectory($thumbnail_dir);
     }
     $imagine = new Imagine();
     $mode = ImageInterface::THUMBNAIL_OUTBOUND;
     $size = new \Imagine\Image\Box(48, 48);
     foreach ($contributors as $contributor) {
         $login = $contributor['login'];
         // Check if the file exists and there are no errors
         $headers = get_headers($contributor['avatar_url'], 1);
         $code = isset($headers[1]) ? explode(' ', $headers[1]) : explode(' ', $headers[0]);
         $code = next($code);
         if ($code != 404 and $code != 403 and $code != 400 and $code != 500) {
             // the image url seems to be good, save the thumbnail
             $this->stdout("Saving {$login}.png\n");
             $imagine->open($contributor['avatar_url'])->thumbnail($size, $mode)->save($thumbnail_dir . DIRECTORY_SEPARATOR . $login . '.png');
         } else {
             //TODO: default avatar thumbnail?
             $this->stdout("Avatar {$login}.png was not found\n");
         }
     }
     if (YII_ENV_DEV) {
         exec('gulp sprites && gulp styles', $output, $ret);
     } else {
         exec('gulp sprites && gulp styles --production', $output, $ret);
     }
     $this->releaseMutex();
     return self::EXIT_CODE_NORMAL;
 }
예제 #22
0
파일: app.php 프로젝트: gikundi/edge
 |--------------------------------------------------------------------------
 |
 | Next, we need to bind some important interfaces into the container so
 | we will be able to resolve them when needed. The kernels serve the
 | incoming requests to this application from both the web and CLI.
 |
*/
$app->singleton(Illuminate\Contracts\Http\Kernel::class, App\Http\Kernel::class);
$app->singleton(Illuminate\Contracts\Console\Kernel::class, App\Console\Kernel::class);
$app->singleton(Illuminate\Contracts\Debug\ExceptionHandler::class, App\Exceptions\Handler::class);
$app->singleton('Github\\Client', function () {
    $client = new Github\Client();
    $token = env('GITHUB_TOKEN');
    if (!isset($token)) {
        dd("Github token is not set.");
    }
    Session::get('token');
    $client->authenticate(env('GITHUB_TOKEN'), Github\Client::AUTH_URL_TOKEN);
    return $client;
});
/*
 |--------------------------------------------------------------------------
 | Return The Application
 |--------------------------------------------------------------------------
 |
 | This script returns the application instance. The instance is given to
 | the calling script so we can separate the building of the instances
 | from the actual running of the application and sending responses.
 |
*/
return $app;
예제 #23
0
파일: Sync.php 프로젝트: webflo/inboxSync
 protected function getClient()
 {
     $gh = new \Github\Client();
     $gh->authenticate($this->config->get('github.token'), \Github\Client::AUTH_HTTP_TOKEN);
     return $gh;
 }
예제 #24
0
$github_verify_payload = function (Request $request, \Silex\Application $app) {
    $secretKey = $app['db']->fetchColumn("SELECT value FROM config WHERE key = 'github_webhook_hash' ");
    $payload_signature = 'sha1=' . hash_hmac('sha1', $request->getContent(), $secretKey, false);
    $app['monolog']->debug('github signature: ' . $payload_signature);
    if ($payload_signature !== $request->headers->get('X-Hub-Signature')) {
        return new \Symfony\Component\HttpFoundation\Response('invalid', 403);
    }
    return null;
};
/**
 * creating our services
 */
$app['github.client'] = $app->share(function () use($app) {
    $client = new \Github\Client(new CachedHttpClient(['cache_dir' => __DIR__ . '/../cache']));
    if (isset($app['config']['github_token'])) {
        $client->authenticate($app['config']['github_token'], null, \Github\Client::AUTH_HTTP_TOKEN);
    }
    return $client;
});
$app['zendesk.client'] = $app->share(function () use($app) {
    $client = new \Zendesk\API\Client($app['config']['zendesk_subdomain'], $app['config']['zendesk_username']);
    $client->setAuth('token', $app['config']['zendesk_token']);
    return $client;
});
$app['ticket.processor'] = $app->share(function () use($app) {
    $processor = new TicketProcessor($app['zendesk.client'], $app['github.client'], $app['db'], $app['monolog'], $app['config'], $app['translator']);
    return $processor;
});
$app['flashbag'] = $app->share(function () use($app) {
    return $app['session']->getFlashBag();
});
|
| The first thing we will do is create a new Laravel application instance
| which serves as the "glue" for all the components of Laravel, and is
| the IoC container for the system binding all of the various parts.
|
*/
$app = new Illuminate\Foundation\Application(realpath(__DIR__ . '/../'));
/*
|--------------------------------------------------------------------------
| Bind Important Interfaces
|--------------------------------------------------------------------------
|
| Next, we need to bind some important interfaces into the container so
| we will be able to resolve them when needed. The kernels serve the
| incoming requests to this application from both the web and CLI.
|
*/
$app->singleton(Illuminate\Contracts\Http\Kernel::class, App\Http\Kernel::class);
$app->singleton(Illuminate\Contracts\Console\Kernel::class, App\Console\Kernel::class);
$app->singleton(Illuminate\Contracts\Debug\ExceptionHandler::class, App\Exceptions\Handler::class);
$app->singleton('Github\\Client', function () {
    $client = new Github\Client();
    $token = env('GITHUB_TOKEN');
    if (!isset($token)) {
        dd("Github token is not set.");
    }
    $client->authenticate(env('GITHUB_EMAIL'), env('GITHUB_PASSWORD'), Github\Client::AUTH_HTTP_PASSWORD);
    //$client->authenticate($token, null, Github\Client::AUTH_HTTP_TOKEN);
    return $client;
});
return $app;
예제 #26
0
<?php

/**
 * Repositories to add / alter the irc hook for
 */
$hookTargets = array('wmde' => array('DataValuesJavascript', 'ValueView', 'WikibaseDataModel', 'WikibaseDataModelSerialization', 'DataTypes', 'Ask', 'WikibaseInternalSerialization', 'Serialization', 'AskSerialization', 'WikidataBuilder', 'wikidata-analysis', 'WikibaseDatabase'), 'DataValues' => array('Geo', 'Number', 'Common', 'Interfaces', 'DataValues', 'Serialization', 'Validators', 'Time', 'Iri'));
/**
 * Params for the irc hook
 */
$hook = array('name' => 'irc', 'active' => true, 'config' => array('server' => 'chat.freenode.org', 'port' => '7000', 'room' => '#wikidata', 'nick' => 'github-wmde', 'ssl' => '1'), 'events' => array('push', 'pull_request', 'commit_comment', 'pull_request_review_comment'));
require_once __DIR__ . '/../vendor/autoload.php';
echo "Please generate a personal access token at https://github.com/settings/applications\n";
echo "Github Token:";
$token = stream_get_line(STDIN, 1024, "\n");
$client = new \Github\Client();
$client->authenticate($token, null, \Github\Client::AUTH_HTTP_TOKEN);
$controller = new \GithubHookController\IrcHookController($client);
foreach ($hookTargets as $user => $repos) {
    foreach ($repos as $repo) {
        $controller->setIrcHook($hook, $user, $repo);
    }
}
예제 #27
0
    echo 'Tipo: ', $issue->getIssueType()->getName(), "\n";
    echo 'Status:', $issue->getStatus()->getName(), "\n";
    echo 'Responsável: ', $issue->getAssignee()->getDisplayName(), "\n";
    echo 'Prioridade:', $issue->getPriority()->getName(), "\n";
    echo 'Criado em :', $issue->getCreated()->format('d/m/Y H:i:s'), "\n";
    echo 'Última atualização em :', $issue->getUpdated()->format('d/m/Y H:i:s'), "\n";
    if (getWeekdayDifference($issue->getUpdated(), $now) >= 2) {
        echo "URGENTE: esta tarefa precisa ser quebrada e entregue hoje. Nenhuma tarefa pode ficar mais de 2 dias parada", "\n";
    }
    echo "\n\n";
}
$client = new \Github\Client(new \Github\HttpClient\CachedHttpClient(array('cache_dir' => '/tmp/github-api-cache')));
$githubUser = getenv('GITHUB_USER');
$githubPassword = getenv('GITHUB_PASSWORD');
$githubRepo = getenv('GITHUB_REPO');
$client->authenticate($githubUser, $githubPassword, \Github\Client::AUTH_HTTP_PASSWORD);
$activity = $client->api('repo')->statistics($githubUser, $githubRepo);
echo "Commits \n\n";
foreach ($activity as $a) {
    $lastWeek = count($a['weeks']) - 1;
    if ($a['weeks'][$lastWeek]['c'] > 0) {
        echo $a['author']['login'], " Total de commits: ", $a['total'], '. Commits na última semana (começando em ' . DateTime::createFromFormat('U', $a['weeks'][$lastWeek]['w'])->format('d/m/Y') . ' ):' . $a['weeks'][$lastWeek]['c'], "\n";
    }
}
echo "\n\nOBS: se o nome de alguém não aparece acima não significa que ela não está trabalhando e sim que está commitando em branches diferentes da master pois o Github só entrega estatísticas desta branch. A ausência de alguém na lista acima indica que a sua tarefa está demorando mais de dois dias para terminar e ser aprovada no master o que reforça a necessidade de quebrar a tarefa em pedaços menores.\n";
function getWeekdayDifference(\DateTime $startDate, \DateTime $endDate)
{
    $days = 0;
    while ($startDate->diff($endDate)->days > 0) {
        $days += $startDate->format('N') < 6 ? 1 : 0;
        $startDate = $startDate->add(new \DateInterval("P1D"));
예제 #28
0
파일: merge.php 프로젝트: FreePBX/devtools
     $branchXML = simplexml_load_string($moduleBranchXmlString);
 } catch (\Exception $e) {
     die($e->getMessage());
 }
 $rawname = (string) $branchXML->rawname;
 $name = (string) $branchXML->name;
 $description = (string) $branchXML->description;
 if (empty($vars['githubtoken'])) {
     freepbx::out("If you add 'githubtoken' to your .freepbxconfig file you wont have to enter these credentials");
     $username = freepbx::getInput("GitHub Username");
     $password = freepbx::getPassword("GitHub Password", true);
     $client = new \Github\Client();
     $client->authenticate($username, $password, Github\Client::AUTH_HTTP_PASSWORD);
 } else {
     $client = new \Github\Client();
     $client->authenticate($vars['githubtoken'], "", Github\Client::AUTH_HTTP_TOKEN);
 }
 $merge = true;
 if (!freepbx::version_compare_freepbx((string) $masterXML->supported->version, (string) $branchXML->supported->version, "<=")) {
     echo "Master is on a higher or equal supported version than " . $options['updatemaster'] . "\n";
     $merge = false;
 }
 if (freepbx::version_compare_freepbx((string) $masterXML->version, (string) $branchXML->version, ">")) {
     echo "Master is a higher (" . (string) $masterXML->version . ") version than this release (" . (string) $branchXML->version . ")? Scary? Aborting\n";
     $merge = false;
 }
 if (freepbx::version_compare_freepbx((string) $masterXML->version, (string) $branchXML->version, "=")) {
     echo "Master IS already this version\n";
     $merge = false;
 }
 if ($merge) {
예제 #29
0
 /**
  * Creates a GitHub repository with the given name.
  *
  * @param string $repo Name of the repository (slug)
  *
  * @return bool True if GitHub repository was created, false otherwise.
  */
 protected function _createGithubRepo($repo)
 {
     try {
         $client = new Github\Client();
         $client->getHttpClient()->setOption('user_agent', Configure::read('GitHub.user_agent'));
         $client->authenticate(GITHUB_USERNAME, GITHUB_PASSWORD, Github\Client::AUTH_HTTP_PASSWORD);
         $client->getHttpClient()->post('orgs/' . Configure::read('GitHub.org_name') . '/repos', array('name' => $repo, 'description' => Configure::read('GitHub.repo_description'), 'homepage' => sprintf(Configure::read('App.plugin_app_url'), $repo), 'has_issues' => false, 'has_wiki' => false, 'has_downloads' => false));
     } catch (Exception $exception) {
         $this->out(__('<warning>Failed to create GitHub repository for "%s": %s</warning>', $repo, $exception->getMessage()));
         return false;
     }
     return true;
 }
예제 #30
0
$pimple = new \Pimple\Container();
$pimple['config'] = function ($c) {
    return include 'config/config.php';
};
$pimple['camera'] = function ($c) {
    $config = $c['config'];
    return new \TekBooth\Service\GoPro\Client($config['gopro']['password']);
};
$pimple['pubnub'] = function ($c) {
    $config = $c['config'];
    return new \Pubnub\Pubnub($config['pubnub']);
};
$pimple['github'] = function ($c) {
    $config = $c['config'];
    $github = new \Github\Client();
    $github->authenticate($config['github']['key'], null, $github::AUTH_HTTP_TOKEN);
    return $github;
};
$pimple['darkroom'] = function ($c) {
    $config = $c['config'];
    $github = $c['github'];
    return new TekBooth\Service\Darkroom\GithubDarkroom($github, 'templates/set.html', 'templates/photo.html', $config['github']['repo'], $config['github']['url'], $config['github']['branch']);
};
$pimple['photographer'] = function ($c) {
    $config = $c['config'];
    $photographer = new \TekBooth\Workers\Photographer($c['camera'], $c['pubnub'], $c['darkroom'], $config['channel']);
    return new \TekBooth\Daemon\ClosureDaemon($photographer, [$photographer, 'setup']);
};
$pimple['developer'] = function ($c) {
    $developer = new \TekBooth\Workers\Developer($c['camera'], $c['darkroom'], new \Imagine\Gd\Imagine(), 'templates/watermark.png');
    return new \TekBooth\Daemon\ClosureDaemon($developer, [$developer, 'setup']);