Completed
Push — master ( 26bb40...982e02 )
by Marcus
02:00
created

Shoppingcart::doCheckout()   D

Complexity

Conditions 10
Paths 6

Size

Total Lines 38
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 6
Bugs 0 Features 1
Metric Value
c 6
b 0
f 1
dl 0
loc 38
rs 4.8196
cc 10
eloc 26
nc 6
nop 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/*
4
    HCSF - A multilingual CMS and Shopsystem
5
    Copyright (C) 2014  Marcus Haase - [email protected]
6
7
    This program is free software: you can redistribute it and/or modify
8
    it under the terms of the GNU General Public License as published by
9
    the Free Software Foundation, either version 3 of the License, or
10
    (at your option) any later version.
11
12
    This program is distributed in the hope that it will be useful,
13
    but WITHOUT ANY WARRANTY; without even the implied warranty of
14
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
    GNU General Public License for more details.
16
17
    You should have received a copy of the GNU General Public License
18
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19
 */
20
21
namespace HaaseIT\HCSF\Controller\Shop;
22
23
use HaaseIT\HCSF\HelperConfig;
24
use HaaseIT\Toolbox\Tools;
25
use HaaseIT\HCSF\Helper;
26
use HaaseIT\HCSF\Customer\Helper as CHelper;
27
use HaaseIT\HCSF\Shop\Helper as SHelper;
28
29
class Shoppingcart extends Base
30
{
31
    /**
32
     * @var \HaaseIT\Toolbox\Textcat
33
     */
34
    private $textcats;
35
36
    /**
37
     * Shoppingcart constructor.
38
     * @param \Zend\ServiceManager\ServiceManager $serviceManager
39
     */
40
    public function __construct(\Zend\ServiceManager\ServiceManager $serviceManager)
41
    {
42
        parent::__construct($serviceManager);
43
        $this->textcats = $this->serviceManager->get('textcats');
44
    }
45
46
    /**
47
     *
48
     */
49
    public function preparePage()
0 ignored issues
show
Coding Style introduced by
preparePage uses the super-global variable $_SESSION which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

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

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
50
    {
51
        $this->P = new \HaaseIT\HCSF\CorePage($this->serviceManager);
52
        $this->P->cb_pagetype = 'contentnosubnav';
53
54
        if (HelperConfig::$shop['show_pricesonlytologgedin'] && !CHelper::getUserData()) {
55
            $this->P->oPayload->cl_html = $this->textcats->T('denied_notloggedin');
56
        } else {
57
            $this->P->cb_customcontenttemplate = 'shop/shoppingcart';
58
59
            // Check if there is a message to display above the shoppingcart
60
            $this->P->oPayload->cl_html = $this->getNotification();
61
62
            // Display the shoppingcart
63
            if (isset($_SESSION['cart']) && count($_SESSION['cart']) >= 1) {
64
                $aErr = [];
65
                if (filter_input(INPUT_POST, 'doCheckout') === 'yes') {
66
                    $aErr = $this->validateCheckout($aErr);
67
                    if (count($aErr) === 0) {
68
                        $this->doCheckout();
69
                    }
70
                }
71
72
                $aShoppingcart = SHelper::buildShoppingCartTable($_SESSION['cart'], false, '', $aErr);
0 ignored issues
show
Documentation introduced by
$aErr is of type array, but the function expects a string.

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...
73
74
                $this->P->cb_customdata = $aShoppingcart;
75
            } else {
76
                $this->P->oPayload->cl_html .= $this->textcats->T('shoppingcart_empty');
77
            }
78
        }
79
    }
80
81
    /**
82
     * @param array $aErr
83
     * @return array
84
     */
85
    private function validateCheckout($aErr = [])
86
    {
87
        $aErr = CHelper::validateCustomerForm(HelperConfig::$lang, $aErr, true);
88 View Code Duplication
        if (!CHelper::getUserData() && filter_input(INPUT_POST, 'tos') !== 'y') {
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...
89
            $aErr['tos'] = true;
90
        }
91 View Code Duplication
        if (!CHelper::getUserData() && filter_input(INPUT_POST, 'cancellationdisclaimer') !== 'y') {
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...
92
            $aErr['cancellationdisclaimer'] = true;
93
        }
94
        $postpaymentmethod = filter_input(INPUT_POST, 'paymentmethod');
95
        if (
96
            $postpaymentmethod === null
97
            || in_array($postpaymentmethod, HelperConfig::$shop['paymentmethods'], true) === false
98
        ) {
99
            $aErr['paymentmethod'] = true;
100
        }
101
102
        return $aErr;
103
    }
104
105
    /**
106
     * @param $aV
107
     * @return array
108
     */
109
    private function getItemImage($aV)
110
    {
111
        // base64 encode img and prepare for db
112
        // image/png image/jpeg image/gif
113
        // data:{mimetype};base64,XXXX
1 ignored issue
show
Unused Code Comprehensibility introduced by
45% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
114
115
        $aImagesToSend = [];
116
        $base64Img = false;
117
        $binImg = false;
118
119
        if (HelperConfig::$shop['email_orderconfirmation_embed_itemimages_method'] === 'glide') {
120
            $sPathToImage = '/'.HelperConfig::$core['directory_images'].'/'.HelperConfig::$shop['directory_images_items'].'/';
121
            $sImageroot = PATH_BASEDIR . HelperConfig::$core['directory_glide_master'];
122
123
            if (
124
                is_file($sImageroot.substr($sPathToImage.$aV['img'], strlen(HelperConfig::$core['directory_images']) + 1))
125
                && $aImgInfo = getimagesize($sImageroot.substr($sPathToImage.$aV['img'], strlen(HelperConfig::$core['directory_images']) + 1))
126
            ) {
127
                $glideserver = \League\Glide\ServerFactory::create([
128
                    'source' => $sImageroot,
129
                    'cache' => PATH_GLIDECACHE,
130
                    'max_image_size' => HelperConfig::$core['glide_max_imagesize'],
131
                ]);
132
                $glideserver->setBaseUrl('/' . HelperConfig::$core['directory_images'] . '/');
133
                $base64Img = $glideserver->getImageAsBase64($sPathToImage.$aV['img'], HelperConfig::$shop['email_orderconfirmation_embed_itemimages_glideparams']);
134
                $TMP = explode(',', $base64Img);
135
                $binImg = base64_decode($TMP[1]);
136
                unset($TMP);
137
            }
138
        } else {
139
            $sPathToImage =
140
                PATH_DOCROOT.HelperConfig::$core['directory_images'].'/'
141
                .HelperConfig::$shop['directory_images_items'].'/'
142
                .HelperConfig::$shop['directory_images_items_email'].'/';
143
            if ($aImgInfo = getimagesize($sPathToImage.$aV['img'])) {
144
                $binImg = file_get_contents($sPathToImage.$aV['img']);
145
                $base64Img = 'data:' . $aImgInfo['mime'] . ';base64,';
146
                $base64Img .= base64_encode($binImg);
147
            }
148
        }
149
        if (HelperConfig::$shop['email_orderconfirmation_embed_itemimages']) {
150
            $aImagesToSend['binimg'] = $binImg;
151
        }
152
        if ($base64Img) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $base64Img of type string|false is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
153
            $aImagesToSend['base64img'] = $base64Img;
154
        }
155
        return $aImagesToSend;
156
    }
157
158
    /**
159
     * @return array
160
     */
161
    private function prepareDataOrder()
0 ignored issues
show
Coding Style introduced by
prepareDataOrder uses the super-global variable $_SESSION which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

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

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
Coding Style introduced by
prepareDataOrder uses the super-global variable $_POST which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

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

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
162
    {
163
        $cartpricesums = $_SESSION['cartpricesums'];
164
        return [
165
            'o_custno' => filter_var(trim(Tools::getFormfield('custno')), FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW),
166
            'o_email' => filter_var(trim(Tools::getFormfield('email')), FILTER_SANITIZE_EMAIL),
167
            'o_corpname' => filter_var(trim(Tools::getFormfield('corpname')), FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW),
168
            'o_name' => filter_var(trim(Tools::getFormfield('name')), FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW),
169
            'o_street' => filter_var(trim(Tools::getFormfield('street')), FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW),
170
            'o_zip' => filter_var(trim(Tools::getFormfield('zip')), FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW),
171
            'o_town' => filter_var(trim(Tools::getFormfield('town')), FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW),
172
            'o_phone' => filter_var(trim(Tools::getFormfield('phone')), FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW),
173
            'o_cellphone' => filter_var(trim(Tools::getFormfield('cellphone')), FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW),
174
            'o_fax' => filter_var(trim(Tools::getFormfield('fax')), FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW),
175
            'o_country' => filter_var(trim(Tools::getFormfield('country')), FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW),
176
            'o_group' => trim(CHelper::getUserData('cust_group')),
177
            'o_remarks' => filter_var(trim(Tools::getFormfield('remarks')), FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW),
178
            'o_tos' => (filter_input(INPUT_POST, 'tos') === 'y' || CHelper::getUserData()) ? 'y' : 'n',
179
            'o_cancellationdisclaimer' => (filter_input(INPUT_POST, 'cancellationdisclaimer') === 'y' || CHelper::getUserData()) ? 'y' : 'n',
180
            'o_paymentmethod' => filter_var(trim(Tools::getFormfield('paymentmethod')), FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW),
181
            'o_sumvoll' => $cartpricesums['sumvoll'],
182
            'o_sumerm' => $cartpricesums['sumerm'],
183
            'o_sumnettoall' => $cartpricesums['sumnettoall'],
184
            'o_taxvoll' => $cartpricesums['taxvoll'],
185
            'o_taxerm' => $cartpricesums['taxerm'],
186
            'o_sumbruttoall' => $cartpricesums['sumbruttoall'],
187
            'o_mindermenge' => isset($cartpricesums['mindergebuehr']) ? $cartpricesums['mindergebuehr'] : '',
188
            'o_shippingcost' => SHelper::getShippingcost(),
189
            'o_orderdate' => date('Y-m-d'),
190
            'o_ordertimestamp' => time(),
191
            'o_authed' => CHelper::getUserData() ? 'y' : 'n',
192
            'o_sessiondata' => serialize($_SESSION),
193
            'o_postdata' => serialize($_POST),
194
            'o_remote_address' => filter_input(INPUT_SERVER, 'REMOTE_ADDR', FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW),
195
            'o_ordercompleted' => 'n',
196
            'o_paymentcompleted' => 'n',
197
            'o_srv_hostname' => filter_input(INPUT_SERVER, 'SERVER_NAME', FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW),
198
            'o_vatfull' => HelperConfig::$shop['vat']['full'],
199
            'o_vatreduced' => HelperConfig::$shop['vat']['reduced'],
200
        ];
201
    }
202
203
    /**
204
     * @param int $orderid
205
     * @param string $cartkey
206
     * @param array $values
207
     * @return array
208
     */
209
    private function buildOrderItemRow($orderid, $cartkey, array $values)
210
    {
211
        return [
212
            'oi_o_id' => $orderid,
213
            'oi_cartkey' => $cartkey,
214
            'oi_amount' => $values['amount'],
215
            'oi_price_netto_list' => $values['price']['netto_list'],
216
            'oi_price_netto_use' => $values['price']['netto_use'],
217
            'oi_price_brutto_use' => $values['price']['brutto_use'],
218
            'oi_price_netto_sale' => isset($values['price']['netto_sale']) ? $values['price']['netto_sale'] : '',
219
            'oi_price_netto_rebated' => isset($values['price']['netto_rebated']) ? $values['price']['netto_rebated'] : '',
220
            'oi_vat' => HelperConfig::$shop['vat'][$values['vat']],
221
            'oi_rg' => $values['rg'],
222
            'oi_rg_rebate' => isset(
223
                HelperConfig::$shop['rebate_groups'][$values['rg']][trim(CHelper::getUserData('cust_group'))]
224
            )
225
                ? HelperConfig::$shop['rebate_groups'][$values['rg']][trim(CHelper::getUserData('cust_group'))]
226
                : '',
227
            'oi_itemname' => $values['name'],
228
            'oi_img' => $this->imagestosend[$values['img']]['base64img'],
229
        ];
230
    }
231
232
    /**
233
     * @var array
234
     */
235
    private $imagestosend = [];
236
237
    private function writeCheckoutToDB()
0 ignored issues
show
Coding Style introduced by
writeCheckoutToDB uses the super-global variable $_SESSION which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

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

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
238
    {
239
        /** @var \Doctrine\DBAL\Connection $dbal */
240
        $dbal = $this->serviceManager->get('dbal');
241
242
        try {
243
            $dbal->beginTransaction();
244
245
            $aDataOrder = $this->prepareDataOrder();
246
247
            $iInsertID = \HaaseIT\HCSF\Helper::autoInsert($dbal, 'orders', $aDataOrder);
248
249
            foreach ($_SESSION['cart'] as $sK => $aV) {
250
                $this->imagestosend[$aV['img']] = $this->getItemImage($aV);
251
252
                \HaaseIT\HCSF\Helper::autoInsert(
253
                    $dbal,
254
                    'orders_items',
255
                    $this->buildOrderItemRow($iInsertID, $sK, $aV)
256
                );
257
            }
258
            $dbal->commit();
259
260
            return $iInsertID;
261
        } catch (\Exception $e) {
262
            // If something raised an exception in our transaction block of statements,
263
            // roll back any work performed in the transaction
264
            print '<p>Unable to complete transaction!</p>';
265
            error_log($e);
266
            $dbal->rollBack();
267
268
            throw new \Exception('Unable to submit order!');
269
        }
270
    }
271
272
    private function doCheckout()
0 ignored issues
show
Coding Style introduced by
doCheckout uses the super-global variable $_SESSION which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

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

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
273
    {
274
        try {
275
            $iInsertID = $this->writeCheckoutToDB();
276
        } catch (\Exception $e) {
277
            echo $e->getMessage();
278
        }
279
        $sMailbody_us = $this->buildOrderMailBody(false, $iInsertID);
280
        $sMailbody_they = $this->buildOrderMailBody(true, $iInsertID);
281
282
        // write to file
283
        $this->writeCheckoutToFile($sMailbody_us);
284
285
        // Send Mails
286
        $this->sendCheckoutMails($iInsertID, $sMailbody_us, $sMailbody_they);
287
288
        unset($_SESSION['cart'], $_SESSION['cartpricesums'], $_SESSION['sondercart']);
289
290
        $postpaymentmethod = filter_input(INPUT_POST, 'paymentmethod');
291
        if (
292
            $postpaymentmethod !== null
293
            && isset(HelperConfig::$shop['paypal_interactive'])
294
            && $postpaymentmethod === 'paypal'
295
            && in_array('paypal', HelperConfig::$shop['paymentmethods'], true) !== false
296
            && HelperConfig::$shop['paypal_interactive']
297
        ) {
298
            $redirectto = '/_misc/paypal.html?id=' . $iInsertID;
299
        } elseif (
300
            $postpaymentmethod !== null
301
            && $postpaymentmethod === 'sofortueberweisung'
302
            && in_array('sofortueberweisung', HelperConfig::$shop['paymentmethods'], true) !== false
303
        ) {
304
            $redirectto = '/_misc/sofortueberweisung.html?id=' . $iInsertID;
305
        } else {
306
            $redirectto = '/_misc/checkedout.html?id=' . $iInsertID;
307
        }
308
        \HaaseIT\HCSF\Helper::redirectToPage($redirectto);
309
    }
310
311
    /**
312
     * @param int $iInsertID
313
     * @param string $sMailbody_us
314
     * @param string $sMailbody_they
315
     */
316
    private function sendCheckoutMails($iInsertID, $sMailbody_us, $sMailbody_they)
317
    {
318
        if (
319
            isset(HelperConfig::$shop['email_orderconfirmation_attachment_cancellationform_' .HelperConfig::$lang])
320
            && file_exists(
321
                PATH_DOCROOT.HelperConfig::$core['directory_emailattachments']
322
                .'/'.HelperConfig::$shop['email_orderconfirmation_attachment_cancellationform_'
323
                .HelperConfig::$lang]
324
            )
325
        ) {
326
            $aFilesToSend[] =
0 ignored issues
show
Coding Style Comprehensibility introduced by
$aFilesToSend was never initialized. Although not strictly required by PHP, it is generally a good practice to add $aFilesToSend = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
327
                PATH_DOCROOT.HelperConfig::$core['directory_emailattachments'].'/'
328
                .HelperConfig::$shop['email_orderconfirmation_attachment_cancellationform_' .HelperConfig::$lang];
329
        } else {
330
            $aFilesToSend = [];
331
        }
332
333
        Helper::mailWrapper(
334
            filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL),
335
            $this->textcats->T('shoppingcart_mail_subject') . ' ' . $iInsertID,
336
            $sMailbody_they,
337
            $this->imagestosend,
338
            $aFilesToSend
339
        );
340
        Helper::mailWrapper(
341
            HelperConfig::$core['email_sender'],
342
            'Bestellung im Webshop Nr: ' . $iInsertID,
343
            $sMailbody_us,
344
            $this->imagestosend
345
        );
346
    }
347
348
    /**
349
     * @param string $sMailbody_us
350
     */
351
    private function writeCheckoutToFile($sMailbody_us)
352
    {
353
        $fp = fopen(PATH_LOGS . 'shoplog_' . date('Y-m-d') . '.html', 'a');
354
        // Write $somecontent to our opened file.
355
        fwrite($fp, $sMailbody_us . "\n\n-------------------------------------------------------------------------\n\n");
356
        fclose($fp);
357
    }
358
359
    /**
360
     * @param string $field
361
     * @return string
362
     */
363
    private function getPostValue($field)
364
    {
365
        $postvalue = filter_input(INPUT_POST, $field);
366
        return (!empty($postvalue) ? $postvalue : '');
367
    }
368
369
    /**
370
     * @param bool $bCust
371
     * @param int $iId
372
     * @return mixed
373
     */
374
    private function buildOrderMailBody($bCust = true, $iId)
0 ignored issues
show
Coding Style introduced by
buildOrderMailBody uses the super-global variable $_SESSION which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

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

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
Coding Style introduced by
buildOrderMailBody uses the super-global variable $_POST which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

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

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
375
    {
376
        $aM = [
377
            'customdata' => SHelper::buildShoppingCartTable($_SESSION['cart'], true),
378
            'currency' => HelperConfig::$shop['waehrungssymbol'],
379
        ];
380
        if (isset(HelperConfig::$shop['custom_order_fields'])) {
381
            $aM['custom_order_fields'] = HelperConfig::$shop['custom_order_fields'];
382
        }
383
384
        $postcustno = trim(filter_input(INPUT_POST, 'custno', FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW));
385
        $postcountry = trim(filter_input(INPUT_POST, 'country', FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW));
386
        $postpaymentmethod = filter_input(INPUT_POST, 'paymentmethod', FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW);
387
        $serverservername = filter_input(INPUT_SERVER, 'SERVER_NAME', FILTER_SANITIZE_URL);
388
        $aData = [
389
            'customerversion' => $bCust,
390
            //'shc_css' => file_get_contents(PATH_DOCROOT.'screen-shc.css'),
0 ignored issues
show
Unused Code Comprehensibility introduced by
55% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
391
            'datetime' => date('d.m.Y - H:i'),
392
            'custno' => $postcustno !== null && strlen($postcustno) >= HelperConfig::$customer['minimum_length_custno'] ? $postcustno : '',
393
            'corpname' => $this->getPostValue('corpname'),
394
            'name' => $this->getPostValue('name'),
395
            'street' => $this->getPostValue('street'),
396
            'zip' => $this->getPostValue('zip'),
397
            'town' => $this->getPostValue('town'),
398
            'phone' => $this->getPostValue('phone'),
399
            'cellphone' => $this->getPostValue('cellphone'),
400
            'fax' => $this->getPostValue('fax'),
401
            'email' => $this->getPostValue('email'),
402
            'country' => !empty($postcountry) ?
403
            (
404
                isset(
405
                    HelperConfig::$countries['countries_' .HelperConfig::$lang][$postcountry]
406
                )
407
                    ? HelperConfig::$countries['countries_' .HelperConfig::$lang][$postcountry]
408
                    : $postcountry)
409
            : '',
410
            'remarks' => $this->getPostValue('remarks'),
411
            'tos' => $this->getPostValue('tos'),
412
            'cancellationdisclaimer' => $this->getPostValue('cancellationdisclaimer'),
413
            'paymentmethod' => $this->getPostValue('paymentmethod'),
414
            'shippingcost' => empty($_SESSION['shippingcost']) ? false : $_SESSION['shippingcost'],
415
            'paypallink' => $postpaymentmethod === 'paypal' ? $serverservername.'/_misc/paypal.html?id='.$iId : '',
416
            'sofortueberweisunglink' => $postpaymentmethod === 'sofortueberweisung' ?  $serverservername.'/_misc/sofortueberweisung.html?id='.$iId : '',
417
            'SESSION' => !$bCust ? Tools::debug($_SESSION, '$_SESSION', true, true) : '',
418
            'POST' => !$bCust ? Tools::debug($_POST, '$_POST', true, true) : '',
419
            'orderid' => $iId,
420
        ];
421
422
        $aM['customdata']['mail'] = $aData;
423
424
        return $this->serviceManager->get('twig')->render('shop/mail-order-html.twig', $aM);
425
    }
426
427
    /**
428
     * @return string
429
     */
430
    private function getNotification()
431
    {
432
        $return = '';
433
        $getmsg = filter_input(INPUT_GET, 'msg');
434
        $getcartkey = filter_input(INPUT_GET, 'cartkey', FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW);
435
        $getamount = filter_input(INPUT_GET, 'cartkey', FILTER_SANITIZE_NUMBER_INT);
436
        if (!empty($getmsg)) {
437
            if (
438
                ($getmsg === 'updated' && !empty($getcartkey) && !empty($getamount))
439
                || ($getmsg === 'removed' && !empty($getcartkey))
440
            ) {
441
                $return .= $this->textcats->T('shoppingcart_msg_' . $getmsg . '_1') . ' ';
442
                if (isset(HelperConfig::$shop['custom_order_fields']) && mb_strpos($getcartkey, '|') !== false) {
443
                    $mCartkeys = explode('|', $getcartkey);
444
                    foreach ($mCartkeys as $sKey => $sValue) {
445
                        if ($sKey == 0) {
446
                            $return .= $sValue . ', ';
447
                        } else {
448
                            $TMP = explode(':', $sValue);
449
                            $return .= $this->textcats->T('shoppingcart_item_' . $TMP[0]) . ' ' . $TMP[1] . ', ';
450
                            unset($TMP);
451
                        }
452
                    }
453
                    $return = Tools::cutStringend($return, 2);
454
                } else {
455
                    $return .= $getcartkey;
456
                }
457
                $return.= ' ' . $this->textcats->T('shoppingcart_msg_'.$getmsg.'_2');
458
                if ($getmsg === 'updated') {
459
                    $return .= ' '.$getamount;
460
                }
461
                $return .= '<br><br>';
462
            }
463
        }
464
465
        return $return;
466
    }
467
}
468