Issues (19)

Security Analysis    no request data  

This project does not seem to handle request data directly as such no vulnerable execution paths were found.

  Cross-Site Scripting
Cross-Site Scripting enables an attacker to inject code into the response of a web-request that is viewed by other users. It can for example be used to bypass access controls, or even to take over other users' accounts.
  File Exposure
File Exposure allows an attacker to gain access to local files that he should not be able to access. These files can for example include database credentials, or other configuration files.
  File Manipulation
File Manipulation enables an attacker to write custom data to files. This potentially leads to injection of arbitrary code on the server.
  Object Injection
Object Injection enables an attacker to inject an object into PHP code, and can lead to arbitrary code execution, file exposure, or file manipulation attacks.
  Code Injection
Code Injection enables an attacker to execute arbitrary code on the server.
  Response Splitting
Response Splitting can be used to send arbitrary responses.
  File Inclusion
File Inclusion enables an attacker to inject custom files into PHP's file loading mechanism, either explicitly passed to include, or for example via PHP's auto-loading mechanism.
  Command Injection
Command Injection enables an attacker to inject a shell command that is execute with the privileges of the web-server. This can be used to expose sensitive data, or gain access of your server.
  SQL Injection
SQL Injection enables an attacker to execute arbitrary SQL code on your database server gaining access to user data, or manipulating user data.
  XPath Injection
XPath Injection enables an attacker to modify the parts of XML document that are read. If that XML document is for example used for authentication, this can lead to further vulnerabilities similar to SQL Injection.
  LDAP Injection
LDAP Injection enables an attacker to inject LDAP statements potentially granting permission to run unauthorized queries, or modify content inside the LDAP tree.
  Header Injection
  Other Vulnerability
This category comprises other attack vectors such as manipulating the PHP runtime, loading custom extensions, freezing the runtime, or similar.
  Regex Injection
Regex Injection enables an attacker to execute arbitrary code in your PHP process.
  XML Injection
XML Injection enables an attacker to read files on your local filesystem including configuration files, or can be abused to freeze your web-server process.
  Variable Injection
Variable Injection enables an attacker to overwrite program variables with custom data, and can lead to further vulnerabilities.
Unfortunately, the security analysis is currently not available for your project. If you are a non-commercial open-source project, please contact support to gain access.

src/ForecastIO.php (5 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
/**
3
 *
4
 * PHP version 5.5
5
 *
6
 * @package Forecast
7
 * @author  Sergey V.Kuzin <[email protected]>
8
 * @license MIT
9
 */
10
11
namespace Forecast;
12
13
14
use Forecast\Helper\Point;
15
use Psr\Cache\CacheItemPoolInterface;
16
use Psr\Log\LoggerInterface;
17
18
/**
19
 * Получение информации о погоде с сервиса forecast.io.
20
 *
21
 * Для работы необходимо получить key на сайте https://developer.forecast.io
22
 *
23
 * PHP version 5.5
24
 *
25
 * @package Forecast
26
 * @author  Sergey V.Kuzin <[email protected]>
27
 * @license http://opensource.org/licenses/MIT The MIT License (MIT)
28
 *
29
 */
30
class ForecastIO extends WeatherAbstract
31
{
32
    /**
33
     * @var string
34
     */
35
    protected $apiKey = null;
36
    protected $pint = null;
37
38
    /**
39
     * Полу
40
     *
41
     * @param string $apiKey Ключ получченный на https://developer.forecast.io/
42
     *       Получить ключь можно бесплатно. Каждому дано 100 бесплатных запров в день к серверу.
43
     * @param CacheItemPoolInterface|null $cache Экземпляра класса кэширования по стандарту PSR-6
44
     * @param LoggerInterface|null $logger Экземляр класса логера сандарта PSR-3
45
     *
46
     * @api
47
     */
48
    public function __construct($apiKey, CacheItemPoolInterface $cache = null, LoggerInterface $logger = null)
49
    {
50
        $this->apiKey = $apiKey;
51
        parent::__construct($cache, $logger);
52
    }
53
54
    protected function doFetchAll(Point $point)
55
    {
56
        if ($point->getType() == Point::ADDRESS) {
57
            throw new \InvalidArgumentException();
58
        }
59
60
        $key = 'weather.fc.io-all-' . md5(serialize([$this->getLang(), $this->getUnits(), $point->getKey()]));
61
        $item = $this->cache->getItem($key);
62
        if (!$item->isHit()) {
63
            $params = [
64
                'units' => $this->getUnits(),
65
                'lang' => $this->getLang(),
66
                'exclude' => 'flags'
67
            ];
68
            $url = 'https://api.forecast.io/forecast/' . $this->apiKey . '/' . $point->getLatitude() . ',' . $point->getLongitude();
69
70
            $client = new \GuzzleHttp\Client();
71
72
            $response = $client->get($url, ['debug' => false, 'query' => $params]);
73
74
            $result = json_decode($response->getBody()->getContents(), true);
75
76
            if ($result !== null) {
77
                list($n, $exp) = explode('=', $response->getHeader('Cache-Control'));
0 ignored issues
show
The assignment to $n is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
78
                $exp = (int)$exp;
0 ignored issues
show
$exp is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
79
                $exp  = 60*15;
80
                $this->expiration = \DateTime::createFromFormat(
0 ignored issues
show
Documentation Bug introduced by
It seems like \DateTime::createFromFormat('U', time() + $exp) can also be of type false. However, the property $expiration is declared as type object<DateTime>. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
81
                    'U',
82
                    time() + $exp
83
                );
84
                $item->set($result)
85
                    ->expiresAfter($exp)
86
                    ->addTag('weather');
87
                $this->cache->save($item);
88
            }
89
        }
90
91
        return $item->get();
92
    }
93
94
    /**
95
     * @internal
96
     * @return \Forecast\Current
97
     */
98
    protected function doFetchCurrent(Point $point)
99
    {
100
        if ($point->getType() == Point::ADDRESS) {
101
            throw new \InvalidArgumentException();
102
        }
103
        $result = $this->doFetchAll($point);
104
        $result = $result['currently'];
105
106
        $cur = new Current();
107
108
        $precipType = self::PRECIP_TYPE_NONE;
109 View Code Duplication
        if ($result['precipProbability'] > 0) {
0 ignored issues
show
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
110
            switch ($result['precipType']) {
111
                case 'rain':
112
                    $precipType = self::PRECIP_TYPE_RAIN;
113
                    break;
114
                case 'snow':
115
                    $precipType = self::PRECIP_TYPE_SNOW;
116
                    break;
117
                case 'sleet':
118
                    $precipType = self::PRECIP_TYPE_SLEET;
119
                    break;
120
                case 'hail':
121
                    $precipType = self::PRECIP_TYPE_HAIL;
122
                    break;
123
                default:
124
                    throw new \Exception('Не известный тип precipType: ' . $result['precipType']);
125
            }
126
        }
127
        $cur->setData([
128
            'summary' => $result['summary'],
129
            'temperature' => [
130
                'current' => $result['temperature'],
131
                'apparent' => $result['apparentTemperature']
132
            ],
133
            'wind' => [
134
                'speed' => $result['windSpeed'],
135
                'degree' => $result['windBearing'],
136
            ],
137
            'precipitation' => [
138
                'intensity' => $result['precipIntensity'],
139
                'probability' => $result['precipProbability'] * 100,
140
                'type' => $precipType,
141
            ],
142
            'humidity' => [
143
                'humidity' => $result['humidity']
144
            ]
145
        ]);
146
147
        return $cur;
148
    }
149
150
    /**
151
     * @param Point $point Класс с коорденатами места для которой запрашивается погода
152
     * @internal
153
     * @return string
154
     */
155
    protected function getCacheKeyCurrent(Point $point)
156
    {
157
        return 'weather.fc.io-current-' . md5(serialize([$this->getLang(), $this->getUnits(), $point->getKey()]));
158
    }
159
160
    /**
161
     * @internal
162
     * @return \DateTime
163
     */
164
    protected function getCacheExpirationCurrent()
165
    {
166
        return $this->expiration;
167
    }
168
169
    /**
170
     * @param Point $point
171
     * @return Hourly
172
     */
173
    protected function doFetchHourly(Point $point)
174
    {
175
        if ($point->getType() == Point::ADDRESS) {
176
            throw new \InvalidArgumentException();
177
        }
178
179
        $result = $this->doFetchAll($point);
180
        $result = $result['hourly'];
181
182
        $hours = [];
183
        foreach ($result['data'] as $item) {
184
            $precipType = self::PRECIP_TYPE_NONE;
185 View Code Duplication
            if ($item['precipProbability'] > 0) {
0 ignored issues
show
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
186
                switch ($item['precipType']) {
187
                    case 'rain':
188
                        $precipType = self::PRECIP_TYPE_RAIN;
189
                        break;
190
                    case 'snow':
191
                        $precipType = self::PRECIP_TYPE_SNOW;
192
                        break;
193
                    case 'sleet':
194
                        $precipType = self::PRECIP_TYPE_SLEET;
195
                        break;
196
                    case 'hail':
197
                        $precipType = self::PRECIP_TYPE_HAIL;
198
                        break;
199
                    default:
200
                        throw new \Exception('Не известный тип precipType: ' . $item['precipType']);
201
                }
202
            }
203
204
            $hours[] = [
205
                'summary' => $item['summary'],
206
                'date' => new \DateTime(date(\DateTime::RFC3339, $item['time'])),
207
                'temperature' => [
208
                    'current' => $item['temperature'],
209
                    'apparent' => $item['apparentTemperature']
210
                ],
211
                'wind' => [
212
                    'speed' => $item['windSpeed'],
213
                    'degree' => $item['windBearing'],
214
                ],
215
                'precipitation' => [
216
                    'intensity' => $item['precipIntensity'],
217
                    'probability' => $item['precipProbability'] * 100,
218
                    'type' => $precipType,
219
                ],
220
                'humidity' => [
221
                    'humidity' => $item['humidity']
222
                ],
223
                'icon' => $item['icon']
224
            ];
225
        }
226
227
        $hourly = new Hourly();
228
        $hourly->setData([
229
            'summary' => $result['summary'],
230
            'hours' => $hours
231
        ]);
232
233
        return $hourly;
234
    }
235
236
    /**
237
     * @param Point $point
238
     *
239
     * @internal
240
     * @return string
241
     */
242
    protected function getCacheKeyHourly(Point $point)
243
    {
244
        return 'weather.fc.io-hourly-' . md5(serialize([$this->getLang(), $this->getUnits(), $point->getKey()]));
245
    }
246
247
    /**
248
     *
249
     * @internal
250
     * @return \DateTime
251
     */
252
    protected function getCacheExpirationHourly()
253
    {
254
        return $this->expiration;
255
    }
256
}
257