Issues (453)

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.

src/controllers/PlanController.php (1 issue)

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
 * Finance module for HiPanel
4
 *
5
 * @link      https://github.com/hiqdev/hipanel-module-finance
6
 * @package   hipanel-module-finance
7
 * @license   BSD-3-Clause
8
 * @copyright Copyright (c) 2015-2019, HiQDev (http://hiqdev.com/)
9
 */
10
11
namespace hipanel\modules\finance\controllers;
12
13
use hipanel\actions\Action;
14
use hipanel\actions\IndexAction;
15
use hipanel\actions\SmartCreateAction;
16
use hipanel\actions\SmartDeleteAction;
17
use hipanel\actions\SmartPerformAction;
18
use hipanel\actions\SmartUpdateAction;
19
use hipanel\actions\ValidateFormAction;
20
use hipanel\actions\ViewAction;
21
use hipanel\base\CrudController;
22
use hipanel\filters\EasyAccessControl;
23
use hipanel\helpers\ArrayHelper;
24
use hipanel\modules\finance\collections\PricesCollection;
25
use hipanel\modules\finance\grid\PriceGridView;
26
use hipanel\modules\finance\helpers\PlanInternalsGrouper;
27
use hipanel\modules\finance\helpers\PriceChargesEstimator;
28
use hipanel\modules\finance\helpers\PriceSort;
29
use hipanel\modules\finance\models\factories\PriceModelFactory;
30
use hipanel\modules\finance\models\Plan;
31
use hipanel\modules\finance\models\Price;
32
use hipanel\modules\finance\models\PriceSuggestionRequestForm;
33
use hipanel\modules\finance\models\query\PlanQuery;
34
use hipanel\modules\finance\models\TargetObject;
35
use hiqdev\hiart\ResponseErrorException;
36
use Yii;
37
use yii\base\Event;
38
use yii\base\Module;
39
use yii\data\ArrayDataProvider;
40
use yii\web\NotFoundHttpException;
41
use yii\web\Response;
42
use yii\web\UnprocessableEntityHttpException;
43
44
class PlanController extends CrudController
45
{
46
    /**
47
     * @var PriceModelFactory
48
     */
49
    public $priceModelFactory;
50
51
    /**
52
     * PlanController constructor.
53
     * @param string $id
54
     * @param Module $module
55
     * @param PriceModelFactory $priceModelFactory
56
     * @param array $config
57
     */
58
    public function __construct(string $id, Module $module, PriceModelFactory $priceModelFactory, array $config = [])
59
    {
60
        parent::__construct($id, $module, $config);
61
62
        $this->priceModelFactory = $priceModelFactory;
63
    }
64
65
    public function behaviors()
66
    {
67
        return array_merge(parent::behaviors(), [
68
            [
69
                'class' => EasyAccessControl::class,
70
                'actions' => [
71
                    'create' => 'plan.create',
72
                    'update' => 'plan.update',
73
                    'update-prices' => 'plan.update',
74
                    'templates' => 'plan.create',
75
                    'create-prices' => 'plan.create',
76
                    'delete' => 'plan.delete',
77
                    '*' => 'plan.read',
78
                ],
79
            ],
80
        ]);
81
    }
82
83
    public function actions()
84
    {
85
        return array_merge(parent::actions(), [
86
            'create' => [
87
                'class' => SmartCreateAction::class,
88
                'success' => Yii::t('hipanel.finance.plan', 'Plan was successfully created'),
89
            ],
90
            'update' => [
91
                'class' => SmartUpdateAction::class,
92
                'success' => Yii::t('hipanel.finance.plan', 'Plan was successfully updated'),
93
            ],
94
            'index' => [
95
                'class' => IndexAction::class,
96
            ],
97
            'view' => [
98
                'class' => ViewAction::class,
99
                'on beforePerform' => function (Event $event) {
100
                    /** @var PlanQuery $query */
101
                    $query = $event->sender->getDataProvider()->query;
102
                    $query
103
                        ->withSales()
104
                        ->withPrices()
105
                        ->withPriceHistory();
106
                },
107
                'data' => function (Action $action, array $data) {
108
                    return array_merge($data, array_filter([
109
                        'grouper' => new PlanInternalsGrouper($data['model']),
110
                        'parentPrices' => Yii::$app->user->can('plan.update') ? $this->getParentPrices($data['model']['id']) : null,
111
                    ]));
112
                },
113
            ],
114
            'set-note' => [
115
                'class' => SmartUpdateAction::class,
116
                'success' => Yii::t('hipanel', 'Note changed'),
117
            ],
118
            'validate-form' => [
119
                'class' => ValidateFormAction::class,
120
            ],
121
            'validate-single-form' => [
122
                'class' => ValidateFormAction::class,
123
                'validatedInputId' => false,
124
            ],
125
            'delete' => [
126
                'class' => SmartDeleteAction::class,
127
                'success' => Yii::t('hipanel.finance.plan', 'Plan was successfully deleted'),
128
            ],
129
            'restore' => [
130
                'class' => SmartPerformAction::class,
131
                'success' => Yii::t('hipanel.finance.plan', 'Plan was successfully restored'),
132
            ],
133
            'copy' => [
134
                'class' => SmartUpdateAction::class,
135
                'view' => 'modals/copy',
136
                'queryOptions' => ['batch' => false],
137
            ],
138
        ]);
139
    }
140
141
    public function actionCreatePrices(int $plan_id, int $template_plan_id)
142
    {
143
        $plan = $this->findTemplatePlan($plan_id, $plan_id, $template_plan_id);
144
145
        $suggestions = (new Price())->batchQuery('suggest', [
146
            'object_id' => $plan_id,
147
            'plan_id' => $plan_id,
148
            'template_plan_id' => $template_plan_id,
149
            'type' => $plan->type,
150
        ]);
151
        $this->populateWithPrices($plan, $suggestions);
152
153
        $parentPrices = $this->getParentPrices($plan_id);
154
155
        $targetPlan = Plan::findOne(['id' => $plan_id]);
156
157
        $grouper = new PlanInternalsGrouper($plan);
158
        [$plan->name, $plan->id] = [$targetPlan->name, $targetPlan->id];
159
        $action = ['@plan/update-prices', 'id' => $plan->id, 'scenario' => 'create'];
160
161
        return $this->render($plan->type . '/' . 'createPrices',
162
            compact('plan', 'grouper', 'parentPrices', 'action', 'plan_id'));
163
    }
164
165
    public function actionGetPlanHistory(int $plan_id, string $date)
166
    {
167
        $plan = Plan::find()
168
                    ->where(['id' => $plan_id])
169
                    ->andWhere(['history_time' => $date])
170
                    ->withSales()
171
                    ->withPriceHistory()
172
                    ->one();
173
174
        return PriceGridView::widget([
175
            'boxed' => false,
176
            'showHeader' => true,
177
            'showFooter' => false,
178
            'summaryRenderer' => function (): string {
179
                return '';
180
            },
181
            'emptyText' => Yii::t('hipanel.finance.price', 'No prices found'),
182
            'dataProvider' => new ArrayDataProvider([
183
                'allModels' => $plan->priceHistory,
184
                'pagination' => false,
185
            ]),
186
            'columns' => [
187
                'object->name',
188
                'type',
189
                'object->label',
190
                'old_price',
191
                'note',
192
            ],
193
        ]);
194
    }
195
196
    public function actionSuggestPricesModal($id)
197
    {
198
        /** @var Plan $plan */
199
        $plan = $this->findPlan($id);
200
        $model = new PriceSuggestionRequestForm([
201
            'plan_id' => $plan->id,
202
            'plan_type' => $plan->type,
203
        ]);
204
205
        return $this->renderAjax('modals/suggestPrices', compact('plan', 'model'));
206
    }
207
208
    public function actionSuggestGroupingPricesModal($id)
209
    {
210
        /** @var Plan $plan */
211
        $plan = $this->findPlan($id);
212
        $model = new PriceSuggestionRequestForm([
213
            'plan_id' => $plan->id,
214
            'plan_type' => $plan->type,
215
            'object_id' => $plan->id,
216
            'scenario' => PriceSuggestionRequestForm::SCENARIO_PREDEFINED_OBJECT,
217
        ]);
218
219
        return $this->renderAjax('modals/suggestPrices', compact('plan', 'model'));
220
    }
221
222
    public function actionSuggestSharedPricesModal($id)
223
    {
224
        /** @var Plan $plan */
225
        $plan = $this->findPlan($id);
226
        $model = new PriceSuggestionRequestForm([
227
            'plan_id' => $plan->id,
228
            'plan_type' => $plan->type,
229
            'scenario' => PriceSuggestionRequestForm::SCENARIO_PREDEFINED_OBJECT,
230
        ]);
231
232
        return $this->renderAjax('modals/suggestPrices', compact('plan', 'model'));
233
    }
234
235
    private function findTemplatePlan(int $targetPlan, int $object_id, int $expectedTemplateId): Plan
236
    {
237
        $result = Plan::perform('search-templates', [
238
            'id' => $targetPlan,
239
            'object_id' => $object_id,
240
        ]);
241
        $plans = ArrayHelper::index($result, 'id');
242
243
        if (!isset($plans[$expectedTemplateId])) {
244
            throw new NotFoundHttpException('Requested template plan not found');
245
        }
246
247
        $plan = Plan::instantiate($plans[$expectedTemplateId]);
248
        Plan::populateRecord($plan, $plans[$expectedTemplateId]);
249
250
        return $plan;
251
    }
252
253
    /**
254
     * @param $id integer
255
     * @throws NotFoundHttpException
256
     * @return Plan|null
257
     */
258
    private function findPlan(int $id): ?Plan
259
    {
260
        $plan = Plan::findOne(['id' => $id]);
261
        if ($plan === null) {
262
            throw new NotFoundHttpException('Not found');
263
        }
264
265
        return $plan;
266
    }
267
268
    /**
269
     * @param string $plan_id
270
     * @param string|null $object_id Object ID or `null`
271
     * when the desired templates are not related to a specific object
272
     * @param string $name_ilike
273
     * @return array
274
     */
275
    public function actionTemplates($plan_id, $object_id = null, string $name_ilike = null)
276
    {
277
        $templates = (new Plan())->query('search-templates', [
278
            'id' => $plan_id,
279
            'object_id' => $object_id ?? $plan_id,
280
            'name_ilike' => $name_ilike,
281
        ]);
282
283
        Yii::$app->response->format = Response::FORMAT_JSON;
284
285
        return $templates;
286
    }
287
288
    public function actionCalculateCharges()
289
    {
290
        Yii::$app->response->format = Response::FORMAT_JSON;
291
        $request = Yii::$app->request;
292
293
        $periods = ['now', 'first day of +1 month', 'first day of +1 year'];
294
        $calculations = Plan::perform('calculate-charges', [
295
            'actions' => $request->post('actions'),
296
            'prices' => $request->post('prices'),
297
            'times' => $periods,
298
        ]);
299
        /** @var PriceChargesEstimator $calculator */
300
        $calculator = Yii::$container->get(PriceChargesEstimator::class, [$calculations]);
301
302
        try {
303
            return $calculator->calculateForPeriods($periods);
304
        } catch (ResponseErrorException $exception) {
305
            Yii::$app->response->setStatusCode(412, $exception->getMessage());
306
307
            return [
308
                'formula' => $exception->getResponse()->getData()['_error_ops']['formula'] ?? null,
309
            ];
310
        }
311
    }
312
313
    public function actionCalculateValues($planId)
314
    {
315
        Yii::$app->response->format = Response::FORMAT_JSON;
316
        $periods = ['now', 'first day of +1 month', 'first day of +1 year'];
317
        try {
318
            $calculations = Plan::perform('calculate-values', ['id' => $planId, 'times' => $periods]);
319
            $calculator = Yii::$container->get(PriceChargesEstimator::class, [$calculations]);
320
321
            return $calculator->calculateForPeriods($periods);
322
        } catch (ResponseErrorException $exception) {
323
            Yii::$app->response->setStatusCode(412, $exception->getMessage());
324
325
            return [
326
                'formula' => $exception->getResponse()->getData()['_error_ops']['formula'] ?? null,
327
            ];
328
        }
329
    }
330
331
    public function actionUpdatePrices(int $id, string $scenario = 'update')
332
    {
333
        $plan = Plan::find()
334
            ->byId($id)
335
            ->withPrices()
336
            ->one();
337
338
        $request = Yii::$app->request;
339
        if ($request->isPost) {
340
            try {
341
                $collection = new PricesCollection($this->priceModelFactory, ['scenario' => $scenario]);
342
                $collection->load();
343
                if ($collection->save() === false) {
344
                    if ($scenario === 'create') {
345
                        Yii::$app->session->addFlash('error', Yii::t('hipanel.finance.price', 'Error occurred during creation of prices'));
346
                    } elseif ($scenario === 'update') {
347
                        Yii::$app->session->addFlash('error', Yii::t('hipanel.finance.price', 'Error occurred during prices update'));
348
                    }
349
                } else {
350
                    if ($scenario === 'create') {
351
                        Yii::$app->session->addFlash('success', Yii::t('hipanel.finance.price', 'Prices were successfully created'));
352
                    } elseif ($scenario === 'update') {
353
                        Yii::$app->session->addFlash('success', Yii::t('hipanel.finance.price', 'Prices were successfully updated'));
354
                    }
355
                }
356
357
                return $this->redirect(['@plan/view', 'id' => $id]);
358
            } catch (\Exception $e) {
359
                throw new UnprocessableEntityHttpException($e->getMessage(), 0, $e);
360
            }
361
        }
362
363
        $grouper = new PlanInternalsGrouper($plan);
0 ignored issues
show
$plan is of type object<hiqdev\hiart\ActiveRecord>|array|null, but the function expects a object<hipanel\modules\finance\models\Plan>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
364
        $parentPrices = $this->getParentPrices($id);
365
366
        return $this->render($plan->type . '/' . 'updatePrices',
367
            compact('plan', 'grouper', 'parentPrices'));
368
    }
369
370
    /**
371
     * @param int $plan_id
372
     * @return Price[]|null Array of parent plan prices or `null`, when parent plan was not found
373
     */
374
    private function getParentPrices(int $plan_id)
375
    {
376
        $plan = Plan::find()
377
            ->addAction('get-parent')
378
            ->where(['id' => $plan_id])
379
            ->joinWithPrices()
380
            ->one();
381
382
        if ($plan === null || $plan->id === null) {
383
            return null;
384
        }
385
386
        return (new PlanInternalsGrouper($plan))->group();
387
    }
388
389
    /**
390
     * @param Plan $plan
391
     * @param array $pricesData
392
     */
393
    private function populateWithPrices(Plan $plan, $pricesData): void
394
    {
395
        $prices = [];
396
        foreach ($pricesData as $priceData) {
397
            $object = ArrayHelper::remove($priceData, 'object');
398
            if (isset($priceData['plan_type']) &&
399
                $priceData['plan_type'] === 'certificate') {
400
                $priceData['class'] = 'CertificatePrice';
401
            }
402
403
            /** @var Price $price */
404
            $price = Price::instantiate($priceData);
405
            $price->setScenario('create');
406
            $price->setAttributes($priceData);
407
            $price->populateRelation('object', new TargetObject($object));
408
            $price->trigger(Price::EVENT_AFTER_FIND);
409
            $prices[] = $price;
410
        }
411
        $prices = PriceSort::anyPrices()->values($prices, true);
412
413
        $plan->populateRelation('prices', $prices);
414
    }
415
}
416