Cart.php 87.6 KB
Newer Older
1 2
<?php
// Dobrado Content Management System
3
// Copyright (C) 2018 Malcolm Blaney
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

class Cart extends Base {

  public function Add($id) {

  }

  public function Callback() {
25
    $us_action = isset($_POST['action']) ? $_POST['action'] : '';
26 27
    if ($us_action === 'item') return $this->DisplayItem();
    if ($us_action === 'checkout') return $this->Checkout();
28
    if ($us_action === 'list') {
29 30
      if ($this->user->canEditPage) return $this->ShowSettings();
      return ['error' => 'You don\'t have permission to list cart settings.'];
31
    }
32 33 34
    if ($us_action === 'saveItem') {
      if ($this->user->canEditPage) return $this->SaveItem();
      return ['error' => 'You don\'t have permission to edit cart items.'];
35
    }
36 37 38
    if ($us_action === 'saveShipping') {
      if ($this->user->canEditPage) return $this->SaveShipping();
      return ['error' => 'You don\'t have permission to edit cart shipping.'];
39
    }
40 41 42
    if ($us_action === 'saveCheckout') {
      if ($this->user->canEditPage) return $this->SaveCheckout();
      return ['error' => 'You don\'t have permission to edit cart checkout.'];
43
    }
44 45 46
    if ($us_action === 'removeItem') {
      if ($this->user->canEditPage) return $this->RemoveItem();
      return ['error' => 'You don\'t have permission to remove cart items.'];
47
    }
48 49 50 51 52 53 54
    if ($us_action === 'removeShipping') {
      if ($this->user->canEditPage) return $this->RemoveShipping();
      return ['error' => 'You don\'t have permission to remove cart shipping.'];
    }
    if ($us_action === 'resetItem') {
      if ($this->user->canEditPage) return $this->ResetItem();
      return ['error' => 'You don\'t have permission to reset cart items.'];
55
    }
56
    if ($us_action === 'paymentDone') {
57 58
      // This allows the page to refresh without the query string added by
      // the payment gateway.
59
      return ['location' => $this->Url()];
60
    }
61
    return ['error' => 'Unknown action.'];
62 63 64 65
  }

  public function CanAdd($page) {
    // Can only have one cart module on a page.
66
    return !$this->AlreadyOnPage('cart', $page);
67 68 69 70 71 72 73 74 75 76 77
  }

  public function CanEdit($id) {
    return false;
  }

  public function CanRemove($id) {
    return true;
  }

  public function Content($id) {
78
    $items = '';
79 80 81
    $content = $this->CompleteOrder() .
      '<div id="cart-total"></div>' .
      '<button id="cart-checkout">checkout</button><br>' .
82 83 84 85
      '<form id="cart-form">';
    $tabs = '';
    $prev_tab = '';
    $show_tabs = false;
86
    $tab_names = $this->Substitute('cart-tabs-' . $this->user->page);
87
    if (strpos($tab_names, ',') !== false) {
88
      $tabs .= '<div id="cart-tabs"><ul>';
89 90
      foreach (explode(',', $tab_names) as $current_tab) {
        $tab_id = preg_replace('/[^a-z0-9_-]/', '-', strtolower($current_tab));
91
        $tabs .= '<li><a href="#cart-tab-' . $tab_id . '">' . $current_tab .
92 93 94
          '</a></li>';
      }
      $tabs .= '</ul>';
95 96
      $show_tabs = true;
    }
97

98 99 100 101 102 103
    $tracking = [];
    if ($this->user->loggedIn) {
      $banking = new Module($this->user, $this->owner, 'banking');
      $buyer_group = $banking->Factory('BuyerGroup');
      $tracking = $this->Tracking($buyer_group);
    }
104
    $mysqli = connect_db();
105 106 107 108 109 110
    $query = 'SELECT cart_items.name, image, short, full, price, variable, ' .
      'minimum, download, tab FROM cart_items LEFT JOIN cart_item_page ON ' .
      'cart_items.user = cart_item_page.user AND ' .
      'cart_items.name = cart_item_page.name WHERE ' .
      'cart_items.user = "' . $this->owner . '" AND available = 1 AND ' .
      'page = "' . $this->user->page . '" ORDER BY tab, item_order';
111
    if ($result = $mysqli->query($query)) {
112 113
      $price_text = $this->Substitute('cart-price-text');
      $quantity_text = $this->Substitute('cart-quantity-text');
114
      while ($cart_items = $result->fetch_assoc()) {
115
        if ($show_tabs) {
116 117 118 119 120
          $current_tab = strtolower($cart_items['tab']);
          if ($current_tab !== $prev_tab) {
            // Close the previous tab before creating the next one.
            if ($items !== '') $items .= '</div>';
            $tab_id = preg_replace('/[^a-z0-9_-]/', '-', $current_tab);
121
            $items .= '<div id="cart-tab-' . $tab_id . '">';
122
            $prev_tab = $current_tab;
123 124
          }
        }
125 126 127
        if (isset($tracking[$cart_items['name']])) {
          $cart_items['price'] = $tracking[$cart_items['name']]['price'];
        }
128
        $items .= $this->FormatItem($cart_items, $price_text, $quantity_text);
129 130 131 132
      }
      $result->close();
    }
    else {
133
      $this->Log('Cart->Content 1: ' . $mysqli->error);
134
    }
135
    $mysqli->close();
136

137 138 139 140
    $description = '';
    $label = $this->Substitute('cart-description-label');
    $input = $this->Substitute('cart-description-input');
    if ($label !== '' && $input !== '') {
141 142 143
      $description = '<div class="form-spacing hidden">' .
        '<label for="customer-detail-description">' . $label . '</label>' .
        $input . '</div>';
144
    }
145 146
    // The first closing tag is for the last tab, the second is for #cart-tabs.
    if ($show_tabs) $items .= '</div></div>';
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
    $content .= $tabs . $items . '</form>' .
      '<div id="cart-item-dialog"></div>' .
      '<div id="cart-checkout-dialog" class="hidden">' .
        '<div id="cart-summary"></div>' .
        '<button id="cart-confirm-button">confirm</button>' .
        '<button id="cart-continue-button">continue shopping</button>' .
        '<div id="cart-checkout-message"></div>' .
        '<form id="cart-customer-details-form">' .
          '<div class="form-spacing">' .
            '<label for="customer-detail-first">First Name:</label>' .
            '<input id="customer-detail-first" type="text" maxlength="32">' .
          '</div>' .
          '<div class="form-spacing">' .
            '<label for="customer-detail-last">Last Name:</label>' .
            '<input id="customer-detail-last" type="text" maxlength="64">' .
          '</div>' .
          '<div class="form-spacing">' .
            '<label for="customer-detail-email">Email:</label>' .
            '<input id="customer-detail-email" type="text" maxlength="100">' .
          '</div>' .
          '<div class="form-spacing">' .
            '<label for="customer-detail-address">Address:</label>' .
            '<input id="customer-detail-address" type="text" maxlength="100">' .
          '</div>' .
          '<div class="form-spacing">' .
            '<label for="customer-detail-postcode">Postcode:</label>' .
            '<input id="customer-detail-postcode" type="text" maxlength="32">' .
          '</div>' .
          '<div class="form-spacing">' .
            '<label for="customer-detail-city">City:</label>' .
            '<input id="customer-detail-city" type="text" maxlength="100">' .
          '</div>' .
          '<div class="form-spacing">' .
            '<label for="customer-detail-state">State:</label>' .
            '<input id="customer-detail-state" type="text" maxlength="100">' .
          '</div>' .
          '<div class="form-spacing">' .
            '<label for="customer-detail-country">Country:</label>' .
            '<input id="customer-detail-country" type="text" maxlength="50" ' .
              'value="' . $this->Substitute('cart-default-country') . '">' .
          '</div>' .
          '<div class="form-spacing">' .
            $this->PaymentMethods() .
          '</div>' .
          $description .
          '<button id="customer-detail-submit">Submit Details</button>' .
          '<div id="cart-checkout-info"></div>' .
        '</form>' .
195
      '</div>';
196
    $edit = '<br>';
197
    if ($this->user->canEditPage) {
198
      $edit = '<button id="cart-edit-button"></button>' .
199 200
        '<div id="cart-editor"></div>';
    }
201
    $cart_title = $this->Substitute('cart-title');
202
    return '<div id="cart-title">' . $cart_title . $edit . '</div>' . $content;
203 204
  }

205
  public function Copy($id, $new_page, $old_owner, $old_id) {
206 207 208

  }

209 210 211 212
  public function Cron() {

  }

213
  public function Factory($fn, $p = NULL) {
214
    if (is_array($p)) {
215 216
      $count = count($p);
      if ($fn === 'Payment' && $count === 12) {
217 218 219 220 221 222 223 224 225 226
        $items = $p[0];
        $amount = $p[1];
        $first = $p[2];
        $last = $p[3];
        $email = $p[4];
        $address = $p[5];
        $city = $p[6];
        $postcode = $p[7];
        $state = $p[8];
        $country = $p[9];
227
        $description = $p[10];
228
        $method = $p[11];
229
        return $this->Payment($items, $amount, $first, $last, $email, $address,
230 231
                              $city, $postcode, $state, $country, $description,
                              $method);
232
      }
233
      if ($fn === 'PaymentMethods' && $count === 2) {
234 235 236 237
        $display_cash = $p[0];
        $id = $p[1];
        return $this->PaymentMethods($display_cash, $id);
      }
238 239 240 241 242 243 244 245 246 247 248 249 250
      if ($fn === 'UpdateItem' && $count >= 8) {
        $product = $p[0];
        $supplier = $p[1];
        $image = $p[2];
        $short = $p[3];
        $full = $p[4];
        $price = $p[5];
        $available = $p[6];
        $category = $p[7];
        $old_name = $count === 9 ? $p[8] : '';
        return $this->UpdateItem($product, $supplier, $image, $short, $full,
                                 $price, $available, $category, $old_name);
      }
251 252
      return;
    }
253
    if ($fn === 'Gateway') {
254 255
      return $this->Gateway($p);
    }
256
    if ($fn === 'ProcessingCost') {
257 258
      return $this->ProcessingCost($p);
    }
259 260
  }

261 262 263 264 265 266 267 268 269 270
  public function Group() {

  }

  public function IncludeScript() {
    return true;
  }

  public function Install($path) {
    // Append dobrado.cart.js to the existing dobrado.js file.
271
    $this->AppendScript($path, 'dobrado.cart.js');
272
    $mysqli = connect_db();
273 274 275 276 277 278 279 280 281 282 283 284
    $query = 'CREATE TABLE IF NOT EXISTS cart_items (' .
      'user VARCHAR(50) NOT NULL,' .
      'name VARCHAR(100) NOT NULL,' .
      'image VARCHAR(200),' .
      'short TEXT,' .
      'full TEXT,' .
      'weight DECIMAL(8,2),' .
      'price DECIMAL(8,2),' .
      'variable TINYINT(1),' .
      'minimum DECIMAL(8,2),' .
      'download VARCHAR(200),' .
      'PRIMARY KEY(user, name)' .
285 286
      ') ENGINE=MyISAM';
    if (!$mysqli->query($query)) {
287
      $this->Log('Cart->Install 1: ' . $mysqli->error);
288
    }
289 290 291 292 293 294 295 296
    $query = 'CREATE TABLE IF NOT EXISTS cart_item_page (' .
      'user VARCHAR(50) NOT NULL,' .
      'name VARCHAR(100) NOT NULL,' .
      'page VARCHAR(200),' .
      'available TINYINT(1),' .
      'tab VARCHAR(100),' .
      'item_order INT UNSIGNED,' .
      'PRIMARY KEY(user, name, page(50))' .
297 298
      ') ENGINE=MyISAM';
    if (!$mysqli->query($query)) {
299
      $this->Log('Cart->Install 2: ' . $mysqli->error);
300
    }
301 302 303 304 305 306 307 308 309 310 311
    $query = 'CREATE TABLE IF NOT EXISTS cart_tracking (' .
      'user VARCHAR(50) NOT NULL,' .
      'name VARCHAR(100) NOT NULL,' .
      'supplier VARCHAR(50) NOT NULL,' .
      'product VARCHAR(100) NOT NULL,' .
      'modified TINYINT(1),' .
      'PRIMARY KEY(user, name)' .
      ') ENGINE=MyISAM';
    if (!$mysqli->query($query)) {
      $this->Log('Cart->Install 3: ' . $mysqli->error);
    }
312 313 314 315 316 317 318 319 320 321 322
    $query = 'CREATE TABLE IF NOT EXISTS cart_shipping (' .
      'user VARCHAR(50) NOT NULL,' .
      'id INT UNSIGNED NOT NULL,' .
      'type VARCHAR(100) NOT NULL,' .
      'destination_name VARCHAR(100),' .
      'destination_code VARCHAR(4),' .
      'amount DECIMAL(8,2) NOT NULL,' .
      'minimum DECIMAL(8,2),' .
      'maximum DECIMAL(8,2),' .
      'rule ENUM("weight", "fixed", "percent") NOT NULL,' .
      'PRIMARY KEY(user, id)' .
323 324
      ') ENGINE=MyISAM';
    if (!$mysqli->query($query)) {
325
      $this->Log('Cart->Install 4: ' . $mysqli->error);
326
    }
327 328 329 330 331
    $query = 'CREATE TABLE IF NOT EXISTS cart_checkout (' .
      'user VARCHAR(50) NOT NULL,' .
      'email VARCHAR(200) NOT NULL,' .
      'currency VARCHAR(3) NOT NULL,' .
      'PRIMARY KEY(user)' .
332 333
      ') ENGINE=MyISAM';
    if (!$mysqli->query($query)) {
334
      $this->Log('Cart->Install 5: ' . $mysqli->error);
335
    }
336 337 338 339 340 341 342 343 344
    $query = 'CREATE TABLE IF NOT EXISTS cart_method (' .
      'user VARCHAR(50) NOT NULL,' .
      'name ENUM("credit", "paypal", "pickup") NOT NULL,' .
      'available TINYINT(1),' .
      'gateway ENUM("eway", "migs"),' .
      'gateway_api_key TEXT,' .
      'gateway_password VARCHAR(100),' .
      'fee DECIMAL(8,2),' .
      'PRIMARY KEY(user, name)' .
345 346
      ') ENGINE=MyISAM';
    if (!$mysqli->query($query)) {
347
      $this->Log('Cart->Install 6: ' . $mysqli->error);
348
    }
349 350 351 352 353 354 355 356 357
    $query = 'CREATE TABLE IF NOT EXISTS cart_order (' .
      'user VARCHAR(50) NOT NULL,' .
      'id INT UNSIGNED NOT NULL AUTO_INCREMENT,' .
      'email VARCHAR(200) NOT NULL,' .
      'description TEXT,' .
      'method ENUM("credit", "paypal", "pickup") NOT NULL,' .
      'timestamp INT(10) UNSIGNED NOT NULL,' .
      'completed INT(10) UNSIGNED,' .
      'PRIMARY KEY(user, id)' .
358 359
      ') ENGINE=MyISAM';
    if (!$mysqli->query($query)) {
360
      $this->Log('Cart->Install 7: ' . $mysqli->error);
361
    }
362
    $mysqli->close();
363

364 365 366
    $template = ['"cart-price-text","","Price:"',
                 '"cart-quantity-text","","Quantity:"',
                 '"cart-title","","Shopping Cart"',
367 368
                 '"cart-checkout","","Your order will be sent to:<br>' .
                   '!first !last<br>!address<br>!postcode<br>!city<br>' .
369
                   '!state<br>!country<br>"',
370
                 '"cart-display-item","","<h2>!name</h2><img src=\"!image\">' .
371 372 373 374
                   '<p>!price</p><p>!short</p><p>!full</p>"',
                 '"cart-price-comparison","","Retail: ' .
                   '<span class=\"cart-retail\">$!retail</span>, Wholesale: ' .
                   '<span class=\"cart-wholesale\">$!price</span>"',
375 376 377 378
                 '"cart-email","","To !first !last<br>Thanks for your order! ' .
                   'The following is a confirmation of your purchases and ' .
                   'contact details:<br><br>!items<br><b>Total: ' .
                   '$!amount</b><br><br>Email: !email<br>Address:<br>!address' .
379
                   '<br>!city<br>!postcode<br>!state<br>!country<br><br>"'];
380
    $this->AddTemplate($template);
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
    $description = ['cart-price-text' => 'The text before the price for ' .
                      'each item.',
                    'cart-quantity-text' => 'The text before the quantity ' .
                      'for each item.',
                    'cart-title' => 'The text for the title above the cart ' .
                      'items.',
                    'cart-checkout' => 'The text to display at checkout, ' .
                      'will substitute the following to show where items ' .
                      'will be sent: !first, !last, !address, !postcode, ' .
                      '!city, !state, !country, !description.',
                    'cart-email' => 'The full text of the email that will be ' .
                      'sent to the customer, confirming their order. It will ' .
                      'also be sent to the admin email address set in the ' .
                      'cart checkout settings. Substitutes: !items, !amount, ' .
                      '!first, !last, !email, !address, !postcode, !city, ' .
                      '!state, !country.',
                    'cart-description-label' => 'A label for the input ' .
                      'option set in the \'cart-description-input\' template.',
                    'cart-description-input' => 'A configurable input option ' .
                      'added to \'cart-customer-details-form\' to request ' .
                      'custom details.'];
    $this->AddTemplateDescription($description);
403

404 405
    $site_style = ['"","#cart-summary","margin-bottom","40px"',
                   '"","#cart-confirm-button","float","right"',
406
                   '"","#cart-customer-details-form","background-color",' .
407
                     '"#eeeeee"',
408
                   '"","#cart-customer-details-form","border",' .
409 410 411 412 413 414
                     '"1px solid #aaaaaa"',
                   '"","#cart-customer-details-form","border-radius","2px"',
                   '"","#cart-customer-details-form","padding","5px"',
                   '"","#cart-customer-details-form","margin","5px"',
                   '"","#cart-customer-details-form label","width","7em"',
                   '"","#customer-detail-submit","margin-left","7.3em"',
415
                   '"","#customer-detail-submit","margin-top","1em"',
416
                   '"","#cart-total-table","margin","10px"',
417
                   '"","#cart-total-table tr:last-child","font-weight","bold"',
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
                   '"","#cart-item-form","background-color","#eeeeee"',
                   '"","#cart-item-form","border","1px solid #aaaaaa"',
                   '"","#cart-item-form","border-radius","2px"',
                   '"","#cart-item-form","padding","5px"',
                   '"","#cart-item-form","margin","5px"',
                   '"","#cart-item-form label","width","10em"',
                   '"","#cart-shipping-form","background-color","#eeeeee"',
                   '"","#cart-shipping-form","border","1px solid #aaaaaa"',
                   '"","#cart-shipping-form","border-radius","2px"',
                   '"","#cart-shipping-form","padding","5px"',
                   '"","#cart-shipping-form","margin","5px"',
                   '"","#cart-shipping-form label","width","10em"',
                   '"","#cart-checkout-form","background-color","#eeeeee"',
                   '"","#cart-checkout-form","border","1px solid #aaaaaa"',
                   '"","#cart-checkout-form","border-radius","2px"',
                   '"","#cart-checkout-form","padding","5px"',
                   '"","#cart-checkout-form","margin","5px"',
                   '"","#cart-checkout-form label","width","10em"',
436 437 438
                   '"","#cart-migs-format","font-size","0.8em"',
                   '"","#cart-migs-format","font-style","italic"',
                   '"","#cart-migs-format","margin-left","13em"',
439
                   '"","#eway-form label","width","7em"',
440 441
                   '"","#eway-form button","margin-left","7.3em"',
                   '"",".cart-item .item-quantity","width","25px"',
442 443 444 445
                   '"",".cart-item label","margin-right","5px"',
                   '"",".cart-modified-info","margin-left","10em"',
                   '"",".cart-tracking","margin-left","10em"',
                   '"",".cart-tracking","font-style","italic"'];
446
    $this->AddSiteStyle($site_style);
447 448 449
  }

  public function Placement() {
450
    return 'middle';
451 452
  }

453 454 455 456
  public function Publish($id, $update) {

  }

457
  public function Remove($id) {
458 459 460
    // Return if Remove was called for a specific module,
    // only want to remove cart settings when deleting an account.
    if (isset($id)) return;
461

462
    $mysqli = connect_db();
463
    $query = 'DELETE FROM cart_items WHERE user = "' . $this->owner . '"';
464
    if (!$mysqli->query($query)) {
465
      $this->Log('Cart->Remove 1: ' . $mysqli->error);
466
    }
467
    $query = 'DELETE FROM cart_item_page WHERE user = "' . $this->owner . '"';
468
    if (!$mysqli->query($query)) {
469
      $this->Log('Cart->Remove 2: ' . $mysqli->error);
470
    }
471
    $query = 'DELETE FROM cart_shipping WHERE user = "' . $this->owner . '"';
472
    if (!$mysqli->query($query)) {
473
      $this->Log('Cart->Remove 3: ' . $mysqli->error);
474
    }
475
    $query = 'DELETE FROM cart_checkout WHERE user = "' . $this->owner . '"';
476
    if (!$mysqli->query($query)) {
477
      $this->Log('Cart->Remove 4: ' . $mysqli->error);
478
    }
479
    $query = 'DELETE FROM cart_method WHERE user = "' . $this->owner . '"';
480
    if (!$mysqli->query($query)) {
481 482 483 484 485
      $this->Log('Cart->Remove 5: ' . $mysqli->error);
    }
    $query = 'DELETE FROM cart_tracking WHERE user = "' . $this->owner . '"';
    if (!$mysqli->query($query)) {
      $this->Log('Cart->Remove 6: ' . $mysqli->error);
486
    }
487
    $mysqli->close();
488 489 490 491 492 493 494
  }

  public function SetContent($id, $us_content) {

  }

  public function Update() {
495
    $mysqli = connect_db();
496 497 498 499 500 501 502 503
    $query = 'CREATE TABLE IF NOT EXISTS cart_tracking (' .
      'user VARCHAR(50) NOT NULL,' .
      'name VARCHAR(100) NOT NULL,' .
      'supplier VARCHAR(50) NOT NULL,' .
      'product VARCHAR(100) NOT NULL,' .
      'modified TINYINT(1),' .
      'PRIMARY KEY(user, name)' .
      ') ENGINE=MyISAM';
504
    if (!$mysqli->query($query)) {
505
      $this->Log('Cart->Update: ' . $mysqli->error);
506 507
    }
    $mysqli->close();
508 509 510
  }

  public function UpdateScript($path) {
511
    $this->AppendScript($path, 'dobrado.cart.js');
512 513
  }

514 515
  // Public functions that aren't part of interface here /////////////////////

516 517
  // Private functions below here ////////////////////////////////////////////

518
  private function AllItems() {
519 520
    $object = [];
    $current = [];
521
    $mysqli = connect_db();
522 523 524
    // Get the availability and item_order for the current page. This is done
    // in two steps because the queries don't join well. Need everything from
    // the cart_items table and only existing values from cart_item_page table.
525 526
    $query = 'SELECT name, available, tab, item_order FROM cart_item_page ' .
      'WHERE user = "' . $this->owner . '" AND page = "' .$this->user->page.'"';
527 528
    if ($result = $mysqli->query($query)) {
      while ($cart_item_page = $result->fetch_assoc()) {
529
        $current[$cart_item_page['name']] =
530
          ['available' => $cart_item_page['available'],
531
           'tab' => $cart_item_page['tab'],
532
           'item_order' => $cart_item_page['item_order']];
533 534 535 536
      }
      $result->close();
    }
    else {
537
      $this->Log('Cart->AllItems 1: ' . $mysqli->error);
538
    }
539 540 541
    $tracking = $this->Tracking();
    $query = 'SELECT name, image, short, full, weight, price, variable, ' .
      'minimum, download FROM cart_items WHERE user = "' . $this->owner . '" ' .
542
      'ORDER BY name';
543 544
    if ($result = $mysqli->query($query)) {
      while ($cart_items = $result->fetch_assoc()) {
545
        $name = $cart_items['name'];
546
        if (isset($current[$name])) {
547
          $cart_items['available'] = $current[$name]['available'];
548
          $cart_items['tab'] = $current[$name]['tab'];
549
          $cart_items['item_order'] = $current[$name]['item_order'];
550 551
        }
        else {
552
          $cart_items['available'] = '0';
553
          $cart_items['tab'] = '';
554
          $cart_items['item_order'] = '0';
555
        }
556 557 558 559 560 561
        if (isset($tracking[$name])) {
          $cart_items['tracking'] = 'Tracking stock item: ' .
            $tracking[$name]['name'] . ', from: ' .
            $tracking[$name]['supplier'] . '.';
          $cart_items['modified'] = $tracking[$name]['modified'];
        }
562 563
        $cart_items['name'] = $cart_items['name'];
        $cart_items['short'] = $cart_items['short'];
564 565 566 567 568
        $object[] = $cart_items;
      }
      $result->close();
    }
    else {
569
      $this->Log('Cart->AllItems 2: ' . $mysqli->error);
570 571 572 573 574
    }
    $mysqli->close();
    return $object;
  }

575
  private function Checkout() {
576
    $mysqli = connect_db();
577
    // Do htmlspecialchars first so that quotes don't need escaping.
578 579 580 581 582 583 584 585
    $first = $mysqli->escape_string(htmlspecialchars($_POST['first']));
    $last = $mysqli->escape_string(htmlspecialchars($_POST['last']));
    $email = $mysqli->escape_string(htmlspecialchars($_POST['email']));
    $address = $mysqli->escape_string(htmlspecialchars($_POST['address']));
    $city = $mysqli->escape_string(htmlspecialchars($_POST['city']));
    $postcode = $mysqli->escape_string(htmlspecialchars($_POST['postcode']));
    $state = $mysqli->escape_string(htmlspecialchars($_POST['state']));
    $country = $mysqli->escape_string(htmlspecialchars($_POST['country']));
586
    $method = $mysqli->escape_string(htmlspecialchars($_POST['method']));
587 588 589 590 591
    $description = '';
    if (isset($_POST['description'])) {
      $description =
        $mysqli->escape_string(htmlspecialchars($_POST['description']));
    }
592

593 594
    // Paypal does not allow a detailed item description.
    $item_names = $method === 'paypal' ? 'Items: ' :
Malcolm Blaney's avatar
Malcolm Blaney committed
595
      '<table><tr><th>Item Name</th><th>Quantity</th><th>Price</th></tr>';
596 597 598
    $total_price = 0;
    $total_weight = 0;
    $order_verified = true;
599 600
    // Initialise the cart session array to store downloadable items, also
    // items may need to be saved in the Purchase module once order is complete.
601
    $_SESSION['cart'] = [];
602
    $_SESSION['cart-purchase'] = [];
603 604
    $_SESSION['cart-owner'] = $this->owner;
    $us_cart = json_decode($_POST['cart'], true);
605 606 607 608 609 610 611 612

    $purchase = [];
    $buyer_group = 'retail';
    if ($this->user->loggedIn) {
      $banking = new Module($this->user, $this->owner, 'banking');
      $buyer_group = $banking->Factory('BuyerGroup');
    }
    $tracking = $this->Tracking($buyer_group);
613
    foreach ($us_cart as $us_item => $us_values) {
614 615 616
      $quantity = (float)$us_values['quantity'];
      if ($quantity < 0.01) continue;

617
      $item = $mysqli->escape_string($us_item);
618
      $price = (float)$us_values['price'];
619 620 621 622 623 624 625 626 627
      $stock_price = 0;
      if (isset($tracking[$item])) {
        $stock_price = $tracking[$item]['price'];
        // Tracking returns the format required for the Purchase module to add
        // the sale, just need to add quantity.
        $tracking[$item]['quantity'] = $quantity;
        $_SESSION['cart-purchase'][] = $tracking[$item];
      }
      list($verified, $weight) = $this->VerifyItem($item, $price, $stock_price);
628 629 630 631
      if (!$verified) {
        $order_verified = false;
        break;
      }
632 633 634 635
      if ($method === 'paypal') {
        if ($item_names !== '') $item_names .= ', ';
        $item_names .= $item;
        if ($quantity > 1) {
636
          $item_names .= ' (' . $quantity . ')';
637 638 639
        }
      }
      else {
640 641
        $item_names .= '<tr><td>' . $item . '</td><td>' . $quantity . '</td>' .
          '<td>$' . number_format($price * $quantity, 2, '.', '') .'</td></tr>';
642
      }
643
      $total_price += round($price * $quantity, 2);
644 645
      $total_weight += $weight * $quantity;
    }
646
    if ($first === '' || $last === '' || $email === '' || $address === '') {
647 648
      $order_verified = false;
    }
649 650 651
    $mysqli->close();

    $result = [];
652
    if ($order_verified) {
653 654 655 656 657 658
      $shipping = 0;
      if ($method !== 'pickup') {
        // Look for shipping rules that match the given locations.
        $rules = $this->ShippingRules($city, $state, $country, $total_weight);
        $shipping = $this->ShippingCost($total_price, $rules);
      }
659
      $result['shipping'] = $shipping;
660
      $processing = $this->ProcessingCost($total_price);
661
      $result['processing'] = $processing;
662
      if ($method !== 'paypal') {
663
        if ($shipping > 0.01) {
664 665
          $item_names .= '<tr><td>Shipping</td><td></td>' .
            '<td>$' . number_format($shipping, 2, '.', '') . '</td></tr>';
666
        }
667
        if ($processing > 0.01) {
668 669
          $item_names .= '<tr><td>Processing</td><td></td>' .
            '<td>$' . number_format($processing, 2, '.', '') . '</td></tr>';
670 671 672
        }
        $item_names .= '</table>';
      }
673
      if ($method === 'pickup') {
674 675 676 677 678
        if (count($_SESSION['cart-purchase']) > 0) {
          $purchase = new Module($this->user, $this->owner, 'purchase');
          $purchase->Factory('CartSales',
                             ['account', $_SESSION['cart-purchase']]);
        }
679 680 681 682 683
        $order_id = $this->Payment($item_names, $total_price + $shipping +
                                   $processing, $first, $last, $email, $address,
                                   $city, $postcode, $state, $country,
                                   $description, $method);
        $result['content'] =
684
          $this->Substitute('cart-pickup', '/!order-id/', $order_id) .
685 686 687 688 689 690
          '<button id="cart-payment">done</button>';
      }
      else {
        $patterns = ['/!first/', '/!last/', '/!address/', '/!postcode/',
                     '/!city/', '/!state/', '/!country/', '/!description/'];
        $replacements = [$first, $last, $address, $postcode, $city, $state,
691
                         $country, $description];
692 693 694 695 696 697 698 699
        $result['content'] = $this->Substitute('cart-checkout', $patterns,
                                               $replacements);
        $result['content'] .= $this->Payment($item_names, $total_price +
                                             $shipping + $processing, $first,
                                             $last, $email, $address, $city,
                                             $postcode, $state, $country,
                                             $description, $method);
      }
700 701
    }
    else {
702 703
      $result['shipping'] = 0;
      $result['processing'] = 0;
704
      $result['content'] = 'There was a problem processing your order.<br>' .
705
        'Please check your details and try again.';
706
    }
707
    return $result;
708 709
  }

710 711 712 713 714 715
  private function CompleteOrder() {
    if (!isset($_GET['payment']) || !isset($_SESSION['cart-order-id'])) {
      return '';
    }

    $content = '';
716
    $email = '';
717 718 719
    $message = '';
    $order_id = $_SESSION['cart-order-id'];
    $mysqli = connect_db();
720 721
    $query = 'SELECT email, description FROM cart_order WHERE user = ' .
      '"' . $this->owner . '" AND id = ' . $order_id;
722 723
    if ($result = $mysqli->query($query)) {
      if ($cart_order = $result->fetch_assoc()) {
724
        $email = $cart_order['email'];
725 726 727 728 729
        $message = $cart_order['description'];
      }
      $result->close();
    }
    else {
730
      $this->Log('Cart->CompleteOrder 1:' . $mysqli->error);
731 732 733 734
    }
    if ($_GET['payment'] === 'paypal') {
      // TODO: There is no checking done on paypal return values,
      // that requires supporting PDT and maybe IPN in the future.
735 736 737 738 739 740 741
      if (count($_SESSION['cart-purchase']) > 0) {
        $purchase = new Module($this->user, $this->owner, 'purchase');
        $purchase->Factory('CartSales', ['PayPal', $_SESSION['cart-purchase']]);
      }
      $content = '<div class="cart-payment-message">' .
        'Thanks for your purchase!<br>' .
        'For your reference, the order number is: ' . $order_id . '<br><br>' .
742
        '<button>dismiss</button></div>';
743 744
      $this->SendEmail('Confirmation for order number ' . $order_id,
                       $message . 'Payment made using PayPal.', $email);
745 746 747
    }
    else if ($_GET['payment'] === 'credit') {
      $gateway = $this->Gateway('credit');
748
      if ($gateway === true) {
749 750 751 752 753 754 755 756 757
        if (count($_SESSION['cart-purchase']) > 0) {
          $purchase = new Module($this->user, $this->owner, 'purchase');
          $purchase->Factory('CartSales',
                             ['Credit Card', $_SESSION['cart-purchase']]);
        }
        $this->SendEmail('Confirmation for order number ' . $order_id,
                         $message . 'Payment made using Credit Card.', $email);
        // Gateway returns an error message when unsuccesful, so set the message
        // here when it returns true.
758 759 760
        $gateway = 'Thanks your payment has been processed.';
      }
      else {
761
        $this->SendEmail('Error processing order number ' .$order_id, $message);
762
      }
763 764
      $content = '<div class="cart-payment-message">' . $gateway . '<br>' .
        'For your reference, the order number is: ' . $order_id . '<br><br>' .
765 766
        '<button>dismiss</button></div>';
    }
767 768
    $query = 'UPDATE cart_order SET completed = ' . time() . ' WHERE ' .
      'user = "' . $this->owner . '" AND id = ' . $order_id;
769
    if (!$mysqli->query($query)) {
770
      $this->Log('Cart->CompleteOrder 2: ' . $mysqli->error);
771
    }
772 773
    $_SESSION['cart-order-id'] = NULL;
    $_SESSION['cart-purchase'] = [];
774 775 776 777 778 779 780 781
    // Check if there are any items that need downloading.
    $count = isset($_SESSION['cart']) ? count($_SESSION['cart']) : 0;
    if ($count !== 0) {
      $_SESSION['cart-owner'] = $this->owner;
      $download = 'download';
      if ($count > 1) {
        $download = 'downloads';
      }
782 783
      $content .= '<div class="cart-download-message">' .
        'Your ' . $download . ' will begin shortly.</div>' .
784 785
        '<ul class="cart-download-list hidden">';
      for ($i = 0; $i < $count; $i++) {
786
        $content .= '<li>' . $_SESSION['cart'][$i] . '</li>';
787 788 789 790 791 792 793
      }
      $content .= '</ul>';
    }
    $mysqli->close();
    return $content;
  }

794
  private function DisplayItem() {
795
    $object = [];
796
    $mysqli = connect_db();
797
    $name = $mysqli->escape_string(htmlspecialchars($_POST['name']));
798 799 800
    $price = number_format((float)$_POST['price'], 2, '.', '');
    $query = 'SELECT image, short, full, price FROM cart_items WHERE ' .
      'user = "' . $this->owner . '" AND name = "' . $name . '"';
801 802
    if ($result = $mysqli->query($query)) {
      if ($cart_items = $result->fetch_assoc()) {
803
        $image = $cart_items['image'];
804
        $short = $cart_items['short'];
805
        $full = $cart_items['full'];
806 807 808 809 810 811 812 813
        $retail = $cart_items['price'];
        $price_comparison = $price === $retail ? '' :
          $this->Substitute('cart-price-comparison', ['/!price/', '/!retail/'],
                            [$price, $retail]);
        $object['content'] =
          $this->Substitute('cart-display-item', ['/!name/', '/!image/',
                            '/!short/', '/!full/', '/!price/'],
                            [$name, $image, $short, $full, $price_comparison]);
814 815 816 817
      }
      $result->close();
    }
    else {
818
      $this->Log('Cart->DisplayItem: ' . $mysqli->error);
819 820
    }
    $mysqli->close();
821 822 823
    return $object;
  }

824 825
  private function FormatItem($item, $price_text, $quantity_text) {
    // Want to use item name in css class and id's, so replace some chars.
826 827
    $id = preg_replace('/[^a-z0-9_-]/i', '-', $item['name']);
    $download = $item['download'];
828 829
    $price = '<span class="item-price">' . $price_text . '$' .
      $item['price'] . '</span>';
830 831 832
    // If 'variable' is true need to make price an input field.
    if ($item['variable'] === '1') {
      $minimum = $item['minimum'];
833 834
      // If minimum price is zero for a downloadable item provide a
      // download link.
835 836
      $download_content = '';
      if ($download !== '' && $minimum === '0.00') {
837 838
        $download_content = '<a class="item-download hidden" ' .
          'href="' . $download . '">Yes you can download for free!</a>';
839
      }
840 841
      $minimum_content = '';
      if ($minimum !== '0.00') {
842 843
        $minimum_content = '(min: $' .
          '<span class="item-minimum">' . $minimum . '</span>)';
844
      }
845 846 847 848 849 850
      $price = '<i>You can choose a price for this item, suggested ' .
          'price is displayed.</i><br>' .
        '<label for="item-price-' . $id . '">Price:</label>' .
        '<input id="item-price-' . $id . '" class="item-price" ' .
          'value="' . $item["price"] . '" type="text" maxlength="11"> ' .
        $minimum_content . $download_content;
851
    }
852
    // If an item can be downloaded, display an 'add to cart' button
853 854
    // rather than an input for quantity.
    $quantity = '<button class="item-add">Add to cart</button>';
855
    if ($download === '') {
856 857 858 859 860 861
      $quantity = '<span class="item-quantity-wrapper">' .
          '<label for="item-quantity-' . $id . '">' . $quantity_text.'</label>'.
          '<input id="item-quantity-' . $id . '" class="item-quantity" ' .
            'type="text" value="0">' .
        '</span> ' .
        '<span class="item-after-quantity-' . $id . '"></span>';
862
    }
863 864
    $image = '';
    if (preg_match('/^(.+)\.(.+)$/', $item['image'], $matches)) {
865
      $image = '<img class="item-image" src="' . $matches[1];
866
      $type = $matches[2];
867
      if (in_array(strtolower($type), ['gif', 'jpeg', 'jpg', 'png'])) {
868
        $image .= '_thumb.' . $type;
869 870 871
      }
      $image .= '">';
    }
872
    $title = $item['name'];
873 874
    // Only provide an anchor on the title if there is a
    // full description to display in a dialog box.
875
    if ($item['full'] !== '') {
876 877
      $title = '<a href="#cart-item-id-' . $id . '">' . $item['name'] . '</a>';
      $image = '<a href="#cart-item-id-' . $id . '">' . $image . '</a>';
878
    }
879 880 881 882
    return '<span id="cart-item-id-' . $id . '" class="cart-item"> ' .
      '<span class="item-name">' . $title . '</span> ' . $image .
      ' <span class="item-short-description">' . $item['short'] . '</span> ' .
      $price . ' ' . $quantity . ' <span class="clear"></span> </span>';
883 884
  }

885
  private function Gateway($name, $data = NULL) {
886 887 888
    $gateway = '';
    $gateway_api_key = '';
    $gateway_password = '';
889
    $mysqli = connect_db();
890 891 892
    $query = 'SELECT gateway, gateway_api_key, gateway_password FROM ' .
      'cart_method WHERE user = "' . $this->owner . '" AND ' .
      'name = "' . $name . '" AND available = 1';
893 894
    if ($result = $mysqli->query($query)) {
      if ($cart_method = $result->fetch_assoc()) {
895 896 897
        $gateway = $cart_method['gateway'];
        $gateway_api_key = $cart_method['gateway_api_key'];
        $gateway_password = $cart_method['gateway_password'];
898
      }
899
      $result->close();
900 901
    }
    else {
902
      $this->Log('Cart->Gateway: ' . $mysqli->error);
903 904 905
    }
    $mysqli->close();

906 907
    if ($gateway === 'eway') {
      if ($gateway_api_key === '' || $gateway_password === '') {
908
        return '<div class="error ui-state-error ui-corner-all">' .
909
          'Gateway not set.</div>';
910
      }
911

912 913
      $auth = base64_encode($gateway_api_key . ':' . $gateway_password);
      $curl_headers = ['Authorization: Basic ' . $auth,
914
                       'Content-Type: application/json'];
915
      // For sandbox set domain to: api.sandbox.ewaypayments.com
916
      $url = 'https://api.ewaypayments.com/';
917 918
      // If data was passed to this function, user wants to make a payment
      // so need to get an access code. Otherwise querying results.
919
      if (isset($data)) {
920
        $url .= 'AccessCodes';
921 922
      }
      else {
923
        if (!isset($_GET['AccessCode'])) {
924
          return '<div class="error ui-state-error ui-corner-all">' .
925
            'Transaction not found.</div>';
926
        }
927
        $url .= 'AccessCode/' . $_GET['AccessCode'];
928 929 930 931
      }
      $ch = curl_init($url);
      curl_setopt($ch, CURLOPT_HTTPHEADER, $curl_headers);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
932
      if (isset($data)) {
933
        curl_setopt($ch, CURLOPT_POST, true);
934 935 936 937 938 939
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
      }
      $result = json_decode(curl_exec($ch), true);
      curl_close($ch);

      // If data was passed to the function now return the payment form.
940 941 942
      if (isset($data)) {
        $access_code = NULL;
        $form_action_url = NULL;
943 944
        if (isset($result['AccessCode'])) {
          $access_code = $result['AccessCode'];
945
        }
946 947
        if (isset($result['FormActionURL'])) {
          $form_action_url = $result['FormActionURL'];
948
        }
949 950 951 952
        if (!isset($access_code) ||
            !isset($form_action_url) || $result['Errors']) {
          return '<div class="error ui-state-error ui-corner-all">' .
            'There was a problem processing your details.<br>' .
953
            'Please contact support.</div>';
954
        }
955
        // Look up customer in data to automatically set the card name.
956
        $customer = $data['Customer'];
957
        $full_name = $customer['FirstName'] . ' ' . $customer['LastName'];
958
        // Generate year options.
959 960 961
        $long = (int)date('Y');
        $short = (int)date('y');
        $options = '';
962
        for ($i = 0; $i < 7; $i++) {
963 964
          $options .= '<option value="' . $short++ . '">' . $long++ .
            '</option>';
965 966
        }
        return
967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007
          '<form id="eway-form" action="' . $form_action_url . '" ' .
            'method="post">' .
            'Please enter your credit card details:' .
            '<div class="form-spacing">' .
              '<label for="eway-name">Name:</label>' .
              '<input id="eway-name" name="EWAY_CARDNAME" ' .
                'value="' . $full_name . '" type="text">' .
            '</div>' .
            '<div class="form-spacing">' .
              '<label for="eway-number">Number:</label>' .
              '<input id="eway-number" name="EWAY_CARDNUMBER" type="text" ' .
                'maxlength="50">' .
            '</div>' .
            '<div class="form-spacing">' .
              '<label for="eway-number">Security Code:</label>' .
              '<input id="eway-cvn" name="EWAY_CARDCVN" type="text" ' .
                'maxlength="3">' .
            '</div>' .
            '<div class="form-spacing">' .
              '<label for="eway-expiry-month">Expiry:</label>' .
              '<select id="eway-expiry-month" name="EWAY_CARDEXPIRYMONTH">' .
                '<option value="01">Jan</option>' .
                '<option value="02">Feb</option>' .
                '<option value="03">Mar</option>' .
                '<option value="04">Apr</option>' .
                '<option value="05">May</option>' .
                '<option value="06">Jun</option>' .
                '<option value="07">Jul</option>' .
                '<option value="08">Aug</option>' .
                '<option value="09">Sep</option>' .
                '<option value="10">Oct</option>' .
                '<option value="11">Nov</option>' .
                '<option value="12">Dec</option>' .
              '</select> ' .
              '<select name="EWAY_CARDEXPIRYYEAR">' .
                $options .
              '</select>' .
            '</div>' .
            '<input type="hidden" name="EWAY_ACCESSCODE" ' .
              'value="' . $access_code . '">' .
            '<button id="cart-payment">Submit Payment</button>' .
1008 1009 1010
          '</form>';
      }
      // If no data was provided, check the payment result.
1011 1012
      if (isset($result['TransactionStatus']) &&
          $result['TransactionStatus'] === true) {
1013
        return true;
1014
      }
1015 1016
      return '<div class="error ui-state-error ui-corner-all">' .
        'There was a problem processing your payment.<br>' .
1017
        'Please contact support.</div>';
1018
    }
1019
    else if ($gateway === 'migs') {
1020
      if (isset($data)) {
1021 1022
        if ($gateway_password === '' ||
            strpos($gateway_api_key, ':') === false) {
1023
          return '<div class="error ui-state-error ui-corner-all">' .
1024 1025 1026
            'Gateway not set.</div>';
        }

1027 1028 1029 1030
        list($merchant_id, $access_code) = explode(':', $gateway_api_key);
        $amount = $data['Payment']['TotalAmount'];
        $merch_txn_ref = time();
        $order_id = $_SESSION['cart-order-id'];
1031 1032 1033 1034
        $hash_input = 'vpc_AccessCode=' . $access_code . '&vpc_Amount=' .
          $amount . '&vpc_Command=pay&vpc_Locale=en&vpc_MerchTxnRef=' .
          $merch_txn_ref . '&vpc_Merchant=' . $merchant_id . '&vpc_OrderInfo=' .
          $order_id . '&vpc_ReturnURL=' . $data['RedirectURL'].'&vpc_Version=1';
1035 1036
        $secure_hash = strtoupper(hash_hmac('sha256', $hash_input,
                                            pack('H*', $gateway_password)));
1037 1038
        return
          '<form id="migs-form" action="https://migs.mastercard.com.au/vpcpay"'.
1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056
            ' method="post">' .
            '<input type="hidden" name="vpc_AccessCode" ' .
              'value="' . $access_code . '">' .
            '<input type="hidden" name="vpc_Amount" value="' . $amount . '">' .
            '<input type="hidden" name="vpc_Command" value="pay">' .
            '<input type="hidden" name="vpc_Locale" value="en">' .
            '<input type="hidden" name="vpc_MerchTxnRef" ' .
              'value="' . $merch_txn_ref . '">' .
            '<input type="hidden" name="vpc_Merchant" ' .
              'value="' . $merchant_id . '">' .
            '<input type="hidden" name="vpc_OrderInfo" value="' .$order_id.'">'.
            '<input type="hidden" name="vpc_ReturnURL" ' .
              'value="' . $data['RedirectURL'] . '">' .
            '<input type="hidden" name="vpc_Version" value="1">' .
            '<input type="hidden" name="vpc_SecureHash" ' .
              'value="' . $secure_hash . '">' .
            '<input type="hidden" name="vpc_SecureHashType" value="SHA256">' .
            '<button id="cart-payment">Go to payment page</button>' .
1057 1058 1059 1060 1061
          '</form>';
      }
      // If no data was provided, check the payment result.
      if (isset($_GET["vpc_TxnResponseCode"]) &&
          $_GET['vpc_TxnResponseCode'] === '0') {
1062
        return true;
1063
      }
1064 1065
      return '<div class="error ui-state-error ui-corner-all">' .
        'There was a problem processing your payment.<br>' .
1066
        'Please contact support.</div>';
1067
    }
1068
    else {
1069
      return '<div class="error ui-state-error ui-corner-all">' .
1070 1071 1072 1073
        'Gateway not found.</div>';
    }
  }

1074 1075 1076
  private function Payment($items, $amount, $first, $last,
                           $email, $address, $city, $postcode,
                           $state, $country, $description, $method) {
1077 1078
    $business = '';
    $currency = '';
1079
    $mysqli = connect_db();
1080 1081
    $query = 'SELECT email, currency FROM cart_checkout WHERE ' .
      'user = "' . $this->owner . '"';
1082 1083
    if ($result = $mysqli->query($query)) {
      if ($cart_checkout = $result->fetch_assoc()) {
1084 1085
        // email is not escaped when stored.
        $business = htmlspecialchars($cart_checkout['email']);
1086
        $currency = $cart_checkout['currency'];
1087 1088 1089 1090
      }
      $result->close();
    }
    else {
1091
      $this->Log('Cart->Payment 1: ' . $mysqli->error);
1092
    }
1093
    $query = 'SELECT name FROM cart_method WHERE user = "' . $this->owner .'" '.
1094 1095
      'AND available = 1';
    if ($result = $mysqli->query($query)) {
1096
      if ($result->num_rows === 1) {
1097
        if ($cart_method = $result->fetch_assoc()) {
1098
          $method = $cart_method['name'];
1099 1100 1101 1102 1103
        }
      }
      else if ($result->num_rows > 1) {
        // When more than one payment method is allowed, make sure the method
        // selected by the user is in the results.
1104
        $payment_method = $mysqli->escape_string($_POST['method']);
1105
        while ($cart_method = $result->fetch_assoc()) {
1106
          if ($payment_method === $cart_method['name']) {
1107 1108 1109 1110 1111 1112 1113 1114
            $method = $payment_method;
            break;
          }
        }
      }
      $result->close();
    }
    else {
1115
      $this->Log('Cart->Payment 2: ' . $mysqli->error);
1116
    }
1117 1118
    // Store the details to send an email for the order in the session, but
    // it's not sent until return from payment processing.
1119 1120 1121
    $patterns = ['/!items/', '/!amount/', '/!first/', '/!last/', '/!email/',
                 '/!address/', '/!postcode/', '/!city/', '/!state/',
                 '/!country/'];
1122 1123
    $replacements = [$items, number_format($amount, 2, '.', ''), $first, $last,
                     $email, $address, $postcode, $city, $state, $country];
1124
    $us_email_text = $this->Substitute('cart-email', $patterns, $replacements);
1125
    if ($method === 'pickup') {
1126
      $us_email_text .= 'Your order will be available to pick up from: ' .
1127 1128 1129 1130 1131
        $description;
    }
    else {
      $us_email_text .= $this->Substitute('cart-delivery-info');
    }
1132 1133 1134 1135
    $query = 'INSERT INTO cart_order (user, email, description, method, ' .
      'timestamp) VALUES ("' . $this->owner . '", "' . $email . '", ' .
      '"' . $mysqli->escape_string($us_email_text) . '", "' . $method . '", ' .
      time() . ')';
1136
    if (!$mysqli->query($query)) {
1137
      $this->Log('Cart->Payment 3: ' . $mysqli->error);
1138 1139 1140
    }
    $_SESSION['cart-order-id'] = $mysqli->insert_id;
    $mysqli->close();
1141

1142
    if ($business === '' || $currency === '' || $method === '') {
1143
      return '<div class="error ui-state-error ui-corner-all">' .
1144 1145 1146 1147
        'Payment options not set.</div>';
    }

    if ($method === 'pickup') {
1148
      $order_id = $_SESSION['cart-order-id'];
1149
      $this->SendEmail('Confirmation for order number ' . $order_id,
1150
                       $us_email_text, $email);
1151
      return $order_id;
1152
    }
1153
    if ($method === 'paypal') {
1154 1155 1156
      // Maximum item_name string to paypal is 127 chars.
      if (strlen($items) > 127) {
        $items = substr($items, 0, 124);
1157
        $items .= '...';
1158
      }
1159 1160
      $scheme = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== '' ?
        'https://' : 'http://';
1161
      $url = $scheme . $_SERVER['SERVER_NAME'] . $this->Url('payment=paypal');
1162
      return
1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177
        '<form action="https://www.paypal.com/cgi-bin/webscr" method="post">' .
          '<input type="hidden" name="cmd" value="_ext-enter">' .
          '<input type="hidden" name="redirect_cmd" value="_xclick">' .
          '<input type="hidden" name="business" value="' . $business . '">' .
          '<input type="hidden" name="item_name" value="' . $items . '">' .
          '<input type="hidden" name="currency_code" value="' . $currency .'">'.
          '<input type="hidden" name="amount" value="' . $amount . '">' .
          '<input type="hidden" name="email" value="' . $email . '">' .
          '<input type="hidden" name="first_name" value="' . $first . '">' .
          '<input type="hidden" name="last_name" value="' . $last . '">' .
          '<input type="hidden" name="address1" value="' . $address . '">' .
          '<input type="hidden" name="city" value="' . $city . '">' .
          '<input type="hidden" name="zip" value="' . $postcode . '">' .
          '<input type="hidden" name="return" value="' . $url . '">' .
          '<button id="cart-payment">Pay with PayPal</button>' .
1178 1179
        '</form>';
    }
1180
    if ($method === 'credit') {
1181
      // TODO: Not using country here because eway requires two letter codes.
1182 1183 1184 1185
      $customer = ['Email' => $email, 'FirstName' => $first,
                   'LastName' => $last, 'Street1' => $address, 'City' => $city,
                   'PostalCode' => $postcode, 'State' => $state];
      $payment = ['TotalAmount' => (int)($amount*100)];
1186
      $redirect = $_SERVER['SERVER_NAME'] . $this->Url('payment=credit');
1187
      $data = ['Customer' => $customer, 'Payment' => $payment,
1188
               'RedirectURL' => 'https://' . $redirect];
1189
      return $this->Gateway('credit', $data);
1190
    }
1191
    return '<div class="error ui-state-error ui-corner-all">' .
1192 1193 1194 1195
      'Payment method not found.</div>';
  }

  private function PaymentMethods($display_cash = false,
1196
                                  $id = 'customer-detail-method') {
1197
    $mysqli = connect_db();
1198
    $payment_method = '';
1199 1200 1201 1202
    $select_finished = false;
    // When cash and eftpos options need to be displayed always show a select,
    // otherwise the select is only shown if there's more than one option.
    if ($display_cash) {
1203 1204 1205 1206 1207
      $payment_method = '<label for="' . $id . '">Payment:</label>' .
        '<select id="' . $id . '">' .
          '<option value=""></option>' .
          '<option value="cash">Cash</option>' .
          '<option value="eftpos">Eftpos</option>' .
1208
          '<option value="account">Account</option>';
1209
    }
1210
    $query = 'SELECT name FROM cart_method WHERE user = "' . $this->owner .'" '.
1211 1212
      'AND available = 1';
    if ($result = $mysqli->query($query)) {
1213 1214
      if ($payment_method === '' && $result->num_rows === 1) {
        if ($cart_method = $result->fetch_assoc()) {
1215 1216
          $payment_method = '<input id="' . $id . '" type="hidden" ' .
            'value="' . $cart_method['name'] . '">';
1217 1218 1219 1220 1221 1222
          // (There never was a select in this case.)
          $select_finished = true;
        }
      }
      else {
        if ($payment_method === '') {
1223 1224
          $payment_method = '<label for="' . $id . '">Payment:</label>' .
            '<select id="' . $id . '">';
1225
        }
1226
        while ($cart_method = $result->fetch_assoc()) {
1227 1228 1229 1230
          $method = $cart_method['name'];
          $description = '';
          if ($method === 'credit') {
            $description = 'Credit Card';
1231
          }
1232 1233
          else if ($method === 'paypal') {
            $description = 'PayPal';
1234
          }
1235
          else if ($method === 'pickup') {