GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.

Issues (1410)

Security Analysis    not enabled

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.

protected/extensions/retailcrm/RetailCrm.php (13 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
 * @author Alexey Tatarinov <[email protected]>
4
 * @link https://github.com/shogodev/argilla/
5
 * @copyright Copyright &copy; 2003-2015 Shogo
6
 * @license http://argilla.ru/LICENSE
7
 *
8
 * Пример подключения в frontend.php:
9
 * 'components' => array(
10
 *   ...
11
 *   'retailCrm' => array(
12
 *     'class' => 'ext.retailcrm.RetailCrm',
13
 *   ),
14
 *   ...
15
 * )
16
 */
17
Yii::import('frontend.components.cli.*');
18
Yii::import('ext.retailcrm.components.RetailCrmDataManager');
19
20
Yii::import('ext.retailcrm.components.lib.ApiClient', true);
21
Yii::import('ext.retailcrm.components.lib.Http.Client', true);
22
Yii::import('ext.retailcrm.components.lib.Exception.CurlException', true);
23
Yii::import('ext.retailcrm.components.lib.Exception.InvalidJsonException', true);
24
Yii::import('ext.retailcrm.components.lib.Response.ApiResponse', true);
25
26
/**
27
 * Class RetailCrm
28
 */
29
class RetailCrm extends CApplicationComponent
30
{
31
  public $debug = false;
32
33
  /**
34
   * @var string $url
35
   */
36
  protected $url;
37
38
  /**
39
   * @var string $apiKey
40
   */
41
  protected $apiKey;
42
43
  /**
44
   * @var boolean $enabled
45
   */
46
  protected $enabled;
47
48
  /**
49
   * @var boolean $log
50
   */
51
  protected $log;
52
53
  /**
54
   * @var ConsoleFileLogger $logger
55
   */
56
  public $logger;
57
58
  /**
59
   * @var RetailCrmDataManager $retailCrmDataManager
60
   */
61
  protected $retailCrmDataManager; 
62
63
  protected $exportProductCounter;
64
65
  /**
66
   * @var RetailCrm\ApiClient $apiClient
67
   */
68
  private $apiClient;
69
70
  public function init()
71
  {
72
    parent::init();
73
74
    $this->retailCrmDataManager = new RetailCrmDataManager();
75
76
    $this->configure();
77
78
    $this->logger = new ConsoleFileLogger('retail_crm.log');
79
    $this->logger->showLog = false;
80
81
    $this->apiClient = new RetailCrm\ApiClient(
82
      $this->url,
83
      $this->apiKey
84
    );
85
  }
86
87 View Code Duplication
  public function createCallback(Callback $model)
0 ignored issues
show
This method seems to be duplicated in 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...
88
  {
89
    if( !$this->enabled )
90
      return;
91
92
    Utils::finishRequest();
93
94
    try
95
    {
96
      $data = $this->retailCrmDataManager->getCallbackData($model);
97
    }
98
    catch(CException $e)
0 ignored issues
show
The class CException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
99
    {
100
      $this->logger->error('Ошибка в формировании данных для RetailCrm. '.$e->getMessage());
101
      return;
102
    }
103
    $this->setCustomerData($data);
104
105
    if( $retailCrmOrderId = $this->sendOrder($data, $model) )
0 ignored issues
show
$retailCrmOrderId 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...
106
    {
107
      $this->retailCrmDataManager->setRetailCrmUrl($model, $data['number'], $this->url);
108
    }
109
  }
110
111 View Code Duplication
  public function createOrder(Order $model)
0 ignored issues
show
This method seems to be duplicated in 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...
112
  {
113
    if( !$this->enabled )
114
      return;
115
116
    Utils::finishRequest();
117
118
    try
119
    {
120
      $data = $this->retailCrmDataManager->getOrderData($model);
121
    }
122
    catch(CException $e)
0 ignored issues
show
The class CException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
123
    {
124
      $this->logger->error('Ошибка в формировании данных для RetailCrm. '.$e->getMessage());
125
      return;
126
    }
127
128
    $this->setCustomerData($data);
129
    if( $retailCrmOrderId = $this->sendOrder($data, $model) )
130
    {
131
      $this->retailCrmDataManager->updateOrderStatus($model);
132
      $this->retailCrmDataManager->setRetailCrmUrl($model, $retailCrmOrderId, $this->url);
133
    }
134
  }
135
136
  public function registerEventEndExportIcml()
137
  {
138
    if( Yii::app()->request->getParam('force') != 'force' )
139
      return;
140
141
    $this->logger->startTimer(get_class($this));
142
    $this->logger->log('Начало экспорта icml', true);
143
    Yii::app()->attachEventHandler('onEndRequest', array($this, 'onEndExport'));
144
    Yii::app()->attachEventHandler('onException', array($this, 'onError'));
145
    Yii::app()->attachEventHandler('onError', array($this, 'onError'));
146
    register_shutdown_function(array($this, 'exceptionShutdown'));
147
  }
148
149
  public function onEndExport($event)
150
  {
151
    $logMessage = 'Экспорт icml завершен за '.$this->logger->finishTimer(get_class($this)).PHP_EOL;
152
    $logMessage .= 'Обработано '.$this->exportProductCounter.' продуктов.'.PHP_EOL;
153
    $this->logger->log($logMessage, true, true);
154
  }
155
156
  public function onError($event)
157
  {
158
    if( isset($event->exception) )
159
      $this->logger->error($event->exception->getMessage());
160
    else if( isset($event->message) )
161
      $this->logger->error($event->message);
162
    else
163
      $this->logger->error("Не известная ошибка");
164
  }
165
166
  public function exceptionShutdown()
167
  {
168
    $error = error_get_last();
169
170
    if (is_array($error) != FALSE)
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison !== instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
171
    {
172
      if (isset($error['type']) != FALSE)
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison !== instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
173
      {
174
        if ($error['type'] == 1)
175
        {
176
          $this->logger->error("Фатальная ошибка: ".$error['message']);
177
        }
178
      }
179
    }
180
  }
181
182
  public function increaseExportProductCounter()
183
  {
184
    $this->exportProductCounter++;
185
  }
186
187
  /**
188
   * @return ConsoleFileLogger
189
   */
190
  public function getLogger()
191
  {
192
    return $this->logger;
193
  }
194
195
  public function createDebugReport($attributes, $offerCounter)
196
  {
197
    if( $this->debug )
198
    {
199
      $log = 'Product id = '.$attributes['id'].' process'.PHP_EOL;
200
      $log .= 'Processed items '.$offerCounter.' Date '.date('d.m.Y H:i:s').PHP_EOL;
201
      $log .= 'Usage memory is '.round(memory_get_usage() / 1024).' KBt'.PHP_EOL;
202
      $log .= 'Peak usage memory is '.round(memory_get_peak_usage() / 1024).' KBt'.PHP_EOL;
203
      file_put_contents(Yii::getPathOfAlias('frontend.runtime').'/retail_crm_debug.log', array($log));
204
    }
205
  }
206
207
  /**
208
   * @param array $data
209
   *
210
   * @return null
211
   */
212
  private function setCustomerData(&$data = array())
213
  {
214
    $filter = array();
215
216
    if( !empty($data['phone']) )
217
      $filter['name'] = $data['phone'];
218
    else if( !empty($data['email']) )
219
      $filter['email'] = $data['email'];
220 View Code Duplication
    else
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...
221
    {
222
      $nameArray = array();
223
      if( !empty($data['lastName']) )
224
        $nameArray[] = $data['lastName'];
225
      if( !empty($data['firstName']) )
226
        $nameArray[] = $data['firstName'];
227
      if( !empty($data['patronymic']) )
228
        $nameArray[] = $data['patronymic'];
229
230
      if( !empty($nameArray) )
231
        $filter['name'] = implode(' ', $nameArray);
232
    }
233
234
    if( empty($filter) )
235
      return;
236
237
    try
238
    {
239
      $response = $this->apiClient->customersList($filter);
240
    }
241
    catch(\RetailCrm\Exception\CurlException $e)
242
    {
243
      if( $this->log )
244
        $this->logger->error("Сетевые проблемы. Ошибка подключения к retailCRM: ".$e->getMessage());
245
246
      return;
247
    }
248
249
    if( $response->isSuccessful() )
250
    {
251
      if( !($user = Arr::reset($response->customers)) )
0 ignored issues
show
The property customers does not exist on object<RetailCrm\Response\ApiResponse>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
252
        return;
253
254
      if( isset($user['customerId']) )
255
      {
256
        $data['customerId'] = $user['customerId'];
257
      }
258
    }
259
    else
260
    {
261
      if( $this->log )
262
      {
263
        $errorMessage = "Ошибка при запросе пользователей: [Статус HTTP-ответа ".$response->getStatusCode()."] ".$response->getErrorMsg().'.';
0 ignored issues
show
Documentation Bug introduced by
The method getErrorMsg does not exist on object<RetailCrm\Response\ApiResponse>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
264
        if( $response->offsetExists('errors') )
265
          $errorMessage .= ' '.$response->offsetGet('errors');
266
267
        $this->logger->error($errorMessage);
268
      }
269
    }
270
  }
271
272
  private function configure()
273
  {
274
    $configPath = Yii::getPathOfAlias('frontend.config.retail_crm').'.php';
275
    if( file_exists($configPath) )
276
    {
277
      $config = require($configPath);
278
      $this->url = $config['url'];
279
      $this->apiKey = $config['apiKey'];
280
281
      if( isset($config['idPrefix']) )
282
        $this->retailCrmDataManager->idPrefix = $config['idPrefix'];
283
284
      if( isset($config['log']) )
285
        $this->log = $config['log'];
286
287
      if( isset($config['debug']) )
288
        $this->debug = $config['debug'];
289
290
      $this->enabled = $config['enabled'];
291
    }
292
    else
293
    {
294
      throw new CHttpException('500', 'Не найден кофигурационный файл retail_crm.php в папке config');
295
    }
296
  }
297
298
  /**
299
   * @param array $data
300
   * @param CActiveRecord $model
301
   *
302
   * @return null|string $retailCrmId
303
   */
304
  private function sendOrder(array $data, CActiveRecord $model)
305
  {
306
    try
307
    {
308
      $response = $this->apiClient->ordersCreate($data);
309
    }
310
    catch(\RetailCrm\Exception\CurlException $e)
311
    {
312
      if( $this->log )
313
        $this->logger->error("Сетевые проблемы. Ошибка подключения к retailCRM: ".$e->getMessage());
314
315
      return null;
316
    }
317
318
    if( $response->isSuccessful() && 201 === $response->getStatusCode() )
319
    {
320
      if( $this->log )
321
        $this->logger->log('Заказ ('.get_class($model).') успешно создан id = '.$model->id.' retail_crm_id = '.$response->id);
0 ignored issues
show
The property id does not exist on object<RetailCrm\Response\ApiResponse>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
322
323
      return $response->id;
0 ignored issues
show
The property id does not exist on object<RetailCrm\Response\ApiResponse>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
324
    }
325
    else
326
    {
327
      if( $this->log )
328
      {
329
        $errorMessage = "Ошибка создания заказа(".get_class($model).") id = {$model->id}: [Статус HTTP-ответа ".$response->getStatusCode()."] ".$response->getErrorMsg().'.';
0 ignored issues
show
Documentation Bug introduced by
The method getErrorMsg does not exist on object<RetailCrm\Response\ApiResponse>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
330
        if( $response->offsetExists('errors') )
331
          $errorMessage .= ' '.print_r($response->offsetGet('errors'), true);
332
333
        $this->logger->error($errorMessage);
334
      }
335
    }
336
337
    return null;
338
  }
339
}