1<?php
2/*
3This program is free software; you can redistribute it and/or
4modify it under the terms of the GNU General Public License
5version 2 as published by the Free Software Foundation.
6
7This program is distributed in the hope that it will be useful,
8but WITHOUT ANY WARRANTY; without even the implied warranty of
9MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10GNU General Public License for more details.
11
12You should have received a copy of the GNU General Public License along
13with this program; if not, write to the Free Software Foundation, Inc.,
1451 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
15*/
16
17namespace Fossology\Lib\Application;
18
19/**
20 * @file
21 * @brief Helper class to get the latest release and commits from GitHub API
22 */
23
24/**
25 * @class RepositoryApi
26 * @brief Helper class to get the latest release and commits from GitHub API
27 */
28class RepositoryApi
29{
30  /**
31   * @var Fossology::Lib::Application::CurlRequestService $curlRequestService
32   * Curl request service object for interation with GitHub API
33   */
34  private $curlRequestService = null;
35
36  /**
37   * Constructor
38   * @param Fossology::Lib::Application::CurlRequestService $curlRequestService
39   */
40  public function __construct($curlRequestService)
41  {
42    $this->curlRequestService = $curlRequestService;
43  }
44
45  /**
46   * @brief Send a curl request to apiRequest for resource
47   * @param string $apiRequest Required resource
48   * @return array Response from GitHub API
49   */
50  private function curlGet($apiRequest)
51  {
52    $url = 'https://api.github.com/repos/fossology/fossology/'.$apiRequest;
53
54    $request = $this->curlRequestService->create($url);
55    $curlopt = array(
56      CURLOPT_HEADER         => true,
57      CURLOPT_RETURNTRANSFER => true,
58      CURLOPT_HTTPHEADER     => array('User-Agent: fossology'),
59      CURLOPT_TIMEOUT        => 2,
60    );
61    $request->setOptions($curlopt);
62    $response = $request->execute();
63    if ($response !== false) {
64      $headerSize = $request->getInfo(CURLINFO_HEADER_SIZE);
65      $resultBody = json_decode(substr($response, $headerSize), true);
66    } else {
67      $resultBody = array();
68    }
69    $request->close();
70
71    return $resultBody;
72  }
73
74  /**
75   * @brief Get the latest release info from GitHub
76   * @return array
77   */
78  public function getLatestRelease()
79  {
80    return $this->curlGet('releases/latest');
81  }
82
83  /**
84   * @brief Get the commits from past n days.
85   * @param int $days Number of days commits are required.
86   * @return array
87   */
88  public function getCommitsOfLastDays($days = 30)
89  {
90    $since = '?since=' . date('Y-m-d\\TH:i:s\\Z', time() - 3600 * 24 * $days);
91    return $this->curlGet('commits' . $since);
92  }
93}
94