Completed
Push — master ( ef25a3...6ed45b )
by Nicolaas
01:49
created

OrderStatusLog_SecurityCheck::canEdit()   B

Complexity

Conditions 5
Paths 3

Size

Total Lines 14
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 14
rs 8.8571
c 0
b 0
f 0
cc 5
eloc 10
nc 3
nop 1
1
<?php
2
3
4
/**
5
 * @authors: Nicolaas [at] Sunny Side Up .co.nz
6
 * @package: ecommerce
7
 * @sub-package: model
8
 * @inspiration: Silverstripe Ltd, Jeremy
9
 **/
10
class OrderStatusLog_SecurityCheck extends OrderStatusLog
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
11
{
12
    private static $days_ago_to_check = 14;
0 ignored issues
show
Unused Code introduced by
The property $days_ago_to_check is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
13
14
    private static $db = array(
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
Unused Code introduced by
The property $db is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
15
        'Bad' => 'Boolean',
16
        'Risks' => 'HTMLText',
17
        'SubTotal' => 'Currency',
18
        'Check1' => 'Enum("To do, Done, Whitelisted Customer", "To do" )',
19
        'Check2' => 'Enum("To do, Done, Whitelisted Customer", "To do" )',
20
        'Check3' => 'Enum("To do, Done, Whitelisted Customer", "To do" )',
21
        'Check4' => 'Enum("To do, Done, Whitelisted Customer", "To do" )',
22
        'Check5' => 'Enum("To do, Done, Whitelisted Customer", "To do" )',
23
        'Check6' => 'Enum("To do, Done, Whitelisted Customer", "To do" )',
24
        'Check7' => 'Enum("To do, Done, Whitelisted Customer", "To do" )',
25
        'Check8' => 'Enum("To do, Done, Whitelisted Customer", "To do" )',
26
        'Check9' => 'Enum("To do, Done, Whitelisted Customer", "To do" )',
27
        'Check10' => 'Enum("To do, Done, Whitelisted Customer", "To do" )',
28
        'Check11' => 'Enum("To do, Done, Whitelisted Customer", "To do" )',
29
        'Check12' => 'Enum("To do, Done, Whitelisted Customer", "To do" )',
30
    );
31
32
    private static $many_many = array(
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
Unused Code introduced by
The property $many_many is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
33
        'BlacklistItems' => 'EcommerceSecurityBaseClass'
34
    );
35
36
    /**
37
     *  this array works as follows
38
     *      array(
39
     *          Check1 => array(
40
     *              "Title" => "Customer Has Paid",
41
     *              "MinSubTotal" => 10,
42
     *              "Explanation" => "Check Payment system for $$$ coming in"
43
     *          ),
44
     *          Check2 => array(
45
     *              "Title" => "Address Exists",
46
     *              "MinSubTotal" => 50,
47
     *              "Explanation" => "Check Payment system for $$$ coming in"
48
     *          )
49
     *
50
     * @var array
51
     */
52
    private static $checks_required = array();
0 ignored issues
show
Unused Code introduced by
The property $checks_required is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
53
54
    private static $summary_fields = array(
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
Unused Code introduced by
The property $summary_fields is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
55
        'Type' => 'Type',
56
        'SubTotal' => 'SubTotal',
57
        'SecurityCleared' => 'Security Cleared'
58
    );
59
60
    private static $casting = array(
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
Unused Code introduced by
The property $casting is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
61
        'SecurityCleared' => 'Boolean'
62
    );
63
64
    private static $defaults = array(
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
Unused Code introduced by
The property $defaults is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
65
        'InternalUseOnly' => true
66
    );
67
68
    private static $field_labels = array(
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
Unused Code introduced by
The property $field_labels is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
69
        'Bad' => 'Fraudulent',
70
        'Title' => 'Value'
71
    );
72
73
    private static $singular_name = 'Security Check';
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
74
    public function i18n_singular_name()
75
    {
76
        return self::$singular_name;
77
    }
78
79
    private static $plural_name = 'Security Checks';
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
80
    public function i18n_plural_name()
81
    {
82
        return self::$plural_name;
83
    }
84
85
    public function canCreate($member = null)
86
    {
87
        return false;
88
    }
89
90
    public function canEdit($member = null)
91
    {
92
        $order = $this->Order();
0 ignored issues
show
Documentation Bug introduced by
The method Order does not exist on object<OrderStatusLog_SecurityCheck>? 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...
93
        if ($order && $order->exists()) {
94
            $status = $order->MyStep();
95
            if($status && $status->Code == 'SECURITY_CHECK') {
96
                return parent::canEdit($member);
97
            } else {
98
                return false;
99
            }
100
        } else {
101
            return parent::canEdit($member);
102
        }
103
    }
104
105
    /**
106
     * CMS Fields
107
     * @return FieldList
108
     */
109
    public function getCMSFields()
110
    {
111
        $order = $this->Order();
0 ignored issues
show
Documentation Bug introduced by
The method Order does not exist on object<OrderStatusLog_SecurityCheck>? 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...
112
        if ($order) {
113
            $member = $this->orderMember();
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $member is correct as $this->orderMember() (which targets OrderStatusLog_SecurityCheck::orderMember()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
114
            $fields = parent::getCMSFields();
115
            $fields->addFieldToTab(
116
                'Root.Main',
117
                HeaderField::create(
118
                    'BadHeading',
119
                    'Mark as Fraud'
120
                ),
121
                'Bad'
122
            );
123
            $fields->addFieldToTab(
124
                'Root.MoreDetails',
125
                HTMLEditorField::create(
126
                    'Note',
127
                    'Notes'
128
                )
129
            );
130
            $fields->addFieldToTab(
131
                'Root.Main',
132
                HeaderField::create(
133
                    'BadHeading',
134
                    'Risks'
135
                ),
136
                'Risks'
137
            );
138
            $riskField = $fields->dataFieldByName('Risks');
139
            $riskField->setTitle('');
140
            if ($member) {
141
                $previousOrders = Order::get()
142
                    ->filter(
143
                        array(
144
                            'MemberID' => $member->ID
145
                        )
146
                    )
147
                    ->exclude(
148
                        array('ID' => $order->ID)
149
                    );
150
                if ($previousOrders->count()) {
151
                    $fields->addFieldToTab(
152
                        "Root.PreviousOrders",
153
                        new GridField(
154
                            'PreviousOrdersList',
155
                            'Previous Orders',
156
                            $previousOrders
157
                        )
158
                    );
159
                } else {
160
                    $fields->addFieldToTab(
161
                        "Root.PreviousOrders",
162
                        HeaderField::create(
163
                            'NoPreviousOrders',
164
                            'This customer does not have any previous orders'
165
                        )
166
                    );
167
                }
168
            }
169
        }
170
        $allFields = array();
171
        for ($i = 1; $i < 13; $i++) {
172
            $allFields["Check".$i] = "Check".$i;
173
        }
174
        $checks = $this->Config()->get('checks_required');
175
        $fields->addFieldToTab(
0 ignored issues
show
Bug introduced by
The variable $fields does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
176
            "Root.Required",
177
            HeaderField::create('RequiredChecksHeader', 'Required Checks'),
178
            'Note'
179
        );
180
        $fields->addFieldToTab(
181
            "Root.NotRequired",
182
            HeaderField::create('UnrequiredChecksHeader', 'Optional Checks'),
183
            'Note'
184
        );
185
        $hasRequiredChecks = false;
186
        $hasUnrequiredChecks = false;
187
        $memberIsWhitelisted = $this->memberIsWhitelisted();
188
        foreach ($checks as $fieldName => $details) {
189
            unset($allFields[$fieldName]);
190
            if (floatval($this->SubTotal) > floatval($details['SubTotalMin'])) {
0 ignored issues
show
Documentation introduced by
The property SubTotal does not exist on object<OrderStatusLog_SecurityCheck>. 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...
191
                $hasRequiredChecks = true;
192
                $fields->addFieldToTab(
193
                    'Root.Required',
194
                    $myField = $fields->dataFieldByName($fieldName)
195
                );
196
            } else {
197
                $hasUnrequiredChecks = true;
198
                $fields->addFieldToTab(
199
                    'Root.NotRequired',
200
                    $myField = $fields->dataFieldByName($fieldName)
201
                );
202
            }
203
            $originalOptions = $myField->getSource();
204
            if ($memberIsWhitelisted) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
205
                //..
206
            } else {
207
                unset($originalOptions['Whitelisted Customer']);
208
            }
209
            if (! $this->$fieldName) {
210
                $this->$fieldName = 'To do';
211
            }
212
            $fields->replaceField(
213
                $myField->ID(),
0 ignored issues
show
Bug introduced by
It seems like $myField->ID() targeting FormField::ID() can also be of type array; however, FieldList::replaceField() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
214
                OptionsetField::create(
215
                    $myField->ID(),
216
                    $details['Title'],
217
                    $originalOptions
218
                )
219
            );
220
            if (! empty($details['Description'])) {
221
                $myField->setRighTitle($details['Description']);
0 ignored issues
show
Bug introduced by
The method setRighTitle() does not exist on FormField. Did you maybe mean setRightTitle()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
222
            }
223
        }
224
        foreach ($allFields as $fieldToRemove) {
225
            $fields->removeByName($fieldToRemove);
226
        }
227
        if (! $hasUnrequiredChecks) {
228
            $fields->addFieldToTab(
229
                "Root.NotRequired",
230
                HeaderField::create('UnrequiredChecksHeader', 'There are no optional checks for this order.'),
231
                'Note'
232
            );
233
        }
234
        if (! $hasRequiredChecks) {
235
            $fields->addFieldToTab(
236
                "Root.Required",
237
                HeaderField::create('RequiredChecksHeader', 'There are no required checks for this order.'),
238
                'Note'
239
            );
240
        }
241
        $fields->removeFieldFromTab('Root.Main', 'AuthorID');
242
        $fields->removeFieldFromTab('Root.Main', 'Title');
243
        $fields->removeFieldFromTab('Root.Main', 'InternalUseOnly');
244
        $fields->makeFieldReadonly('Risks');
245
        $fields->makeFieldReadonly('SubTotal');
246
        return $fields;
247
    }
248
249
    protected $warningMessages = array();
250
251
    protected function collateRisks()
252
    {
253
        $order = $this->Order();
0 ignored issues
show
Documentation Bug introduced by
The method Order does not exist on object<OrderStatusLog_SecurityCheck>? 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...
254
        $billingAddress = $order->BillingAddress();
255
        $shippingAddress = $order->ShippingAddress();
256
        $member = $this->orderMember();
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $member is correct as $this->orderMember() (which targets OrderStatusLog_SecurityCheck::orderMember()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
257
        $payments = $order->Payments();
258
        $html = '';
259
260
        $similarArray = array();
261
262
        $daysAgo = $this->Config()->get('days_ago_to_check');
263
        $timeFilter = array('Created:GreaterThan' => date('Y-m-d', strtotime('-'.$daysAgo.' days')).' 00:00:00');
264
265
266
        //check emails from user
267
        $emailArray = array();
268
        if ($member) {
269
            if ($member->Email) {
270
                $emailArray[] = $member->Email;
271
                if(OrderStatusLog_WhitelistCustomer::member_is_security_risk($member)) {
272
                    $html .= '<p class="message bad">This customer has been marked as a security risk.</p>';
273
                } else {
274
                    if (OrderStatusLog_WhitelistCustomer::member_is_whitelisted($member)) {
275
                        $html .= '<p class="warning good">This customer is whitelisted.</p>';
276
                    } else {
277
                        $html .= '<p class="message warning">This customer is NOT whitelisted.</p>';
278
                    }
279
                }
280
            }
281
        }
282
        //are there any orders with the same Member.email in the last seven days...
283
        $otherOrders = Order::get_datalist_of_orders_with_submit_record()
284
            ->filter(
285
                array_merge(
286
                    array('MemberID' => $member->ID),
287
                    $timeFilter
288
                )
289
            )
290
            ->exclude(array('ID' => $order->ID));
291 View Code Duplication
        foreach ($otherOrders as $otherOrder) {
0 ignored issues
show
Duplication introduced by
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...
292
            if (!isset($similarArray[$otherOrder->ID])) {
293
                $similarArray[$otherOrder->ID] = array();
294
            }
295
            $similarArray[$otherOrder->ID]["Email"] = $otherOrder;
296
        }
297
        //check emails from billing address
298
        $emailArray = array();
299
        if ($billingAddress) {
300
            if ($billingAddress->Email) {
301
                $emailArray[] = $billingAddress->Email;
302
            }
303
        }
304
        //are there any orders with the same Billing.Email in the last seven days...
305
        $otherBillingAddresses = BillingAddress::get()->filter(
306
            array('Email' => $emailArray) + $timeFilter
307
        )->exclude(array('OrderID' => $order->ID));
308 View Code Duplication
        foreach ($otherBillingAddresses as $address) {
0 ignored issues
show
Duplication introduced by
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...
309
            $otherOrder = $address->Order();
310
            if (!isset($similarArray[$otherOrder->ID])) {
311
                $similarArray[$otherOrder->ID] = array();
312
            }
313
            $similarArray[$otherOrder->ID]["Email"] = $otherOrder;
314
        }
315
        //adding all emails to security checks
316
        $this->blacklistCheck($emailArray, 'EcommerceSecurityEmail');
317
318
319
        //phones
320
        $phoneArray = array();
321
        if ($billingAddress) {
322
            if ($billingAddress->Phone) {
323
                $phoneArray[] = $billingAddress->Phone;
324
            }
325
        }
326
        if ($shippingAddress) {
327
            if ($shippingAddress->ShippingPhone) {
328
                $phoneArray[] = $shippingAddress->ShippingPhone;
329
            }
330
        }
331
        //are there any orders with the same phone in the last xxx days...
332
        $otherBillingAddresses = BillingAddress::get()->filter(
333
            array('Phone' => $phoneArray) + $timeFilter
334
        )->exclude(array('OrderID' => $order->ID));
335 View Code Duplication
        foreach ($otherBillingAddresses as $address) {
0 ignored issues
show
Duplication introduced by
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...
336
            $otherOrder = $address->Order();
337
            if ($otherOrder && $otherOrder->ID != $order->ID) {
338
                if (!isset($similarArray[$otherOrder->ID])) {
339
                    $similarArray[$otherOrder->ID] = array();
340
                }
341
                $similarArray[$otherOrder->ID]["Phone"] = $otherOrder;
342
            }
343
        }
344
        $otherShippingAddresses = ShippingAddress::get()->filter(
345
            array('ShippingPhone' => $phoneArray) + $timeFilter
346
        )->exclude(array('OrderID' => $order->ID));
347 View Code Duplication
        foreach ($otherShippingAddresses as $address) {
0 ignored issues
show
Duplication introduced by
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...
348
            $otherOrder = $address->Order();
349
            if ($otherOrder && $otherOrder->ID != $order->ID) {
350
                if (!isset($similarArray[$otherOrder->ID])) {
351
                    $similarArray[$otherOrder->ID] = array();
352
                }
353
                $similarArray[$otherOrder->ID]["Phone"] = $otherOrder;
354
            }
355
        }
356
        //adding all emails to security checks
357
        $this->blacklistCheck($phoneArray, 'EcommerceSecurityPhone');
358
359
        //addresses
360
        $addressArray = array();
361
        if ($billingAddress) {
362
            if ($billingAddress->Address) {
363
                $addressArray[] = $billingAddress->Address;
364
            }
365
        }
366
        if ($shippingAddress) {
367
            if ($shippingAddress->ShippingAddress) {
368
                $addressArray[] = $shippingAddress->ShippingAddress;
369
            }
370
        }
371
        //are there any orders with the same address in the last xxx days...
372
        $otherBillingAddresses = BillingAddress::get()->filter(
373
            array('Address' => $addressArray) + $timeFilter
374
        )->exclude(array('OrderID' => $order->ID));
375 View Code Duplication
        foreach ($otherBillingAddresses as $address) {
0 ignored issues
show
Duplication introduced by
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...
376
            $otherOrder = $address->Order();
377
            if ($otherOrder && $otherOrder->ID != $order->ID) {
378
                if (!isset($similarArray[$otherOrder->ID])) {
379
                    $similarArray[$otherOrder->ID] = array();
380
                }
381
                $similarArray[$otherOrder->ID]["Address"] = $otherOrder;
382
            }
383
        }
384
        $otherShippingAddresses = ShippingAddress::get()
385
            ->filter(
386
                array('ShippingAddress' => $addressArray) + $timeFilter
387
            )
388
            ->exclude(array('OrderID' => $order->ID));
389 View Code Duplication
        foreach ($otherShippingAddresses as $address) {
0 ignored issues
show
Duplication introduced by
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...
390
            $otherOrder = $address->Order();
391
            if ($otherOrder && $otherOrder->ID != $order->ID) {
392
                if (!isset($similarArray[$otherOrder->ID])) {
393
                    $similarArray[$otherOrder->ID] = array();
394
                }
395
                $similarArray[$otherOrder->ID]["Address"] = $otherOrder;
396
            }
397
        }
398
        $this->blacklistCheck($addressArray, 'EcommerceSecurityAddress');
399
400
401
        //IP
402
        $ipArray = array();
403
        $ipProxyArray = array();
404
        if ($payments) {
405
            foreach ($payments as $payment) {
406
                if(strlen($payment->IP) > 10) {
407
                    $ipArray[] = $payment->IP;
408
                }
409
                if(strlen($payment->ProxyIP) > 10) {
410
                    $ipProxyArray[] = $payment->ProxyIP;
411
                }
412
            }
413
        }
414 View Code Duplication
        if(count($ipArray)) {
0 ignored issues
show
Duplication introduced by
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...
415
            //are there any orders with the same IP in the xxx seven days...
416
            $otherPayments = EcommercePayment::get()->filter(
417
                array('IP' => $ipArray) + $timeFilter
418
            )->exclude(array('OrderID' => $order->ID));
419
            foreach ($otherPayments as $payment) {
420
                $otherOrder = $payment->Order();
421
                if (!isset($similarArray[$otherOrder->ID])) {
422
                    $similarArray[$otherOrder->ID] = array();
423
                }
424
                $similarArray[$otherOrder->ID]["IP"] = $otherOrder;
425
            }
426
            $this->blacklistCheck($ipArray, 'EcommerceSecurityIP');
427
        }
428 View Code Duplication
        if(count($ipProxyArray)) {
0 ignored issues
show
Duplication introduced by
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...
429
            //are there any orders with the same Proxy in the xxx seven days...
430
            $otherPayments = EcommercePayment::get()->filter(
431
                array('ProxyIP' => $ipProxyArray) + $timeFilter
432
            )->exclude(array('OrderID' => $order->ID));
433
            foreach ($otherPayments as $payment) {
434
                $otherOrder = $payment->Order();
435
                if (!isset($similarArray[$otherOrder->ID])) {
436
                    $similarArray[$otherOrder->ID] = array();
437
                }
438
                $similarArray[$otherOrder->ID]["ProxyIP"] = $otherOrder;
439
            }
440
            $this->blacklistCheck($ipProxyArray, 'EcommerceSecurityProxyIP');
441
        }
442
443
444
        if (count($this->warningMessages)) {
445
            $html .= '<h4 style="color: red;">Blacklisted Details</h4><ul class="SecurityCheckListOfRisks warnings" style="color: red;">';
446
            foreach ($this->warningMessages as $warningMessage) {
447
                $html .= $warningMessage;
448
            }
449
            $html .= '</ul>';
450
        } else {
451
            $html .= '<p class="message good">No Blacklisted Data Present</p>';
452
        }
453
        if (count($similarArray)) {
454
            $days = $this->Config()->get('days_ago_to_check');
455
            $html .= '<h4>Similar orders in the last '.$days.' days</h4><ul class="SecurityCheckListOfRisks otherRisks">';
456
            foreach ($similarArray as $orderID => $fields) {
457
                //we just loop this so we can get the order ...
458
                foreach ($fields as $tempOrder) {
459
                    break;
460
                }
461
                $html .= '<li><a href="'.$tempOrder->CMSEditLink().'">'.$tempOrder->getTitle().'</a>: with same '.implode(', and with same ', array_keys($fields)).'</li>';
0 ignored issues
show
Bug introduced by
The variable $tempOrder seems to be defined by a foreach iteration on line 458. Are you sure the iterator is never empty, otherwise this variable is not defined?

It seems like you are relying on a variable being defined by an iteration:

foreach ($a as $b) {
}

// $b is defined here only if $a has elements, for example if $a is array()
// then $b would not be defined here. To avoid that, we recommend to set a
// default value for $b.


// Better
$b = 0; // or whatever default makes sense in your context
foreach ($a as $b) {
}

// $b is now guaranteed to be defined here.
Loading history...
462
            }
463
            $html .= '</ul>';
464
        } else {
465
            $html .= '<p class="message good">No similar orders in the last '.$daysAgo.' days</p>';
466
        }
467
468
        return $html;
469
    }
470
471
    public function getSecurityCleared()
472
    {
473
        return  DBField::create_field('Boolean', ($this->pass() ? true : false));
474
    }
475
476
    /**
477
     *
478
     *
479
     *
480
     * @param  Order $order
0 ignored issues
show
Bug introduced by
There is no parameter named $order. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
481
     * @return bool
482
     */
483
    public function pass()
484
    {
485
        $order = $this->Order();
0 ignored issues
show
Documentation Bug introduced by
The method Order does not exist on object<OrderStatusLog_SecurityCheck>? 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...
486
        if (! $order) {
487
            return false;
488
        }
489
        $checks = $this->Config()->get('checks_required');
490
        $fieldsAvailable = $this->stat('db');
491
        foreach ($checks as $fieldName => $fieldDetails) {
492
            if (floatval($this->SubTotal) > floatval($fieldDetails['SubTotalMin'])) {
0 ignored issues
show
Documentation introduced by
The property SubTotal does not exist on object<OrderStatusLog_SecurityCheck>. 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...
493
                if (! isset($fieldsAvailable[$fieldName])) {
494
                    user_error('bad field  ....');
495
                }
496
                // there is a check that needs to be TRUE, but is not ...
497
                if ($this->$fieldName == 'Done' || $this->$fieldName == 'Whitelisted Customer') {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
498
                } else {
499
                    return false;
500
                }
501
            }
502
        }
503
        return true;
504
    }
505
506
    private static $_saved_already = 0;
507
508
    public function onAfterWrite()
509
    {
510
        parent::onAfterWrite();
511
        $order = $this->Order();
0 ignored issues
show
Documentation Bug introduced by
The method Order does not exist on object<OrderStatusLog_SecurityCheck>? 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...
512
        if (self::$_saved_already < 3) {
513
            self::$_saved_already++;
514
            if ($order && $order->exists()) {
515
                $this->SubTotal = $order->getSubTotal();
0 ignored issues
show
Documentation introduced by
The property SubTotal does not exist on object<OrderStatusLog_SecurityCheck>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write 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.");
        }
    }

}

Since the property has write access only, you can use the @property-write 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...
516
                $this->Risks = $this->collateRisks();
0 ignored issues
show
Documentation introduced by
The property Risks does not exist on object<OrderStatusLog_SecurityCheck>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write 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.");
        }
    }

}

Since the property has write access only, you can use the @property-write 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...
517
                $this->write();
518
            } else {
519
                $this->SubTotal = 9999;
0 ignored issues
show
Documentation introduced by
The property SubTotal does not exist on object<OrderStatusLog_SecurityCheck>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write 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.");
        }
    }

}

Since the property has write access only, you can use the @property-write 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...
520
                $this->Risks = "Error";
0 ignored issues
show
Documentation introduced by
The property Risks does not exist on object<OrderStatusLog_SecurityCheck>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write 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.");
        }
    }

}

Since the property has write access only, you can use the @property-write 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...
521
                $this->write();
522
            }
523
            if($this->memberIsWhitelisted()) {
524
                for ($i = 1; $i < 13; $i++) {
525
                    $field = "Check".$i;
526
                    $this->$field = 'Whitelisted Customer';
527
                }
528
                $this->write();
529
            }
530
        }
531
        if($this->Bad) {
0 ignored issues
show
Documentation introduced by
The property Bad does not exist on object<OrderStatusLog_SecurityCheck>. 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...
532
            foreach($this->BlacklistItems() as $blacklistItem) {
0 ignored issues
show
Documentation Bug introduced by
The method BlacklistItems does not exist on object<OrderStatusLog_SecurityCheck>? 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...
533
                $blacklistItem->Status = 'Bad';
534
                $blacklistItem->write();
535
            }
536
            if ($order && $order->exists()) {
537
                $order->Archive(true);
538
            }
539
            if($member = $this->orderMember()) {
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $member is correct as $this->orderMember() (which targets OrderStatusLog_SecurityCheck::orderMember()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
540
                $member->IsWhitelisted = false;
541
                $member->IsSecurityRisk = true;
542
                $member->write();
543
            }
544
        }
545
    }
546
547
    /**
548
     *
549
     * @param  EcommerceSecurityBaseClass $obj
550
     * @return bool                             return true if the status of the object is `Bad`
551
     */
552
    protected function checkSecurityObject($obj)
553
    {
554
        if ($obj->Status == 'Bad') {
0 ignored issues
show
Documentation introduced by
The property Status does not exist on object<EcommerceSecurityBaseClass>. 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...
Unused Code introduced by
This if statement, and the following return statement can be replaced with return !($obj->Status == 'Bad');.
Loading history...
555
            return false;
556
        }
557
        return true;
558
    }
559
560
    /**
561
     * caching variable only...
562
     *
563
     * @var null | bool
564
     */
565
    private $_memberIsWhitelisted = null;
566
567
    protected function memberIsWhitelisted()
568
    {
569
        if ($this->_memberIsWhitelisted  === null) {
570
            if($member = $this->orderMember()) {
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $member is correct as $this->orderMember() (which targets OrderStatusLog_SecurityCheck::orderMember()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
571
                $this->_memberIsWhitelisted = OrderStatusLog_WhitelistCustomer::member_is_whitelisted($member);
0 ignored issues
show
Documentation Bug introduced by
It seems like \OrderStatusLog_Whitelis...is_whitelisted($member) of type boolean is incompatible with the declared type null of property $_memberIsWhitelisted.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
572
            }
573
        }
574
        return $this->_memberIsWhitelisted;
575
    }
576
577
    /**
578
     *
579
     * @return null | Member
580
     */
581
    protected function orderMember()
582
    {
583
        $order = $this->Order();
0 ignored issues
show
Documentation Bug introduced by
The method Order does not exist on object<OrderStatusLog_SecurityCheck>? 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...
584
        if ($order && $order->exists()) {
585
            $member = $order->Member();
586
            if ($member && $member->exists()) {
587
                return $member;
588
            }
589
        }
590
    }
591
592
    protected function blacklistCheck($arrayOfValues, $securityClass)
593
    {
594
        //adding all emails to security checks
595
        foreach ($arrayOfValues as $value) {
596
            if ($value) {
597
                $obj = $securityClass::find_or_create(array("Title" => $value));
598
                if($obj->exists()) {
599
                    $this->BlacklistItems()->add($obj);
0 ignored issues
show
Documentation Bug introduced by
The method BlacklistItems does not exist on object<OrderStatusLog_SecurityCheck>? 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...
600
                    if ($obj->hasRisks()) {
601
                        $title = $obj->i18n_singular_name();
602
                        $message = '<li><strong>'.$title.':</strong> '.$value.'<li>';
603
                        $this->warningMessages[$message] = $message;
604
                    }
605
                }
606
            }
607
        }
608
609
    }
610
611
}
612