Completed
Pull Request — master (#366)
by Matthew
03:56
created

FoxyStripeController::getEncryption()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 14
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
eloc 11
dl 0
loc 14
ccs 0
cts 10
cp 0
rs 9.6111
c 0
b 0
f 0
cc 5
nc 5
nop 1
crap 30
1
<?php
2
3
namespace Dynamic\FoxyStripe\Controller;
4
5
use Dynamic\FoxyStripe\Model\FoxyCart;
6
use Dynamic\FoxyStripe\Model\FoxyStripeSetting;
7
use Dynamic\FoxyStripe\Model\OptionItem;
8
use Dynamic\FoxyStripe\Model\Order;
9
use Dynamic\FoxyStripe\Model\OrderDetail;
10
use Dynamic\FoxyStripe\Page\ProductPage;
11
use SilverStripe\Security\Member;
12
use SilverStripe\Security\Security;
13
14
class FoxyStripeController extends \PageController
15
{
16
    /**
17
     *
18
     */
19
    const URLSEGMENT = 'foxystripe';
20
    /**
21
     * @var array
22
     */
23
    private static $allowed_actions = array(
0 ignored issues
show
introduced by
The private property $allowed_actions is not used, and could be removed.
Loading history...
24
        'index',
25
        'sso',
26
    );
27
28
    /**
29
     * @return string
30
     */
31
    public function getURLSegment()
32
    {
33
        return self::URLSEGMENT;
34
    }
35
36
    /**
37
     * @return string
38
     *
39
     * @throws \SilverStripe\ORM\ValidationException
40
     */
41
    public function index()
42
    {
43
        // handle POST from FoxyCart API transaction
44
        if ((isset($_POST['FoxyData']) or isset($_POST['FoxySubscriptionData']))) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
45
            $FoxyData_encrypted = (isset($_POST['FoxyData'])) ?
46
                urldecode($_POST['FoxyData']) :
47
                urldecode($_POST['FoxySubscriptionData']);
48
            $FoxyData_decrypted = \rc4crypt::decrypt(FoxyCart::getStoreKey(), $FoxyData_encrypted);
0 ignored issues
show
Bug introduced by
It seems like Dynamic\FoxyStripe\Model\FoxyCart::getStoreKey() can also be of type false; however, parameter $pwd of rc4crypt::decrypt() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

48
            $FoxyData_decrypted = \rc4crypt::decrypt(/** @scrutinizer ignore-type */ FoxyCart::getStoreKey(), $FoxyData_encrypted);
Loading history...
49
50
            // parse the response and save the order
51
            self::handleDataFeed($FoxyData_encrypted, $FoxyData_decrypted);
0 ignored issues
show
Bug Best Practice introduced by
The method Dynamic\FoxyStripe\Contr...oller::handleDataFeed() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

51
            self::/** @scrutinizer ignore-call */ 
52
                  handleDataFeed($FoxyData_encrypted, $FoxyData_decrypted);
Loading history...
52
53
            // extend to allow for additional integrations with Datafeed
54
            $this->extend('addIntegrations', $FoxyData_encrypted);
55
56
            return 'foxy';
57
        } else {
58
            return 'No FoxyData or FoxySubscriptionData received.';
59
        }
60
    }
61
62
    /**
63
     * @param $encrypted
64
     * @param $decrypted
65
     *
66
     * @throws \SilverStripe\ORM\ValidationException
67
     */
68
    public function handleDataFeed($encrypted, $decrypted)
69
    {
70
        $orders = new \SimpleXMLElement($decrypted);
71
72
        // loop over each transaction to find FoxyCart Order ID
73
        foreach ($orders->transactions->transaction as $transaction) {
74
            // if FoxyCart order id, then parse order
75
            if (isset($transaction->id)) {
76
                ($order = Order::get()->filter('Order_ID', (int)$transaction->id)->First()) ?
0 ignored issues
show
Unused Code introduced by
The assignment to $order is dead and can be removed.
Loading history...
77
                    $order = Order::get()->filter('Order_ID', (int)$transaction->id)->First() :
78
                    $order = Order::create();
79
80
                // save base order info
81
                $order->Order_ID = (int)$transaction->id;
82
                $order->Response = urlencode($encrypted);
83
                $this->parseOrder($orders, $order);
0 ignored issues
show
Bug introduced by
$orders of type SimpleXMLElement is incompatible with the type array expected by parameter $transactions of Dynamic\FoxyStripe\Contr...ontroller::parseOrder(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

83
                $this->parseOrder(/** @scrutinizer ignore-type */ $orders, $order);
Loading history...
84
                $order->write();
85
            }
86
        }
87
    }
88
89
    /**
90
     * @param array $transactions
91
     * @param Order $order
92
     */
93
    public function parseOrder($transactions, $order)
94
    {
95
        $this->parseOrderInfo($transactions, $order);
96
        $this->parseOrderCustomer($transactions, $order);
97
        $this->parseOrderDetails($transactions, $order);
98
    }
99
100
    /**
101
     * @param array $orders
102
     * @param Order $transaction
103
     */
104
    public function parseOrderInfo($orders, $transaction)
105
    {
106
        foreach ($orders->transactions->transaction as $order) {
107
            // Record transaction data from FoxyCart Datafeed:
108
            $transaction->Store_ID = (int)$order->store_id;
0 ignored issues
show
Bug Best Practice introduced by
The property Store_ID does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
109
            $transaction->TransactionDate = (string)$order->transaction_date;
0 ignored issues
show
Documentation Bug introduced by
It seems like (string)$order->transaction_date of type string is incompatible with the declared type SilverStripe\ORM\FieldType\DBDatetime of property $TransactionDate.

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...
110
            $transaction->ProductTotal = (float)$order->product_total;
0 ignored issues
show
Documentation Bug introduced by
It seems like (double)$order->product_total of type double is incompatible with the declared type SilverStripe\ORM\FieldType\DBCurrency of property $ProductTotal.

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...
111
            $transaction->TaxTotal = (float)$order->tax_total;
0 ignored issues
show
Documentation Bug introduced by
It seems like (double)$order->tax_total of type double is incompatible with the declared type SilverStripe\ORM\FieldType\DBCurrency of property $TaxTotal.

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...
112
            $transaction->ShippingTotal = (float)$order->shipping_total;
0 ignored issues
show
Documentation Bug introduced by
It seems like (double)$order->shipping_total of type double is incompatible with the declared type SilverStripe\ORM\FieldType\DBCurrency of property $ShippingTotal.

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...
113
            $transaction->OrderTotal = (float)$order->order_total;
0 ignored issues
show
Documentation Bug introduced by
It seems like (double)$order->order_total of type double is incompatible with the declared type SilverStripe\ORM\FieldType\DBCurrency of property $OrderTotal.

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...
114
            $transaction->ReceiptURL = (string)$order->receipt_url;
0 ignored issues
show
Documentation Bug introduced by
It seems like (string)$order->receipt_url of type string is incompatible with the declared type SilverStripe\ORM\FieldType\DBVarchar of property $ReceiptURL.

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...
115
            $transaction->OrderStatus = (string)$order->status;
0 ignored issues
show
Documentation Bug introduced by
It seems like (string)$order->status of type string is incompatible with the declared type SilverStripe\ORM\FieldType\DBVarchar of property $OrderStatus.

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...
116
        }
117
    }
118
119
    /**
120
     * @param array $orders
121
     * @param Order $transaction
122
     * @throws \SilverStripe\ORM\ValidationException
123
     */
124
    public function parseOrderCustomer($orders, $transaction)
125
    {
126
        foreach ($orders->transactions->transaction as $order) {
127
            if (!isset($order->customer_email) || $order->is_anonymous != 0) {
128
                continue;
129
            }
130
131
            // if Customer is existing member, associate with current order
132
            if (Member::get()->filter('Email', $order->customer_email)->First()) {
133
                $customer = Member::get()->filter('Email', $order->customer_email)->First();
134
                /* todo: make sure local password is updated if changed on FoxyCart
135
                $this->updatePasswordFromData($customer, $order);
136
                */
137
            } else {
138
                // create new Member, set password info from FoxyCart
139
                $customer = Member::create();
140
                $customer->Customer_ID = (int)$order->customer_id;
141
                $customer->FirstName = (string)$order->customer_first_name;
142
                $customer->Surname = (string)$order->customer_last_name;
143
                $customer->Email = (string)$order->customer_email;
144
                $this->updatePasswordFromData($customer, $order);
145
            }
146
            $customer->write();
147
            // set Order MemberID
148
            $transaction->MemberID = $customer->ID;
149
        }
150
    }
151
152
    /**
153
     * Updates a customer's password. Sets password encryption to 'none' to avoid encryting it again.
154
     *
155
     * @param Member $customer
156
     * @param $order
157
     */
158
    public function updatePasswordFromData($customer, $order)
159
    {
160
        $password_encryption_algorithm = Security::config()->get('password_encryption_algorithm');
161
        Security::config()->update('password_encryption_algorithm', 'none');
162
163
        $customer->PasswordEncryption = $this->getEncryption($order->customer_password_hash_type);
164
        $customer->Password = (string) $order->customer_password;
165
        $customer->Salt = (string) $order->customer_password_salt;
166
167
        Security::config()->update('password_encryption_algorithm', $password_encryption_algorithm);
168
    }
169
170
    /**
171
     * @param string $hashType
172
     * @return string
173
     */
174
    private function getEncryption($hashType)
175
    {
176
        // TODO - update this with new/correct types
177
        switch (true) {
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing stristr($hashType, 'sha1') of type string to the boolean true. If you are specifically checking for a non-empty string, consider using the more explicit !== '' instead.
Loading history...
Bug Best Practice introduced by
It seems like you are loosely comparing stristr($hashType, 'md5') of type string to the boolean true. If you are specifically checking for a non-empty string, consider using the more explicit !== '' instead.
Loading history...
Bug Best Practice introduced by
It seems like you are loosely comparing stristr($hashType, 'bcrypt') of type string to the boolean true. If you are specifically checking for a non-empty string, consider using the more explicit !== '' instead.
Loading history...
Bug Best Practice introduced by
It seems like you are loosely comparing stristr($hashType, 'sha256') of type string to the boolean true. If you are specifically checking for a non-empty string, consider using the more explicit !== '' instead.
Loading history...
178
            case stristr($hashType, 'sha1'):
179
                return 'sha1_v2.4';
180
            case stristr($hashType, 'sha256'):
181
                return 'sha256';
182
            case stristr($hashType, 'md5'):
183
                return 'md5';
184
            case stristr($hashType, 'bcrypt'):
185
                return 'bcrypt';
186
            default:
187
                return 'none';
188
        }
189
    }
190
191
    /**
192
     * @param array $orders
193
     * @param Order $transaction
194
     */
195
    public function parseOrderDetails($orders, $transaction)
196
    {
197
        // remove previous OrderDetails so we don't end up with duplicates
198
        foreach ($transaction->Details() as $detail) {
199
            $detail->delete();
200
        }
201
202
        foreach ($orders->transactions->transaction as $order) {
203
            // Associate ProductPages, Options, Quanity with Order
204
            foreach ($order->transaction_details->transaction_detail as $product) {
205
                $this->orderDetailFromProduct($product, $transaction);
206
            }
207
        }
208
    }
209
210
    /**
211
     * @param $product
212
     * @param $transaction
213
     */
214
    public function orderDetailFromProduct($product, $transaction)
215
    {
216
        $OrderDetail = OrderDetail::create();
217
        $OrderDetail->Quantity = (int)$product->product_quantity;
218
        $OrderDetail->Price = (float)$product->product_price;
219
        // Find product via product_id custom variable
220
221
        foreach ($this->getTransactionOptions($product) as $productID) {
222
            $productPage = $this->getProductPage($product);
223
            $this->modifyOrderDetailPrice($productPage, $OrderDetail, $product);
224
            // associate with this order
225
            $OrderDetail->OrderID = $transaction->ID;
226
            // extend OrderDetail parsing, allowing for recording custom fields from FoxyCart
227
            $this->extend('handleOrderItem', $decrypted, $product, $OrderDetail);
228
            // write
229
            $OrderDetail->write();
230
        }
231
    }
232
233
    /**
234
     * @param $product
235
     * @return \Generator
236
     */
237
    public function getTransactionOptions($product)
238
    {
239
        foreach ($product->transaction_detail_options->transaction_detail_option as $productOption) {
240
            yield $productOption;
241
        }
242
    }
243
244
    /**
245
     * @param $product
246
     * @return bool|ProductPage
247
     */
248
    public function getProductPage($product)
249
    {
250
        foreach ($this->getTransactionOptions($product) as $productOptions) {
251
            if ($productOptions->product_option_name != 'product_id') {
252
                continue;
253
            }
254
255
            return ProductPage::get()
256
                ->filter('ID', (int) $productOptions->product_option_value)
257
                ->First();
258
        }
259
    }
260
261
    /**
262
     * @param bool|ProductPage $OrderProduct
263
     * @param OrderDetail $OrderDetail
264
     */
265
    public function modifyOrderDetailPrice($OrderProduct, $OrderDetail, $product)
266
    {
267
        if (!$OrderProduct) {
268
            return;
269
        }
270
271
        $OrderDetail->ProductID = $OrderProduct->ID;
272
273
        foreach ($this->getTransactionOptions($product) as $option) {
274
            $OptionItem = OptionItem::get()->filter(array(
275
                'ProductID' => (string)$OrderProduct->ID,
276
                'Title' => (string)$option->product_option_value
277
            ))->First();
278
279
            if (!$OptionItem) {
280
                continue;
281
            }
282
283
            $OrderDetail->OptionItems()->add($OptionItem);
284
            // modify product price
285
            if ($priceMod = $option->price_mod) {
286
                $OrderDetail->Price += $priceMod;
287
            }
288
        }
289
    }
290
291
    /**
292
     * Single Sign on integration with FoxyCart.
293
     */
294
    public function sso()
295
    {
296
297
        // GET variables from FoxyCart Request
298
        $fcsid = $this->request->getVar('fcsid');
299
        $timestampNew = strtotime('+30 days');
300
301
        // get current member if logged in. If not, create a 'fake' user with Customer_ID = 0
302
        // fake user will redirect to FC checkout, ask customer to log in
303
        // to do: consider a login/registration form here if not logged in
304
        if ($Member = Security::getCurrentUser()) {
0 ignored issues
show
Unused Code introduced by
The assignment to $Member is dead and can be removed.
Loading history...
305
            $Member = Security::getCurrentUser();
306
        } else {
307
            $Member = new Member();
308
            $Member->Customer_ID = 0;
309
        }
310
311
        $auth_token = sha1($Member->Customer_ID . '|' . $timestampNew . '|' . FoxyCart::getStoreKey());
0 ignored issues
show
Bug introduced by
Are you sure Dynamic\FoxyStripe\Model\FoxyCart::getStoreKey() of type SilverStripe\ORM\FieldType\DBVarchar|false can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

311
        $auth_token = sha1($Member->Customer_ID . '|' . $timestampNew . '|' . /** @scrutinizer ignore-type */ FoxyCart::getStoreKey());
Loading history...
312
313
        $config = FoxyStripeSetting::current_foxystripe_setting();
314
        if ($config->CustomSSL) {
0 ignored issues
show
Bug Best Practice introduced by
The property CustomSSL does not exist on Dynamic\FoxyStripe\Model\FoxyStripeSetting. Since you implemented __get, consider adding a @property annotation.
Loading history...
315
            $link = FoxyCart::getFoxyCartStoreName();
316
        } else {
317
            $link = FoxyCart::getFoxyCartStoreName() . '.foxycart.com';
318
        }
319
320
        $redirect_complete = 'https://'.$link.'/checkout?fc_auth_token='.$auth_token.'&fcsid='.$fcsid.
321
            '&fc_customer_id='.$Member->Customer_ID.'&timestamp='.$timestampNew;
322
323
        $this->redirect($redirect_complete);
324
    }
325
}
326