Passed
Push — master ( 98c61b...80c098 )
by Mario
04:44
created

otherPaymentAction()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 35
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 17
nc 2
nop 0
dl 0
loc 35
rs 8.8571
c 0
b 0
f 0
1
<?php
2
3
use Shopware\Components\CSRFWhitelistAware;
4
5
/**
6
 * Klarna payment controller
7
 */
8
class Shopware_Controllers_Frontend_PaymentKlarna extends Shopware_Controllers_Frontend_Payment implements CSRFWhitelistAware
9
{
10
    /**
11
     * @var Shopware_Plugins_Frontend_SwagPaymentKlarna_Bootstrap
12
     */
13
    private $plugin;
14
15
    /**
16
     * @var Enlight_Config
17
     */
18
    private $config;
19
20
21
    private $basket;
22
23
    private $admin;
24
25
    private $session;
26
27
    /**
28
     * Init method that get called automatically
29
     *
30
     * Set class properties
31
     */
32
    public function init()
33
    {
34
        $this->admin = Shopware()->Modules()->Admin();
35
        $this->session = Shopware()->Session();
36
    }
37
38
39
    /**
40
     * {@inheritdoc}
41
     */
42
    public function preDispatch()
43
    {
44
45
        if (in_array($this->Request()->getActionName(), array('push', 'saveFormData'))) {
46
            $this->Front()->Plugins()->ViewRenderer()->setNoRender();
47
        }
48
    }
49
    
50
    /**
51
     * whitelists indexAction for SW 5.2 compatibility
52
     */
53
    public function getWhitelistedCSRFActions()
54
    {
55
        return [
56
            'index',
57
            'express',
58
            'push',
59
            'login',
60
            'return',
61
            'showIframe',
62
            'calculateShippingCosts',
63
            'savePayment',
64
            'addVoucher',
65
            'deleteArticle',
66
            'saveFormData',
67
            'setPayment',
68
            'otherPayment',
69
        ];
70
    }    
71
72
    /**
73
     * {@inheritdoc}
74
     */
75 View Code Duplication
    public function get($name)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
76
    {
77
        if (version_compare(Shopware::VERSION, '4.2.0', '<') && Shopware::VERSION != '___VERSION___') {
78
            if ($name == 'pluginlogger') {
79
                $name = 'log';
80
            }
81
            $name = ucfirst($name);
82
            return Shopware()->Bootstrap()->getResource($name);
83
        }
84
        return parent::get($name);
85
    }
86
    
87
    /**
88
     * Index action method.
89
     *
90
     * Forwards to correct the action.
91
     */
92
    public function indexAction()
93
    {
94
        $this->redirect(array('controller' => 'payment_klarna', 'action' => 'showIframe'));
95
96
    }
97
98
    /**
99
     * Express payment action method.
100
     */
101
    public function expressAction()
102
    {
103
        $this->plugin = $this->get('plugins')->Frontend()->SwagPaymentKlarna();
104
        if (!empty($this->session->PaypalResponse)){
105
            $this->plugin->klarnaLog("Paypal Payment in Progress detected Redirecting To Index Page", 3);
106
            $this->redirect(
107
                array(
108
                    'controller' => 'index',
109
                    'action' => 'index'
110
                )
111
            );
112
            return;
113
        }        
114
        
115
        if ($this->Request()->getPost('sCountry')) {
116
            $this->session['sCountry'] = (int)$this->Request()->getPost('sCountry');
117
            $this->session["sState"] = 0;
118
            $this->session["sArea"] = Shopware()->Db()->fetchOne("
119
                SELECT areaID FROM s_core_countries WHERE id = ?
120
            ", array($this->session['sCountry']));
121
            unset($this->session->KlarnaOrder);
122
            $this->session['sChangedCountry'] = (int)$this->Request()->getPost('sCountry');
123
        }
124
        $this->forward('index');
125
    }
126
127
128
    /**
129
     * Express Iframe Test
130
     */
131
    public function showIframeAction() {
132
133
        $this->plugin = $this->get('plugins')->Frontend()->SwagPaymentKlarna();
134
        $this->config = $this->plugin->Config();
135
        $this->basket = $this->get('modules')->Basket()->sGetBasket();
136
137
        $preFill = $this->config['preFillCheckout'];
138
        if ($this->isUserLoggedIn()){
139
            $user = Shopware()->Modules()->Admin()->sGetUserData();
140
        }
141
142
        $paymentIdDebug = $this->plugin->getPayment()->getId();
143
144
        // set payment to klarna checkout
145
        $this->session['sPaymentID'] = $this->plugin->getPayment()->getId();
146
147
        // Register Custom Template
148
        $this->View()->loadTemplate("frontend/checkout/confirm.tpl");
149
        // update dispatch or delivery country in case form was submitted
150
        if ($this->Request()->isPost()) {
151
152
            // set klarnaPrefill, in case User ovverides Setting with checkbox
153
154
            if ($this->Request()->getParam('klarnaPreFill') == "on"){
155
                $this->session['klarnaUserPreFill'] = true;
156
            }
157
158
            $this->setDispatch($this->Request()->getPost('sDispatch'));
159
            $postedCountry = $this->Request()->getPost('sCountry');
160
            if (!empty($postedCountry)) {
161
                $shopCountryId = $this->session['sCountry'];
162
                $validKlarnaCountry = $this->plugin->checkValidKlarnaCountry($postedCountry);
163
                if (!$validKlarnaCountry) {
164
                    $this->redirect(array('controller' => 'payment_klarna', 'action' => 'otherPayment'));
165
                    return;
166
                }
167
                $shopCountryId = (string)$shopCountryId;
168
                if ($shopCountryId != $postedCountry) {
169
                    $this->session['sCountry'] = $postedCountry;
170
                    // unset klarnaOrder so it will be created with new countryID
171
                    unset($this->session['KlarnaOrder']);
172
                }
173
            }
174
            //$this->redirect(array('controller' => 'payment_klarna', 'action' => 'showIframe'));
0 ignored issues
show
Unused Code Comprehensibility introduced by
72% 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...
175
        } else {
176
            $this->setDispatch($this->session->sDispatch, $paymentIdDebug);
177
        }
178
        // set shipping costs (Overwrites $session->sCountry!)
179
        $debugShipping = $this->getShippingCosts();
180
        if ($postedCountry){
181
            $this->session['sCountry'] = $postedCountry;
0 ignored issues
show
Bug introduced by
The variable $postedCountry 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...
182
        } else {
183
            // set Default Country
184
            $this->session['sCountry'] = $this->getCountryByShop(Shopware()->Shop());
185
        }
186
187
        $this->basket['sShippingcosts'] = $debugShipping['brutto'];;
188
        $this->basket['sShippingcostsWithTax'] = $debugShipping['brutto'];
189
        $this->basket['sShippingcostsNet'] = $debugShipping['netto'];
190
        $this->basket['sShippingcostsTax'] = $debugShipping['tax'];
191
192
        // set missing basket vars for use in view
193
        // $this->basket['sAmount'] = $this->basket['Amount'] + $debugShipping['brutto'];
0 ignored issues
show
Unused Code Comprehensibility introduced by
63% 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...
194
        $this->basket['AmountWithTaxNumeric'] = floatval(str_replace(',','.',$this->basket['Amount'])) + floatval(str_replace(',','.',$debugShipping['brutto']));
195
        $this->basket['AmountNetNumeric'] = floatval(str_replace(',','.',$this->basket['AmountNet']));
196
197
        $klarnaConnector = $this->plugin->getConnector();
198
        $shop = $this->plugin->Application()->Shop();
199
200
        $create = array();
201
        $create['cart']['items'] = $this->plugin->getCheckoutCart($this->basket);
202
        $create['merchant'] = $this->plugin->getCheckoutMerchant();
203
204
        $create['purchase_country'] = $this->plugin->getCountryIsoById($this->session['sCountry']);
205
        $create['purchase_currency'] = $shop->getCurrency()->toString();
206
        $create['locale'] = $this->plugin->getLocale(false, $create['purchase_country']);
207
        $create['options'] = $this->plugin->getCheckoutOptions();
208
209
        if ($this->config->get('KlarnaExternalPayments')) {
210
            list($create['external_payment_methods'], $create['external_checkouts']) = $this->plugin->getExternalPaymentMethods($this->basket);
211
        }
212
213
        if ($this->config->get('disableAutofocus')) {
214
            $create['gui']['options'] = array('disable_autofocus');
215
        }
216
217
        // set Prefill Information
218
219
        if (($preFill == true) || ($this->session['klarnaUserPreFill'] == true)) {
220
            $this->session['klarnaPreFill'] = true;
221
            if (empty($session['sCountry'])) {
0 ignored issues
show
Bug introduced by
The variable $session seems to never exist, and therefore empty should always return true. Did you maybe rename this variable?

This check looks for calls to isset(...) or empty() on variables that are yet undefined. These calls will always produce the same result and can be removed.

This is most likely caused by the renaming of a variable or the removal of a function/method parameter.

Loading history...
222
                $countryId = $this->getCountryByShop($shop);
223
            }
224
            else {
225
                $countryId = $session['sCountry'];
226
            }
227
            if ($user ['additional']['countryShipping']['id'] == $countryId
228
                && $user['billingaddress']['zipcode'] != '00000'
229
            ) {
230
                $create['customer'] = $this->plugin->getCheckoutCustomer($user);
0 ignored issues
show
Bug introduced by
The variable $user 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...
231
                if ($user['additional']['countryShipping']['id'] == $user['additional']['country']['id']) {
232
                    $create['shipping_address'] = $this->plugin->getCheckoutAddress($user, 'billing');
233
                } else {
234
                    $create['shipping_address'] = $this->plugin->getCheckoutAddress($user, 'shipping');
235
                }
236
            }
237
        } else {
238
            $this->session['klarnaPreFill'] = false;
239
        }
240
241
        // In case Customer fills Iframe and then logs in do not update existing klarnaOrder
242
        if (!empty($this->session['KlarnaOrder']) && !$this->isUserLoggedIn()){
243
            $klarnaOrder = new Klarna_Checkout_Order($klarnaConnector, $this->session['KlarnaOrder']);
244
            $update = array();
245
            $update['cart']['items'] = $this->plugin->getCheckoutCart($this->basket);
246
            $update['purchase_country'] = $this->plugin->getCountryIsoById($this->session['sCountry']);
247
248
            $klarnaOrder->fetch();
249
            // update basket and delivery country in case it changed
250
            $klarnaOrder->update($update);
251
252
        } else {
253
            $klarnaOrder = new Klarna_Checkout_Order($klarnaConnector);
254
            $klarnaOrder->create($create);
255
        }
256
257
258
        try {
259
            $klarnaOrder->fetch();
260
261
        } catch (Exception $e) {
262
            Shopware()->Plugins()->Controller()->ViewRenderer()->setNoRender();
263
            echo "Entschuldigung, Ein Verbindungsfehler ist aufgetreten, bitte aktualisieren Sie die Seite";
264
            $this->plugin->klarnaLog("Verbindungsfehler in onPreDispatchCheckout\nCode:".$e->getCode()."Nachricht:\n".$e->getMessage(),1);
265
        }
266
267
        $this->session->KlarnaOrder = $klarnaOrder->getLocation();
268
269
        // Delete old perhaps cancelled Klarna Order
270
271
        if ($klarnaOrder['status'] !== "checkout_incomplete"){
272
            unset($this->session->KlarnaOrder);
273
        }
274
275
276
        $configDebug = $this->config;
0 ignored issues
show
Unused Code introduced by
$configDebug is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
277
        $testarray = array();
278
        $testarray['additional']['charge_vat'] = 1;
279
280
        $testPayment = array();
281
        $testPayment['id'] = $this->plugin->getPayment()->getId();
282
283
        // persist basket changes
284
        Shopware()->Session()->sOrderVariables['sBasket'] = $this->basket;
285
286
        $test1 = Shopware()->Session()->sDispatch;
0 ignored issues
show
Unused Code introduced by
$test1 is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
287
288
        // Klarna Iframe Information
289
        $this->View()->assign('KlarnaOrder', $klarnaOrder->marshal());
290
291
        // Klarna Prefill checkBox
292
        if ($this->isUserLoggedIn()) {
293
               $this->View()->assign('KlarnaPreFillSelect', !$this->session['klarnaPreFill']);
294
        }
295
296
        // Iframe Backend Config
297
        $this->plugin->getViewConfig($this->View(), $this->config);
298
        $countryDebug = $this->session['sCountry'];
0 ignored issues
show
Unused Code introduced by
$countryDebug is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
299
        $this->View()->sBasket = $this->basket;
300
        $countryDebug = $this->session['sCountry'];
0 ignored issues
show
Unused Code introduced by
$countryDebug is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
301
        //$debugDispatches = $this->getDispatches($paymentIdDebug);
0 ignored issues
show
Unused Code Comprehensibility introduced by
64% 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...
302
        $countryDebug = $this->session['sCountry'];
0 ignored issues
show
Unused Code introduced by
$countryDebug is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
303
        $this->View()->sDispatches = $this->getDispatches($paymentIdDebug);
304
        if ($postedCountry){
305
            $this->session['sCountry'] = $postedCountry;
306
        }
307
308
        $countryDebug = $this->session['sCountry'];
0 ignored issues
show
Unused Code introduced by
$countryDebug is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
309
        $sessionDbg = $this->session->sDispatch;
0 ignored issues
show
Unused Code introduced by
$sessionDbg is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
310
        $this->View()->sDispatch = $this->getSelectedDispatch();
311
312
        // Neccessary if user is not logged in
313
        $this->View()->sPayment = $testPayment;
314
315
        $this->basket['sShippingcosts'] = $debugShipping['brutto'];;
316
        $this->basket['sShippingcostsWithTax'] = $debugShipping['brutto'];
317
        $this->basket['sShippingcostsNet'] = $debugShipping['netto'];
318
        $this->basket['sShippingcostsTax'] = $debugShipping['tax'];
319
320
        $this->basket['sAmount'] = floatval ($this->basket['Amount']) + floatval($this->basket['sShippingcosts']);
321
        //$this->basket['AmountWithTaxNumeric'] = (int) $this->basket['Amount'] + $debugShipping['brutto'];
0 ignored issues
show
Unused Code Comprehensibility introduced by
64% 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...
322
        //$this->basket['AmountNumeric'] = floatval($this->basket['Amount']) + floatval($debugShipping['brutto'];
0 ignored issues
show
Unused Code Comprehensibility introduced by
65% 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...
323
        //$this->basket['AmountNetNumeric'] = (int) $this->basket['AmountNet'] + $debugShipping['netto'];
0 ignored issues
show
Unused Code Comprehensibility introduced by
64% 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...
324
        $netto1 =  $this->basket['AmountNet'];
0 ignored issues
show
Unused Code introduced by
$netto1 is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
325
        $netto2 =  $debugShipping['netto'];
0 ignored issues
show
Unused Code introduced by
$netto2 is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
326
        $netto3 =  (float)$this->basket['AmountNet'];
0 ignored issues
show
Unused Code introduced by
$netto3 is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
327
        $netto4 =  (float)$debugShipping['netto'];
0 ignored issues
show
Unused Code introduced by
$netto4 is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
328
        $netto5 = (float)$this->basket['AmountNet'] + (float)$debugShipping['netto'];
0 ignored issues
show
Unused Code introduced by
$netto5 is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
329
        $this->basket['sAmountNet'] = floatval($this->basket['AmountNetNumeric']) + floatval($debugShipping['netto']);
330
331
        $this->basket['sAmountTax'] = 1.9;
332
        $this->View()->sShippingcosts = $debugShipping['brutto'];
333
        $this->View()->sShippingcostsWithTax =  $debugShipping['brutto'];
334
        $this->View()->sShippingcostsNet = $debugShipping['netto'];
335
        $this->View()->sShippingcostsTax = $debugShipping['tax'];
336
        $this->View()->sAmount = $this->basket['AmountWithTaxNumeric'] ;
337
338
339
340
//      $this->View()->sAmountWithTax = 0;
0 ignored issues
show
Unused Code Comprehensibility introduced by
54% 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...
341
        $this->View()->sAmountNet = $this->basket['sAmountNet'];
342
        $this->View()->sAmountTax = $this->basket['sAmountTax'];
343
        $countryDebug = $this->session['sCountry'];
0 ignored issues
show
Unused Code introduced by
$countryDebug is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
344
        $this->View()->assign('sUserData', $testarray);
345
        $countryDebug = $this->session['sCountry'];
0 ignored issues
show
Unused Code introduced by
$countryDebug is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
346
        $this->View()->sPayments = $this->admin->sGetPaymentMeans();
347
        $countryDebug = $this->session['sCountry'];
0 ignored issues
show
Unused Code introduced by
$countryDebug is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
348
        $this->View()->sUserLoggedIn = $this->isUserLoggedIn();
349
        $countryDebug = $this->session['sCountry'];
0 ignored issues
show
Unused Code introduced by
$countryDebug is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
350
    }
351
352
    /**
353
     * @param $shop Shopware\Models\Shop\Shop
354
     * @return int|null
355
     */
356 View Code Duplication
    public function getCountryByShop($shop)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
357
    {
358
        $locale = $shop->getLocale()->getLocale();
359
        $this->plugin->klarnaLog("Entering Bootstrap::getCountryByShop", 3);
360
        $locale = explode('_', $locale);
361
        $locale = isset($locale[1]) ? $locale[1] : $locale[0];
362
        $this->plugin->klarnaLog("Bootstrap::getCountryByShop locale to request for:".$locale,3);
363
        $sql = 'SELECT id FROM s_core_countries WHERE countryiso=?';
364
        $countryId = Shopware()->Db()->fetchOne($sql, array($locale));
365
        $countryId = ($countryId) ? (int)$countryId : null;
366
367
        return $countryId;
368
    }
369
370
    /**
371
     * Add voucher to cart
372
     *
373
     * At failure view variable sVoucherError will give further information
374
     * At success return to cart / confirm view
375
     */
376
    public function addVoucherAction()
377
    {
378
        $this->basket = Shopware()->Modules()->Basket();
379
        if ($this->Request()->isPost()) {
380
            $voucher = $this->basket->sAddVoucher($this->Request()->getParam('sVoucher'));
381
            if (!empty($voucher['sErrorMessages'])) {
382
                $this->View()->assign('sVoucherError', $voucher['sErrorMessages'], null, Smarty::SCOPE_ROOT);
383
            }
384
        }
385
        $this->forward('showIframe');
386
    }
387
388
389
390
    /**
391
     * Get shipping costs as an array (brutto / netto) depending on selected country / payment
392
     *
393
     * @return array
394
     */
395
    public function getShippingCosts()
396
    {
397
        $country = $this->getSelectedCountry();
398
        $payment = $this->plugin->getPayment()->getId();
399
        if (empty($country) || empty($payment)) {
400
            return array('brutto'=>0, 'netto'=>0);
401
        }
402
        $shippingcosts = $this->admin->sGetPremiumShippingcosts($country);
403
        return empty($shippingcosts) ? array('brutto'=>0, 'netto'=>0) : $shippingcosts;
404
    }
405
406
    /**
407
     * Express Iframe Test
408
     */
409
    public function finishAction() {
410
411
        $this->plugin = $this->get('plugins')->Frontend()->SwagPaymentKlarna();
412
        $this->config = $this->plugin->Config();
413
        $this->basket = $this->get('modules')->Basket()->sGetBasket();
414
415
        $connector = $this->plugin->getConnector();
416
        $klarnaOrder = new Klarna_Checkout_Order($connector, $this->session['KlarnaOrder']);
417
        $klarnaOrder->fetch();
418
        $this->View()->loadTemplate("frontend/checkout/finish.tpl");
419
        $this->View()->assign('KlarnaOrder', $klarnaOrder->marshal());
420
        // reset basket
421
        unset($this->session['KlarnaOrder']);
422
        unset($this->session['sBasketQuantity']);
423
        unset($this->session['sBasketAmount']);
424
    }
425
426
    /**
427
     * Change quantity of a certain product
428
     * @param sArticle = The article to update
429
     * @param sQuantity = new quantity
430
     * Forward to cart / confirm view after success
431
     */
432
    public function changeQuantityAction()
433
    {
434
        $basketObj = $this->get('modules')->Basket();
435
436
        if ($this->Request()->getParam('sArticle') && $this->Request()->getParam('sQuantity')) {
437
            $this->View()->sBasketInfo = $basketObj->sUpdateArticle($this->Request()->getParam('sArticle'), $this->Request()->getParam('sQuantity'));
438
        }
439
       $this->redirect(['action' => $this->Request()->getParam('sTargetAction', 'showIframe')]);
440
    }
441
442
    /**
443
     * Delete an article from cart -
444
     * @param sDelete = id from s_basket identifying the product to delete
445
     * Forward to cart / confirmation page after success
446
     */
447
    public function deleteArticleAction()
448
    {
449
        $basketObj = $this->get('modules')->Basket();
450
451
        if ($this->Request()->getParam('sDelete')) {
452
            $basketObj->sDeleteArticle($this->Request()->getParam('sDelete'));
453
        }
454
        $this->forward($this->Request()->getParam('sTargetAction', 'index'));
455
    }
456
457
    /**
458
     * Get all dispatches available in selected country from sAdmin object
459
     *
460
     * @param null $paymentId
461
     * @return array list of dispatches
462
     */
463
    public function getDispatches($paymentId = null)
464
    {
465
        $country = $this->getSelectedCountry();
466
        $state = $this->getSelectedState();
467
        if (empty($country)) {
468
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by Shopware_Controllers_Fro...ntKlarna::getDispatches of type array.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

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

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
469
        }
470
        $stateId = !empty($state['id']) ? $state['id'] : null;
471
        return $this->admin->sGetPremiumDispatches($country['id'], $paymentId, $stateId);
472
    }
473
474
    /**
475
     * Set the provided dispatch method
476
     *
477
     * @param $dispatchId ID of the dispatch method to set
478
     * @param int|null $paymentId Payment id to validate
479
     * @return int set dispatch method id
480
     */
481
    public function setDispatch($dispatchId, $paymentId = null)
482
    {
483
        $supportedDispatches = $this->getDispatches($paymentId);
484
485
        // Iterate over supported dispatches, look for the provided one
486
        foreach ($supportedDispatches as $dispatch) {
487
            if ($dispatch['id'] == $dispatchId) {
488
                $this->session['sDispatch'] = $dispatchId;
489
                return $dispatchId;
490
            }
491
        }
492
493
        // If it was not found, we fallback to the default (head of supported)
494
        $defaultDispatch = array_shift($supportedDispatches);
495
        $this->session['sDispatch'] = $defaultDispatch['id'];
496
        $sessionDbg = $this->session->sDispatch;
0 ignored issues
show
Unused Code introduced by
$sessionDbg is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
497
        return $this->session['sDispatch'];
498
    }
499
500
    /**
501
     * Get selected dispatch or select a default dispatch
502
     *
503
     * @return boolean|array
504
     */
505
    public function getSelectedDispatch()
506
    {
507
        if (empty($this->session['sCountry'])) {
508
            return false;
509
        }
510
511
        $dispatches = $this->admin->sGetPremiumDispatches($this->session['sCountry'], null, $this->session['sState']);
512
        if (empty($dispatches)) {
513
            unset($this->session['sDispatch']);
514
            return false;
515
        }
516
517
        foreach ($dispatches as $dispatch) {
518
            if ($dispatch['id'] == $this->session['sDispatch']) {
519
                return $dispatch;
520
            }
521
        }
522
        $dispatch = reset($dispatches);
523
        $this->session['sDispatch'] = (int) $dispatch['id'];
524
        return $dispatch;
525
    }
526
527
    /**
528
     * On any change on country, payment or dispatch recalculate shipping costs
529
     * and forward to cart / confirm view
530
     */
531
    public function calculateShippingCostsAction()
532
    {
533
        if ($this->Request()->getPost('sCountry')) {
534
            $this->session['sCountry'] = (int) $this->Request()->getPost('sCountry');
535
            $this->session["sState"] = 0;
536
            $this->session["sArea"] = Shopware()->Db()->fetchOne("
537
            SELECT areaID FROM s_core_countries WHERE id = ?
538
            ", array($this->session['sCountry']));
539
        }
540
541
        if ($this->Request()->getPost('sPayment')) {
542
            $this->session['sPaymentID'] = (int) $this->Request()->getPost('sPayment');
543
        }
544
545
        if ($this->Request()->getPost('sDispatch')) {
546
            $this->session['sDispatch'] = (int) $this->Request()->getPost('sDispatch');
547
        }
548
549
        if ($this->Request()->getPost('sState')) {
550
            $this->session['sState'] = (int) $this->Request()->getPost('sState');
551
        }
552
553
        // We might change the shop context here so we need to initialize it again
554
        $this->get('shopware_storefront.context_service')->initializeShopContext();
555
556
        // We need an indicator in the view to expand the shipping costs pre-calculation on page load
557
        $this->View()->assign('calculateShippingCosts', true);
558
559
        $this->forward('showIframe');
560
    }
561
562
    /**
563
     * Get current selected country - if no country is selected, choose first one from list
564
     * of available countries
565
     *
566
     * @return array with country information
567
     */
568
    public function getSelectedCountry()
569
    {
570
        if (!empty($this->View()->sUserData['additional']['countryShipping'])) {
571
            $this->session['sCountry'] = (int) $this->View()->sUserData['additional']['countryShipping']['id'];
572
            $this->session['sArea'] = (int) $this->View()->sUserData['additional']['countryShipping']['areaID'];
573
574
            return $this->View()->sUserData['additional']['countryShipping'];
575
        }
576
        $countries = $this->getCountryList();
577
        if (empty($countries)) {
578
            unset($this->session['sCountry']);
579
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by Shopware_Controllers_Fro...rna::getSelectedCountry of type array.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

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

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
580
        }
581
        $country = reset($countries);
582
        $this->session['sCountry'] = (int) $country['id'];
583
        $this->session['sArea'] = (int) $country['areaID'];
584
        $this->View()->sUserData['additional']['countryShipping'] = $country;
585
        return $country;
586
    }
587
588
    /**
589
     * Get all countries from database via sAdmin object
590
     *
591
     * @return array list of countries
592
     */
593
    public function getCountryList()
594
    {
595
        return $this->admin->sGetCountryList();
596
    }
597
598
    /**
599
     * Get current selected country - if no country is selected, choose first one from list
600
     * of available countries
601
     *
602
     * @return array with country information
603
     */
604
    public function getSelectedState()
605
    {
606
        if (!empty($this->View()->sUserData['additional']['stateShipping'])) {
607
            $this->session['sState'] = (int) $this->View()->sUserData['additional']['stateShipping']['id'];
608
            return $this->View()->sUserData['additional']['stateShipping'];
609
        }
610
        return array("id" => $this->session['sState']);
611
    }
612
613
   /**
614
     * @param Klarna_Checkout_Order $order
615
     */
616
    public function createAccount($order = null, $checkLoginState=true)
617
    {
618
        $this->plugin = $this->get('plugins')->Frontend()->SwagPaymentKlarna();
619
        $this->plugin->klarnaLog('Entering Shopware_Controllers_Frontend_PaymentKlarna::createAccount', 3);
620
        $module = Shopware()->Modules()->Admin();
621
        $session = Shopware()->Session();
622
623
        $version = Shopware()->Config()->version;
624
        if ($version == '___VERSION___' || version_compare($version, '4.1.0', '>=')) {
625
            $encoder = Shopware()->PasswordEncoder()->getDefaultPasswordEncoderName();
626
        }
627
        
628
        $data = array();
629
630
        if ($order !== null && !empty($order['billing_address']['email'])) {
631
            $data['auth']['email'] = $order['billing_address']['email'];
632
            $data['auth']['password'] = $order['reference'];
633
        } else {
634
            $sessionId = Shopware()->SessionID();
635
            // email is only varchar(70) so we cut the sessionid
636
            //$sessionId = substr($sessionId, 0,49);
0 ignored issues
show
Unused Code Comprehensibility introduced by
65% 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...
637
            $data['auth']['email'] = substr($sessionId, 0,49) . '@klarna.com';
638
            $data['auth']['password'] = $sessionId;
639
        }
640
        $data['auth']['accountmode'] = '1';
641
642
        $phone = $order['billing_address']['phone'];
643
        $data['billing']['phone'] = !empty($phone) ? $phone : ' ';
644
        $data['phone'] = !empty($phone) ? $phone : ' ';
645
        if (!empty($order['customer']['date_of_birth'])) {
646
            list($data['billing']['birthyear'], $data['billing']['birthmonth'], $data['billing']['birthday']) = explode(
647
                '-',
648
                $order['customer']['date_of_birth']
649
            );
650
        }
651
652
        $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::createAccount->order:",4, $order);
653
        
654
        foreach (array('billing', 'shipping') as $type) {
655
            if (isset($order[$type . '_address'])) {
656
                $orderAddress = $order[$type . '_address'];
657
                if (isset($orderAddress['title'])) {
658
                    $data[$type]['salutation'] = $orderAddress['title'] == 'Frau' ? 'ms' : 'mr';
659
                } else {
660
                    $data[$type]['salutation'] = 'mr';
661
                }
662
                $data[$type]['firstname'] = $orderAddress['given_name'];
663
                $data[$type]['lastname'] = $orderAddress['family_name'];
664
                if (isset($orderAddress['street_name']) && $orderAddress['street_number']) {
665
                    if (version_compare(Shopware::VERSION, '5.0.0', '>=')) {
666
                        $data[$type]['street'] = $orderAddress['street_name'] . ' ' . $orderAddress['street_number'];
667 View Code Duplication
                    } else {
1 ignored issue
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...
668
                        $data[$type]['street'] = $orderAddress['street_name'];
669
                        $data[$type]['streetnumber'] = $orderAddress['street_number'];
670
                    }
671
                } else {
672
                    $data[$type]['street'] = $orderAddress['street_address'];
673
                    $data[$type]['streetnumber'] = ' ';
674
                }
675
                $data[$type]['zipcode'] = $orderAddress['postal_code'];
676
                $data[$type]['city'] = $orderAddress['city'];
677
                if (!empty($orderAddress['care_of'])) {
678
                    if ($orderAddress['street_name'] == 'Packstation') {
679
                        $data[$type]['postnumber'] = $orderAddress['care_of'];
680
                        $data[$type]['swagDhlPostnumber'] = $data[$type]['postnumber'];
681
                    } else {
682
                        $data[$type]['company'] = $orderAddress['care_of'];
683
                    }
684
                }
685
            }
686
687
            if (!isset($data[$type]['company'])) {
688
                $data[$type]['company'] = '';
689
            }
690
            $data[$type]['department'] = '';
691
692
            if (!empty($order[$type . '_address']['country'])) {
693
                $sql = 'SELECT id FROM s_core_countries WHERE countryiso=?';
694
                $countryId = Shopware()->Db()->fetchOne($sql, array($order[$type . '_address']['country']));
695
            } else {
696
                $countryId = $session['sCountry'];
697
            }
698
            // make sure country is set in case of lost sessions defualt to germany
699
            if (empty($countryId)){
700
                $countryId = 2;
701
            }            
702
703
            $data[$type]['country'] = $countryId;
704
        }
705
706
        $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::createAccount->data AFTER ADDRESSES:",4,$data);
707
        $sql = 'SELECT id FROM s_core_paymentmeans WHERE name=?';
708
        $paymentId = Shopware()->Db()->fetchOne($sql, array('klarna_checkout'));
709
710
        if ($order !== null && !empty($order['billing_address']['email'])) {
711
            $shop = $this->get('shop');
712
            $shop = $shop->getMain() ?: $shop;
713
            $sql = 'SELECT id, email, `password` FROM `s_user` WHERE `email` LIKE ? AND `active` = 1 ';
714
            if ($shop->getCustomerScope()) {
715
                $sql .= "AND `subshopID` = {$shop->getId()} ";
716
            }
717
            $sql .= 'ORDER BY `accountmode`';
718
            $user = Shopware()->Db()->fetchRow($sql, array($data['auth']['email']));
719
            // First try login 
720
            if (!empty($user)) {
721
                $session->offsetSet('sUserMail', $user['email']);
722
                $session->offsetSet('sUserPassword', $user['password']);
723
                $session->offsetSet('sUserId', $user['id']);
724
            } else {
725
                $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::createAccount->user Not Found in DB SQL was:" .$sql,1);                
726
            }
727
        }
728
729
        if ($checkLoginState) {
730
            // Check login status
731
            if (!empty($session->sUserId)) {
732
                if ($order !== null) {
733
                    $module->sSYSTEM->_POST = $data['shipping'];
734 View Code Duplication
                    if (Shopware::VERSION === '___VERSION___' || version_compare(Shopware::VERSION, '5.2.0', '>=')) {
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...
735
                        $userId = $session->offsetGet('sUserId');
736
                        $this->updateShipping($userId, $data['shipping']);
737
                    } else {
738
                        $module->sUpdateShipping();
739
                    }
740
                    $module->sSYSTEM->_POST = $data['billing'];
741 View Code Duplication
                    if (Shopware::VERSION === '___VERSION___' || version_compare(Shopware::VERSION, '5.2.0', '>=')) {                
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...
742
                         $userId = $session->offsetGet('sUserId');
743
                         $this->updateBilling($userId, $data['billing']);
744
                    } else{
745
                        $module->sUpdateBilling();
746
                    }
747
                    unset($data['auth']['password']);
748
                    $module->sSYSTEM->_POST = $data['auth'];
749
                    if (Shopware::VERSION === '___VERSION___' || version_compare(Shopware::VERSION, '5.2.0', '>=')) {
750
                        $userId = $session->offsetGet('sUserId');
751
                        $this->updateCustomer($data, $userId);
752
                        $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::createAccount->updateCustomer:",3, $data);                                                
753
                    } else{
754
                        $module->sUpdateAccount();
755
                        $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::createAccount->updateAccount:",3, $this->front->Request()->getPost());                                                                        
756
                    }
757
                } else {
758
                    /** @var Enlight_Controller_Front $front */
759
                    $front = $this->get('front');
760
                    $front->Request()->setPost(array());
761
                    $module->sSYSTEM->_POST = array('country' => $data['shipping']['country']);
762
                    $shippingId = $this->get('db')->fetchOne(
763
                        'SELECT id FROM s_user_shippingaddress WHERE userID = ?',
764
                        array($session->offsetGet('sUserId'))
765
                    );
766 View Code Duplication
                    if (!empty($shippingId)) {
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...
767
                        if (Shopware::VERSION === '___VERSION___' || version_compare(Shopware::VERSION, '5.2.0', '>=')) {
768
                            $userId = $session->offsetGet('sUserId');
769
                            $this->updateShipping($userId, $data['shipping']);
770
                        } else {
771
                            $module->sUpdateShipping();
772
                        }
773
                    } else {
774
                        $module->sUpdateBilling();
775
                    }
776
                }
777
                $module->sSYSTEM->_POST = array('sPayment' => $paymentId);
778
                $module->sUpdatePayment();
779
            } else {
780
                $data['payment']['object'] = $module->sGetPaymentMeanById($paymentId);
781
                if (isset($encoder)) {
782
                    $data["auth"]["encoderName"] = $encoder;
783
                    $data["auth"]["password"] = Shopware()->PasswordEncoder()->encodePassword($data["auth"]["password"], $encoder);
784
                } else {
785
                    $data['auth']['password'] = md5($data['auth']['password']);
786
                }
787
                $session->sRegisterFinished = false;
788
                if (version_compare(Shopware::VERSION, '4.3.0', '>=') && version_compare(Shopware::VERSION, '5.2.0', '<')) {
789
                    $session->sRegister = $data;
790
                } elseif (version_compare(Shopware::VERSION, '4.3.0', '<')) {
791
                    $session->sRegister = new ArrayObject($data, ArrayObject::ARRAY_AS_PROPS);
792
                }
793
                try {
794
                    if (Shopware::VERSION === '___VERSION___' || version_compare(Shopware::VERSION, '5.2.0', '>=')) {
795
                        $newdata = $this->saveUser($data);
796
                        $module->sSYSTEM->_POST = $newdata['auth'];
797
                        $errors = $module->sLogin(true);                     
0 ignored issues
show
Unused Code introduced by
$errors is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
798
                        $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::createAccount->saveUser:",3, $newdata);
799
                    } else {
800
                        $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::createAccount->saveUser->Register:",3, $session->sRegister);                         
801
                        $module->sSaveRegister();
802
                        $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::createAccount->saveUser->RegisterFinished:",3, $session->offsetGet('sRegisterFinished')); 
803
                    }
804
                    
805
                } catch (\Exception $ex) { /* do nothing */
806
                    $this->klarnaLog("ERROR while creating User. Exception information:".$ex->getMessage(),1);
807
                    
808
                }
809
            }
810
            
811
        }
812
        
813
        $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::createAccount->data END OF METHOD:",4, $data);
814
    }
815
    
816
    /**
817
     * Saves a new user to the system.
818
     *
819
     * @param array $data
820
     */
821
    private function saveUser($data)
822
    {
823
824
        $plainbilling = array_merge($data['auth'], $data['billing']);
825
        $plainshipping = array_merge($data['auth'], $data['shipping']);
826
827
        //Create forms and validate the input
828
        $customer = new Shopware\Models\Customer\Customer();
829
        $form = $this->createForm('Shopware\Bundle\AccountBundle\Form\Account\PersonalFormType', $customer);
830
        $form->submit($plainbilling);
831
832
        $billingaddress = new Shopware\Models\Customer\Address();
833
        $form = $this->createForm('Shopware\Bundle\AccountBundle\Form\Account\AddressFormType', $billingaddress);
834
        $form->submit($plainbilling);
835
836
        $shippingaddress = new Shopware\Models\Customer\Address();
837
        $form = $this->createForm('Shopware\Bundle\AccountBundle\Form\Account\AddressFormType', $shippingaddress);
838
        $form->submit($plainshipping);
839
840
        /** @var Shopware\Bundle\StoreFrontBundle\Struct\ShopContextInterface $context */
841
        $context = $this->get('shopware_storefront.context_service')->getShopContext();
842
843
        /** @var Shopware\Bundle\StoreFrontBundle\Struct\Shop $shop */
844
        $shop = $context->getShop();
845
846
        /** @var Shopware\Bundle\AccountBundle\Service\RegisterServiceInterface $registerService */
847
        $registerService = $this->get('shopware_account.register_service');
848
        $data['birthdate'] = $data['billing']['birthyear'].'-'.$data['billing']['birthmonth'].'-'.$data['billing']['birthday'];
849
        $customer->setBirthday($data['birthdate']);
850
        $registerService->register($shop, $customer, $billingaddress, $shippingaddress);
851
852
        // get updated password; it is md5 randomized after register
853
        $getUser = Shopware()->Models()->getRepository('Shopware\Models\Customer\Customer')->findOneBy(
854
		array('email' =>  $data['auth']['email'])
855
		);
856
857
       $data['auth']['password']= $getUser->getPassword();
858
       $data['auth']['passwordMD5']= $getUser->getPassword();
859
       $data['auth']['encoderName'] = 'md5';
860
       return $data;
861
    }
862
863
864
    /**
865
     * Endpoint for changing the main profile data
866
     */
867
    public function updateCustomer($data, $userId)
868
    {
869
        $data['birthdate'] = $data['billing']['birthyear'].'-'.$data['billing']['birthmonth'].'-'.$data['billing']['birthday'];
870
        $data['birthday'] = $data['birthdate'];    
871
        $data['email'] = $data['auth']['email'];
872
        $data['firstname'] = $data['billing']['firstname'];
873
        $data['lastname'] = $data['billing']['lastname'];
874
        unset ($data['shipping']);
875
        unset ($data['billing']);        
876
877
        $customer = Shopware()->Models()->getRepository('Shopware\Models\Customer\Customer')->findOneBy(
878
		array('id' =>  $userId)
879
		);
880
        $customer->fromArray($data);
881
        Shopware()->Container()->get('shopware_account.customer_service')->update($customer);
882
    }
883
884
885
     /**
886
     * Updates the shipping address
887
     *
888
     * @param int $userId
889
     * @param array $shippingData
890
     */
891
    private function updateShipping($userId, $shippingData)
892
    {
893
        /** @var \Shopware\Components\Model\ModelManager $em */
894
        $em = $this->get('models');
895
896
        /** @var \Shopware\Models\Customer\Customer $customer */
897
        $customer = $em->getRepository('Shopware\Models\Customer\Customer')->findOneBy(array('id' => $userId));
898
899
        /** @var \Shopware\Models\Customer\Address $address */
900
        $addressold = $customer->getDefaultShippingAddress();
901
        $address = new \Shopware\Models\Customer\Address();
902
        
903
         /** @var \Shopware\Models\Country\Country $country */
904
        $country = $addressold->getCountry();
905
        $shippingData['country'] = $country;
906
        if ($shippingData['phone'] === null) {
907
            $shippingData['phone'] = ' ';
908
        }
909
        $address->fromArray($shippingData);
910
        try {
911
            $addressService = $this->get('shopware_account.address_service');
912
            $addressService->create($address, $customer);
913
            $addressService->setDefaultShippingAddress($address);
914
        } catch (Exception $ex) {
915
            $this->klarnaLog("ERROR while creating address via address service. Exception information:".$ex->getMessage(),1);
916
        }
917
        
918
    }
919
920
    /**
921
     * Updates the billing address
922
     *
923
     * @param int $userId
924
     * @param array $billingData
925
     */
926
    private function updateBilling($userId, $billingData)
927
    {
928
        /** @var \Shopware\Components\Model\ModelManager $em */
929
        $em = $this->get('models');
930
931
        /** @var \Shopware\Models\Customer\Customer $customer */
932
        $customer = $em->getRepository('Shopware\Models\Customer\Customer')->findOneBy(array('id' => $userId));
933
934
        /** @var \Shopware\Models\Customer\Address $address */
935
        $address = $customer->getDefaultBillingAddress();
936
        
937
         /** @var \Shopware\Models\Country\Country $country */
938
        $country = $address->getCountry();
939
        $billingData['country'] = $country;
940
        $address->fromArray($billingData);
941
942
        $this->get('shopware_account.address_service')->update($address);
943
    }
944
945
946
    /**
947
     * Needed to reset the session when the user logs in
948
     */
949
    public function loginAction()
950
    {
951
     //   Shopware()->Session()->offsetSet('KlarnaOrder', null);
0 ignored issues
show
Unused Code Comprehensibility introduced by
71% 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...
952
        $this->redirect(array('controller' => 'payment_klarna', 'action' => 'showIframe'));
953
    }
954
955
    /**
956
     * Return action method
957
     *
958
     * Reads the transactionResult and represents it for the customer.
959
     */
960
    public function returnAction()
961
    {
962
963
        $this->plugin = $this->get('plugins')->Frontend()->SwagPaymentKlarna();
964
        $this->config = $this->plugin->Config();
965
966
        $this->plugin->klarnaLog("Entering Shopware_Controllers_Frontend_PaymentKlarna::returnAction",3);
967
        $transactionId = $this->Request()->getParam('transactionId');
968
        $connector = $this->plugin->getConnector();
969
970
        $order = new Klarna_Checkout_Order($connector, $transactionId);
971
        $this->plugin->klarnaLog("Entering Shopware_Controllers_Frontend_PaymentKlarna::returnAction->transactionId:\n".$transactionId,3);
972
        $this->plugin->klarnaLog("Entering Shopware_Controllers_Frontend_PaymentKlarna::returnAction->order:",4, $order);
973
        $orderNumber = '';
974
        $session = Shopware()->Session();
975
976
        // set payment to Klarna Checkout Dangerous??
977
        $session['sPaymentID'] = $this->plugin->getPayment()->getId();
978
979
        try {
980
            $order->fetch();
981
982
            // if already created by pushaction just redirect
983
984
            if ($order['status'] === 'created'){
985
                $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::returnAction: OrderStatus is already created... nothing to do: " .$orderNumber,1);
986
                $this->redirect(array(
987
                    'controller' => 'payment_klarna',
988
                    'action' => 'finish',
989
                    'sUniqueID' => $order['reference']
990
                ));
991
            }
992
993
            $this->createAccount($order);
994
            // After createAccount update PaymentId to Klarna, could be defaultpayment
995
            $this->plugin->savePayment($this->plugin->getPayment()->getId());
996
            Shopware()->Session()->sOrderVariables['sUserData'] = $this->getUserData();
997
998 View Code Duplication
            if ($order['status'] == 'checkout_complete') {
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...
999
                $this->plugin->klarnaLog("Entering Shopware_Controllers_Frontend_PaymentKlarna::returnAction: checkout_complete. Save oder if session values match.",3);
1000
             if (Shopware()->Session()->offsetGet('KlarnaTransactionId') == null){
1001
                    $this->plugin->klarnaLog("Entering Shopware_Controllers_Frontend_PaymentKlarna::returnAction: Session matches. Order will be saved",3);
1002
                    Shopware()->Session()->offsetSet('KlarnaTransactionId', $transactionId );
1003
                    $orderNumber = $this->saveOrder(
1004
                        $order['reservation'],
1005
                        $order['reference']
1006
                    );
1007
                     Shopware()->Session()->offsetSet('KlarnaTransactionId', null );
1008
                }
1009
            }
1010
1011
1012 View Code Duplication
            if (empty($orderNumber) && !empty($order['merchant_reference']['orderid1'])) {
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...
1013
                $orderNumber = $order['merchant_reference']['orderid1'];
1014
            }
1015
1016 View Code Duplication
            if (!empty($orderNumber)){
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...
1017
                $update = array();
1018
1019
                $update['status'] = 'created';
1020
                $update['merchant_reference'] = array(
1021
                    'orderid1' => (string)$orderNumber,
1022
                    'orderid2' => (string)$order['reference']
1023
                );
1024
                $order->update($update);
1025
            }
1026
           
1027
            // Saves postnumber for dhl packstation
1028
            if (!empty($orderNumber)
1029
                && !empty($order['shipping_address']['care_of'])
1030
                && $order['shipping_address']['street_name'] == 'Packstation'
1031
                && $this->config->get('postnumberField')
1032
            ) {
1033
                $field = $this->config->get('postnumberField');
1034
                $value = $order['shipping_address']['care_of'];
1035
                $this->saveOrderAttribute($orderNumber, $field, $value);
1036
            }
1037
1038
            $session['KlarnaOrder'] = $order->getLocation();
1039
1040
            if ($order['status'] == 'created' || $order['status'] == 'checkout_complete') {
1041
                $this->saveOrderAttribute($orderNumber, 'swag_klarna_status', 'created');
1042
                $this->savePaymentStatus(
1043
                                $order['reservation'],
1044
                                $order['reference'],
1045
                                $this->config->get('statusId')
1046
                            );                
1047
                $this->redirect(array(
1048
                    'controller' => 'payment_klarna',
1049
                    'action' => 'finish',
1050
                    'sUniqueID' => $order['reference']
1051
                ));
1052
            } else {
1053
                $this->redirect(array('controller' => 'checkout', 'action' => 'confirm'));
1054
            }
1055
        } catch (Exception $e) {
1056
            Shopware()->Plugins()->Controller()->ViewRenderer()->setNoRender();
1057
            $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::returnAction: Catch. Searching for Order:",3);   
1058
            $this->checkKlarnaOrderExistsByReservation($order['reservation']);
1059
            $this->checkKlarnaOrderExistsByReference($order['reference']);
1060
            $this->checkKlarnaOrderExistsBySession(Shopware()->Session()->sUserId); 
1061
            $this->checkKlarnaOrderDetailsBySession(Shopware()->Session()->sUserId); 
1062
            echo "Entschuldigung, Ein Verbindungsfehler ist aufgetreten, bitte aktualisieren Sie die Seite";
1063
            echo $e->getMessage();
1064
1065
        }            
1066
    }
1067
    
1068
    /**
1069
     * Method checks if certain klarna order exists or not
1070
     * 
1071
     * @param string $sessionID
1072
     * @return bool
1073
     */
1074 View Code Duplication
    protected function checkKlarnaOrderExistsBySession($sessionID) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1075
        $sql = '
1076
            SELECT * FROM s_order
1077
            WHERE userID=?
1078
        ';
1079
        
1080
        $order = Shopware()->Db()->fetchAll($sql, array(
1081
                $sessionID
1082
        ));
1083
        
1084
        $orderExists = (empty($order)) ? false : true;
1085
        $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::checkKlarnaOrderExistsBySession:",3);   
1086
        if ($orderExists){
1087
            $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::checkKlarnaOrderExistsBySession: Order Found: ",3, $order);   
1088
        }
1089
        return $orderExists;
1090
    }    
1091
    
1092
    /**
1093
     * Method checks if certain klarna order exists or not
1094
     * 
1095
     * @param string $transactionId
0 ignored issues
show
Bug introduced by
There is no parameter named $transactionId. 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...
1096
     * @param string $paymentUniqueId
1097
     * @return bool
1098
     */
1099 View Code Duplication
    protected function checkKlarnaOrderExistsByReference($paymentUniqueId) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1100
        $sql = '
1101
            SELECT * FROM s_order
1102
            WHERE temporaryID=?
1103
        ';
1104
        
1105
        $order = Shopware()->Db()->fetchAll($sql, array(
1106
                $paymentUniqueId
1107
        ));
1108
        
1109
        $orderExists = (empty($order)) ? false : true;
1110
        $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::checkKlarnaOrderExistsByReference:",3);   
1111
        if ($orderExists){
1112
            $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::checkKlarnaOrderExistsByReference: Order Found: ",3, $order);   
1113
        }
1114
        return $orderExists;
1115
    }
1116
    
1117
    /**
1118
     * Method checks if certain klarna order exists or not
1119
     * 
1120
     * @param string $transactionId
1121
     * @param string $paymentUniqueId
0 ignored issues
show
Bug introduced by
There is no parameter named $paymentUniqueId. 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...
1122
     * @return bool
1123
     */
1124 View Code Duplication
    protected function checkKlarnaOrderExistsByReservation($transactionId) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1125
        $sql = '
1126
            SELECT * FROM s_order
1127
            WHERE transactionID=?
1128
        ';
1129
        
1130
        $order = Shopware()->Db()->fetchAll($sql, array(
1131
                $transactionId
1132
        ));
1133
        
1134
        $orderExists = (empty($order)) ? false : true;
1135
        $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::checkKlarnaOrderExistsByReservation:",3);   
1136
        if ($orderExists){
1137
            $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::checkKlarnaOrderExistsByReservation: Order Found: ",3, $order);   
1138
        }
1139
        return $orderExists;
1140
    }    
1141
    
1142
    /**
1143
     * Method checks if certain klarna order exists or not
1144
     * 
1145
     * @param string $transactionId
1146
     * @param string $paymentUniqueId
1147
     * @param string $userId
1148
     * @return bool
1149
     */
1150
    protected function checkKlarnaOrderExists($transactionId, $paymentUniqueId, $userId) {
1151
        $sql = '
1152
            SELECT ordernumber FROM s_order
1153
            WHERE transactionID=? AND temporaryID=?
1154
            AND status!=-1 AND userID=?
1155
        ';
1156
        
1157
        $orderNumber = Shopware()->Db()->fetchOne($sql, array(
1158
                $transactionId,
1159
                $paymentUniqueId,
1160
                $userId
1161
        ));
1162
        
1163
        $orderExists = (empty($orderNumber)) ? false : true;
1164
        
1165
        return $orderExists;
1166
    }
1167
    
1168
    /**
1169
     * Method checks if certain klarna order exists or not
1170
     * 
1171
     * @param string $sessionID
1172
     * @return bool
1173
     */
1174 View Code Duplication
    protected function checkKlarnaOrderDetailsBySession($sessionID) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1175
        $sql = '
1176
            SELECT * FROM s_order
1177
            LEFT JOIN s_order_details ON s_order.id = s_order_details.orderID
1178
            WHERE userID=?
1179
        ';
1180
        
1181
        $orderDetails = Shopware()->Db()->fetchAll($sql, array(
1182
                $sessionID
1183
        ));
1184
        
1185
        $orderExists = (empty($orderDetails)) ? false : true;
1186
        $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::checkKlarnaOrderDetailsBySession:",3);   
1187
        if ($orderExists){
1188
            $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::checkKlarnaOrderDetailsBySession: OrderDetails Found: ",3, $orderDetails);
1189
        }
1190
        return $orderExists;
1191
    }
1192
    
1193
    /**
1194
     * Method checks if certain klarna order exists or not
1195
     * 
1196
     * @param string $paymentUniqueId
1197
     * @return string
1198
     */
1199
    protected function getUserIdByReference($paymentUniqueId) {
1200
        $sql = '
1201
            SELECT userID FROM s_order
1202
            WHERE temporaryID=?
1203
        ';
1204
        
1205
        $userId = Shopware()->Db()->fetchOne($sql, array(
1206
                $paymentUniqueId
1207
        ));
1208
1209
        return $userId;
1210
    }    
1211
    
1212
    /**
1213
     *
1214
     *
1215
     * @param string $transactionId
1216
     * @param string $paymentUniqueId
1217
     * @param string $userId
1218
     * @return string $orderNumber
1219
     */
1220 View Code Duplication
    protected function getKlarnaOrderNumber($transactionId, $paymentUniqueId, $userId) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1221
        $sql = '
1222
            SELECT ordernumber FROM s_order
1223
            WHERE transactionID=? AND temporaryID=?
1224
            AND status!=-1 AND userID=?
1225
        ';
1226
1227
        $orderNumber = Shopware()->Db()->fetchOne($sql, array(
1228
            $transactionId,
1229
            $paymentUniqueId,
1230
            $userId
1231
        ));
1232
1233
        return $orderNumber;
1234
    }
1235
1236
    /**
1237
     *
1238
     *
1239
     * @param string $transactionId
1240
     * @param string $paymentUniqueId
1241
     * @param string $userId
1242
     * @return string $orderId
1243
     */
1244 View Code Duplication
    protected function getKlarnaOrderId($transactionId, $paymentUniqueId, $userId) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1245
        $sql = '
1246
            SELECT id FROM s_order
1247
            WHERE transactionID=? AND temporaryID=?
1248
            AND status!=-1 AND userID=?
1249
        ';
1250
1251
        $orderId = Shopware()->Db()->fetchOne($sql, array(
1252
            $transactionId,
1253
            $paymentUniqueId,
1254
            $userId
1255
        ));
1256
1257
        return $orderId;
1258
    }
1259
1260
1261
    /**
1262
     * Notify action method
1263
     */
1264
    public function pushAction()
1265
    {
1266
        $this->plugin = $this->get('plugins')->Frontend()->SwagPaymentKlarna();
1267
        $this->config = $this->plugin->Config();
1268
        $transactionId = $this->Request()->getParam('transactionId');
1269
1270
        $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::pushAction->transactionId:\n".$transactionId,3);
1271
        $connector = $this->plugin->getConnector();
1272
        $order = new Klarna_Checkout_Order($connector, $transactionId);
1273
1274
        $order->fetch();
1275
1276
        if ($order['status'] === 'created'){
1277
            $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::pushAction: OrderStatus is already created... nothing to do: ",1);
1278
            return;
1279
        }
1280
1281
        $this->createAccount($order);
1282
        // After createAccount update PaymentId to Klarna, could be defaultpayment
1283
        $this->plugin->savePayment($this->plugin->getPayment()->getId());
1284
        Shopware()->Session()->sOrderVariables['sUserData'] = $this->getUserData();
1285
1286 View Code Duplication
        if ($order['status'] == 'checkout_complete') {
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...
1287
            $this->plugin->klarnaLog("Entering Shopware_Controllers_Frontend_PaymentKlarna::returnAction: checkout_complete. Save oder if session values match.",3);
1288
            if (Shopware()->Session()->offsetGet('KlarnaTransactionId') == null){
1289
                $this->plugin->klarnaLog("Entering Shopware_Controllers_Frontend_PaymentKlarna::returnAction: Session matches. Order will be saved",3);
1290
                Shopware()->Session()->offsetSet('KlarnaTransactionId', $transactionId );
1291
                $orderNumber = $this->saveOrder(
1292
                    $order['reservation'],
1293
                    $order['reference']
1294
                );
1295
                Shopware()->Session()->offsetSet('KlarnaTransactionId', null );
1296
            }
1297
        }
1298
1299 View Code Duplication
        if (empty($orderNumber) && !empty($order['merchant_reference']['orderid1'])) {
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...
1300
            $orderNumber = $order['merchant_reference']['orderid1'];
1301
        }
1302
1303 View Code Duplication
        if (!empty($orderNumber)){
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...
1304
            $update = array();
1305
1306
            $update['status'] = 'created';
1307
            $update['merchant_reference'] = array(
1308
                'orderid1' => (string)$orderNumber,
1309
                'orderid2' => (string)$order['reference']
1310
            );
1311
            $order->update($update);
1312
        }
1313
1314
        $this->savePaymentStatus(
1315
            $order['reservation'],
1316
            $order['reference'],
1317
            $this->config->get('statusId')
1318
        );
1319
    }
1320
1321
    private function saveOrderAttribute($orderNumber, $field, $value)
1322
    {
1323
        try {
1324
            $sql = "
1325
                INSERT INTO s_order_attributes (orderID, `$field`)
1326
                SELECT id, ? FROM s_order WHERE ordernumber = ?
1327
                ON DUPLICATE KEY UPDATE `$field` = VALUES(`$field`)
1328
            ";
1329
            $this->get('db')->query($sql, array(
1330
                $value,
1331
                $orderNumber
1332
            ));
1333
        } catch (Exception $e) {
1334
            $this->plugin->klarnaLog("PROBLEM SAVING ORDER ATTRIBUTES AFTER KLARNA PUSH!:\n".$e->getMessage(),1);
1335
        }
1336
    }
1337
1338
    /**
1339
     * Save register form so we can use it if user change between klarna and register tab
1340
     */
1341
    public function saveFormDataAction()
1342
    {
1343
        $form = $this->Request()->getPost();
1344
1345
        //unset password from passed post
1346
        unset($form['register']['personal']['password']);
1347
1348
        if (!empty($form)) {
1349
            Shopware()->Session()->klarnaSavedRegister = $form;
1350
        }
1351
    }
1352
1353
    /**
1354
     * Helper method to redirect the request to the proper page to set the payment into the customer account
1355
     */
1356
    public function setPaymentAction()
1357
    {
1358
        if ($this->Request()->isPost()) {
1359
            $values = $this->Request()->getPost('register');
1360
            $payment = $values['payment'];
1361
        } else {
1362
            $payment = $this->Request()->getParam('paymentId');
1363
        }
1364
1365
        if (empty($payment)) {
1366
            return;
1367
        }
1368
        $this->plugin = $this->get('plugins')->Frontend()->SwagPaymentKlarna();
1369
        $session = Shopware()->Session();
1370
        $session['KlarnaExternalPaymentId'] = $payment;
1371
1372
        $user = Shopware()->Modules()->Admin()->sGetUserData();
1373
        if (empty($user)) {
1374
1375
            $session->offsetSet('sPaymentID', $payment);
0 ignored issues
show
Bug introduced by
The method offsetSet cannot be called on $session (of type array<string,?,{"KlarnaExternalPaymentId":"?"}>).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
1376
            $session->offsetUnset('sUserId');
0 ignored issues
show
Bug introduced by
The method offsetUnset cannot be called on $session (of type array<string,?,{"KlarnaExternalPaymentId":"?"}>).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
1377
            $session->offsetSet('sRegisterFinished', false);
0 ignored issues
show
Bug introduced by
The method offsetSet cannot be called on $session (of type array<string,?,{"KlarnaExternalPaymentId":"?"}>).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
1378
1379
            $this->redirect(
1380
                array(
1381
                    'controller' => 'register',
1382
                    'action' => 'index',
1383
                    'sTarget' => 'checkout',
1384
                    'sTargetAction' => 'confirm'
1385
                )
1386
            );
1387
        } else {
1388
            $this->plugin->savePayment($payment);
1389
            $this->redirect(
1390
                array(
1391
                    'controller' => 'checkout',
1392
                    'action' => 'confirm'
1393
                )
1394
            );
1395
        }
1396
    }
1397
1398
    /**
1399
     * This action is called when the user is not logged in and tries to change the payment from klarna to another payment.
1400
     * Only used in responsive theme.
1401
     */
1402
    public function otherPaymentAction()
1403
    {
1404
        $userData = Shopware()->Modules()->Admin()->sGetUserData();
1405
        $session = Shopware()->Session();
1406
1407
        // reset country
1408
        $session['sCountry'] = $userData['additional']['country']['id'];
1409
        unset($session['sChangedCountry']);
1410
1411
        //Register-controller redirects to checkout by default when the user is logged in already.
1412
        /*        $this->redirect(array(
0 ignored issues
show
Unused Code Comprehensibility introduced by
60% 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...
1413
                    'controller' => 'checkout',
1414
                    'action' => 'shippingPayment',
1415
                    'klarnaRedirect' => 1
1416
                    //'sTarget' => 'checkout',
1417
                    //'sTargetAction' => 'shippingPayment'
1418
                ));
1419
*/
1420
        if ($this->isUserLoggedIn()) {
1421
            $this->redirect(array(
1422
                'controller' => 'checkout',
1423
                'klarnaRedirect' => 1,
1424
                'action' => 'shippingPayment',
1425
                'sTarget' => 'checkout'
1426
            ));
1427
1428
        } else {
1429
            $this->redirect(array(
1430
                'controller' => 'register',
1431
                'klarnaRedirect' => 1,
1432
                'sTarget' => 'checkout',
1433
                'sTargetAction' => 'shippingPayment'
1434
            ));
1435
        }
1436
    }
1437
1438
    protected function isUserLoggedIn()
1439
    {        
1440
         return (isset($this->session->sUserId) && !empty($this->session->sUserId));
1441
    }
1442
1443
    /**
1444
     * Get complete user-data as an array to use in view
1445
     *
1446
     * @return array
1447
     */
1448
    public function getUserData()
1449
    {
1450
        $system = Shopware()->System();
1451
        $admin = Shopware()->Modules()->Admin();
1452
        $userData = $admin->sGetUserData();
1453
        if (!empty($userData['additional']['countryShipping'])) {
1454
            $system->sUSERGROUPDATA = Shopware()->Db()->fetchRow("
1455
                SELECT * FROM s_core_customergroups
1456
                WHERE groupkey = ?
1457
            ", array($system->sUSERGROUP));
1458
1459
            if ($this->isTaxFreeDelivery($userData)) {
1460
                $system->sUSERGROUPDATA['tax'] = 0;
1461
                $system->sCONFIG['sARTICLESOUTPUTNETTO'] = 1; //Old template
1462
                Shopware()->Session()->sUserGroupData = $system->sUSERGROUPDATA;
1463
                $userData['additional']['charge_vat'] = false;
1464
                $userData['additional']['show_net'] = false;
1465
                Shopware()->Session()->sOutputNet = true;
1466
            } else {
1467
                $userData['additional']['charge_vat'] = true;
1468
                $userData['additional']['show_net'] = !empty($system->sUSERGROUPDATA['tax']);
1469
                Shopware()->Session()->sOutputNet = empty($system->sUSERGROUPDATA['tax']);
1470
            }
1471
        }
1472
1473
        return $userData;
1474
    }
1475
1476
    /**
1477
     * Validates if the provided customer should get a tax free delivery
1478
     * @param array $userData
1479
     * @return bool
1480
     */
1481
    protected function isTaxFreeDelivery($userData)
1482
    {
1483
        if (!empty($userData['additional']['countryShipping']['taxfree'])) {
1484
            return true;
1485
        }
1486
1487
        if (empty($userData['additional']['countryShipping']['taxfree_ustid'])) {
1488
            return false;
1489
        }
1490
1491
        return !empty($userData['shippingaddress']['ustid']);
1492
    }
1493
}
1494
1495
1496