Advertisement
aivavic

api

May 14th, 2015
269
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 5.98 KB | None | 0 0
  1. <?php
  2.  
  3. /**
  4.  * Created by PhpStorm.
  5.  * User: viktor_
  6.  * Date: 5/4/15
  7.  * Time: 10:16 PM
  8.  */
  9. error_reporting(E_STRICT | E_ALL);
  10. class GitAuth2 extends CComponent
  11. {
  12.  
  13.     const OAUTH2_CLIENT_ID = 'cc64d12df7aabfdc420b';
  14.     const OAUTH2_CLIENT_SECRET = '64e88aefd4358240793c5816b7a3adb38da2ca26';
  15.  
  16.     private $authorizeURL = 'https://github.com/login/oauth/authorize';
  17.     private $tokenURL = 'https://github.com/login/oauth/access_token';
  18.     private $apiURLBase = 'https://api.github.com/';
  19.     private $user_agent;
  20.  
  21.     protected static $_instance;
  22.  
  23.     private function __construct(){
  24.     $this->start();
  25.     }
  26.  
  27.  
  28.     private function __clone(){
  29.     }
  30.  
  31.     public static function getInstance() {
  32.         // проверяем актуальность экземпляра
  33.         if (null === self::$_instance) {
  34.             // создаем новый экземпляр
  35.             self::$_instance = new self();
  36.         }
  37.         // возвращаем созданный или существующий экземпляр
  38.         return self::$_instance;
  39.     }
  40.  
  41.  
  42.  
  43.     public function start()
  44.     {
  45.         session_start();
  46.         if ($this->get('action') == 'login') {
  47.             $_SESSION['state'] = hash('sha256', microtime(TRUE) . rand() . $_SERVER['REMOTE_ADDR']);
  48.             unset($_SESSION['access_token']);
  49.  
  50.             $params = array(
  51.                 'client_id' => self::OAUTH2_CLIENT_ID,
  52.                 'redirect_uri' => 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['PHP_SELF'],
  53.                 'scope' => 'user',
  54.                 'state' => $_SESSION['state']
  55.             );
  56.  
  57.             // Redirect the user to Github's authorization page
  58.             header('Location: ' . $this->authorizeURL . '?' . http_build_query($params));
  59.             die();
  60.         }
  61.  
  62. // When Github redirects the user back here, there will be a "code" and "state" parameter in the query string
  63.         if ($this->get('code')) {
  64.             // Verify the state matches our stored state
  65.             if (!$this->get('state') || $_SESSION['state'] != $this->get('state')) {
  66.                 header('Location: ' . $_SERVER['PHP_SELF']);
  67.                 die();
  68.             }
  69.  
  70.             // Exchange the auth code for a token
  71.             $token = $this->apiRequest($this->tokenURL, array(
  72.                 'client_id' => self::OAUTH2_CLIENT_ID,
  73.                 'client_secret' => self::OAUTH2_CLIENT_SECRET,
  74.                 'redirect_uri' => 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['PHP_SELF'],
  75.                 'state' => $_SESSION['state'],
  76.                 'code' => $this->get('code')
  77.             ));
  78.             $_SESSION['access_token'] = $token->access_token;
  79.  
  80.             header('Location: ' . $_SERVER['PHP_SELF']);
  81.         }
  82.  
  83.         if ($this->session('access_token')) {
  84.             $query = $this->apiURLBase . 'search/repositories?q=films+language:php&sort=stars&order=desc';
  85.             var_dump($query);
  86.             $user = $this->apiRequest($this->apiURLBase . 'user');
  87. //            $search = $this->apiRequest($query);
  88.             $name = isset($user->name) ? $user->name : 'noname';
  89.             echo '<h3>Logged In</h3>';
  90.             echo '<h4>' . $name . '</h4>';
  91.             echo '<img src = "'. $user->avatar_url . '" style="width: 100px;"/>';
  92. //            $this->repList($user->repos_url);
  93.             echo '<pre>';
  94.  
  95. //            print_r($user->repos_url);
  96.  
  97.             echo '</pre>';
  98.  
  99.         } else {
  100.             echo '<h3>Not logged in</h3>';
  101.             echo '<p><a href="?action=login">Log In</a></p>';
  102.         }
  103.  
  104.     }
  105.  
  106.     function repList($url){
  107.         $repositories = $this->apiRequest($url);
  108.         echo '<pre>';
  109.  
  110.         echo '<ul> Мои репозитории: ';
  111.         foreach($repositories as $repositorie){
  112.             echo '<li><a href="'. $repositorie->html_url . '" >' . $repositorie->full_name . '</a></li>';
  113.         }
  114.         echo '</ul>';
  115.         var_dump($repositories);
  116.         echo '</pre>';
  117.     }
  118.     function apiRequest($url, $post = FALSE, $headers = array())
  119.     {
  120.         $this->user_agent = 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.0.3705; .NET CLR 1.1.4322; Media Center PC 4.0)';
  121.         $ch = curl_init($url);
  122.         curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
  123.         curl_setopt($ch, CURLOPT_USERAGENT, $this->user_agent);
  124.         if ($post)
  125.             curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
  126.  
  127. //        $headers[] = 'Accept: application/json';
  128.         $headers[] = 'Accept: application/vnd.github.moondragon+json';
  129.  
  130.         if ($this->session('access_token'))
  131.             $headers[] = 'Authorization: Bearer ' . $this->session('access_token');
  132.  
  133.         curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  134.  
  135.         $response = curl_exec($ch);
  136. //        var_dump($response);
  137.         return json_decode($response);
  138.     }
  139.  
  140.     function get($key, $default = NULL)
  141.     {
  142.         return array_key_exists($key, $_GET) ? $_GET[$key] : $default;
  143.     }
  144.  
  145.     function session($key, $default = NULL)
  146.     {
  147.         return array_key_exists($key, $_SESSION) ? $_SESSION[$key] : $default;
  148.     }
  149.     function search($query){
  150.         $this->user_agent = 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.0.3705; .NET CLR 1.1.4322; Media Center PC 4.0)';
  151.         $search = '/search/repositories?q=yii2+language:php&sort=stars&order=desc';
  152.         $url = $this->apiURLBase . $search;
  153.         $ch = curl_init($url);
  154.         curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
  155.         curl_setopt($ch, CURLOPT_USERAGENT, $this->user_agent);
  156.  
  157.  
  158. //        $headers[] = 'Accept: application/json';
  159.         $headers[] = 'Accept: application/vnd.github.moondragon+json';
  160.  
  161.         if ($this->session('access_token'))
  162.             $headers[] = 'Authorization: Bearer ' . $this->session('access_token');
  163.  
  164.         curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  165.  
  166.         $response = curl_exec($ch);
  167. //        var_dump($response);
  168.         return json_decode($response);
  169.     }
  170.  
  171. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement