Advertisement
ThisYouRick

Untitled

Apr 28th, 2016
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 124.63 KB | None | 0 0
  1. <?php
  2.  
  3. require_once DOC_ROOT . 'classes/tools/Element/Element/Common.php';
  4.  
  5. if (!class_exists('Element_Order')):
  6.  
  7.     define('ORDER_STATUS_CHANGED', -1);
  8.     define('ORDER_STATUS_NEW', 0);
  9.     define('ORDER_STATUS_PROCESSING', 1);
  10.     define('ORDER_STATUS_COMPLETE', 2);
  11.     define('ORDER_STATUS_FAILED', 3);
  12.     define('ORDER_STATUS_OFFLINE', 4); // waiting for offline payment
  13.     define('ORDER_STATUS_TIMEOUT', 5); // timeout
  14.     define('ORDER_STATUS_CANCELLED', 6); // order canceled
  15.     define('ORDER_STATUS_PARTIALLY', 7); // order paid partially
  16.     define('ORDER_STATUS_COURIER', 8); // sent by courier
  17.     define('ORDER_STATUS_PREPAY', 9); // prepay
  18.     define('ORDER_STATUS_CASH', 10); // cash payment
  19.  
  20.  
  21.     define('ORDER_CONFIRM_TIME', 15 * 60);
  22.  
  23.     class Element_Order extends Element_Common {
  24.  
  25.         private static $_mIdTopDJ = 41215;
  26.         public $table_name = 't_order';
  27.         public $cache = array();
  28.         public $paymentTypes = array(
  29.             'card' => array(
  30.                 'title' => 'ПриватБанк',
  31.                 'currency' => array(
  32.                     1 => 'UAH',
  33.                     2 => 'EUR',
  34.                     3 => 'UAH',
  35.                 ),
  36.                 'class' => 'PrivatBank',
  37.                 'is_online' => 1
  38.             ),
  39.             'platon' => array(
  40.                 'title' => 'Платон',
  41.                 'currency' => array(
  42.                     1 => 'UAH',
  43.                     2 => 'EUR',
  44.                     3 => 'UAH',
  45.                 ),
  46.                 'class' => 'Platon',
  47.                 'is_online' => 1
  48.             ),
  49.             'webmoney' => array(
  50.                 'title' => 'Webmoney',
  51.                 'currency' => array(
  52.                     1 => 'UAH',
  53.                     2 => 'EUR',
  54.                     3 => 'UAH',
  55.                 ),
  56.                 'subtypes' => array(
  57.                     /*'wmu' => array(
  58.                         'title' => 'WMU',
  59.                         'currency' => array(
  60.                             '1' => 'WMU',
  61.                             '2' => 'WMU',
  62.                             '3' => 'WMU',
  63.                         ),
  64.                     ),
  65.                     'wmz' => array(
  66.                         'title' => 'WMZ',
  67.                         'currency' => array(
  68.                             '1' => 'WMZ',
  69.                             '2' => 'WMZ',
  70.                             '3' => 'WMZ',
  71.                         ),
  72.                     ),*/
  73.                     'wmr' => array(
  74.                         'title' => 'WMR',
  75.                         'currency' => array(
  76.                             1 => 'WMR',
  77.                             2 => 'WMR',
  78.                             3 => 'WMR',
  79.                         ),
  80.                     ),
  81.                 ),
  82.                 'class' => 'Webmoney',
  83.                 'is_online' => 1
  84.             ),
  85.             'WMTerminals' => array(
  86.                 'title' => 'Webmoney (Терминал)',
  87.                 'currency' => 'UAH',
  88.                 'subtypes' => array(
  89.                     'wmu' => array(
  90.                         'title' => 'WMU',
  91.                         'currency' => 'WMU',
  92.                     ),
  93.                 ),
  94.                 'class' => 'Webmoney',
  95.                 'is_online' => 1
  96.             ),
  97.             'liqpay' => array(
  98.                 'title' => 'LiqPAY',
  99.                 'currency' => array(
  100.                     1 => 'UAH',
  101.                     2 => 'EUR',
  102.                     3 => 'UAH',
  103.                 ),
  104.                 'class' => 'LiqPay',
  105.                 'is_online' => 1
  106.             ),
  107.             'pumb' => array(
  108.                 'title' => 'Pumb',
  109.                 'currency' => array(
  110.                     1 => 'UAH',
  111.                     2 => 'EUR',
  112.                     3 => 'UAH',
  113.                 ),
  114.                 'class' => 'Pumb',
  115.                 'is_online' => 1
  116.             ),
  117.             'free' => array(
  118.                 'title' => 'Бесплатно',
  119.                 'currency' => array(
  120.                     1 => 'UAH',
  121.                     2 => 'EUR',
  122.                     3 => 'UAH',
  123.                 ),
  124.                 'subtypes' => array(
  125.                     'test' => array(
  126.                         'title' => 'Тест',
  127.                         'currency' => array(
  128.                             1 => 'UAH',
  129.                             2 => 'EUR',
  130.                             3 => 'UAH',
  131.                         ),
  132.                     ),
  133.                     'real' => array(
  134.                         'title' => 'Забрать билет',
  135.                         'currency' => array(
  136.                             1 => 'UAH',
  137.                             2 => 'EUR',
  138.                             3 => 'UAH',
  139.                         ),
  140.                     ),
  141.                 ), //, 'real' => 'UAH'
  142.                 'class' => 'Free',
  143.                 'is_online' => 0
  144.             ),
  145.             'offline' => array(
  146.                 'title' => 'Касса',
  147.                 'currency' => array(
  148.                     1 => 'UAH',
  149.                     2 => 'EUR',
  150.                     3 => 'UAH',
  151.                 ),
  152.                 'class' => 'Offline',
  153.                 'is_online' => 0
  154.             ),
  155.             'osmp' => array(
  156.                 'title' => 'Qiwi',
  157.                 'currency' => array(
  158.                     1 => 'UAH',
  159.                     2 => 'EUR',
  160.                     3 => 'UAH',
  161.                 ),
  162.                 'class' => 'Osmp',
  163.                 'is_online' => 1
  164.             ),
  165.             'courier' => array(
  166.                 'title' => 'Курьер',
  167.                 'currency' => array(
  168.                     1 => 'UAH',
  169.                     2 => 'EUR',
  170.                     3 => 'UAH',
  171.                 ),
  172.                 'class' => 'Courier',
  173.                 'is_online' => 0
  174.             ),
  175.             'easypay' => array(
  176.                 'title' => 'EasyPay',
  177.                 'currency' => array(
  178.                     1 => 'UAH',
  179.                     2 => 'EUR',
  180.                     3 => 'UAH',
  181.                 ),
  182.                 'class' => 'EasyPay',
  183.                 'is_online' => 1
  184.             ),
  185.             'bass' => array(
  186.                 'title' => 'ПриватБанк (Терминал)',
  187.                 'currency' => array(
  188.                     1 => 'UAH',
  189.                     2 => 'EUR',
  190.                     3 => 'UAH',
  191.                 ),
  192.                 'class' => 'Bass',
  193.                 'is_online' => 1
  194.             ),
  195.             'ibox' => array(
  196.                 'title' => 'iBox',
  197.                 'currency' => array(
  198.                     1 => 'UAH',
  199.                     2 => 'EUR',
  200.                     3 => 'UAH',
  201.                 ),
  202.                 'class' => 'Ibox',
  203.                 'is_online' => 1
  204.             ),
  205.             'citypay' => array(
  206.                 'title' => 'CityPay',
  207.                 'currency' => array(
  208.                     1 => 'UAH',
  209.                     2 => 'EUR',
  210.                     3 => 'UAH',
  211.                 ),
  212.                 'class' => 'Citypay',
  213.                 'is_online' => 1
  214.             ),
  215.             'certificate' => array(
  216.                 'title' => 'Certificate',
  217.                 'currency' => array(
  218.                     1 => 'UAH',
  219.                     2 => 'EUR',
  220.                     3 => 'UAH',
  221.                 ),
  222.                 'class' => 'Certificate',
  223.                 'is_online' => 0
  224.             ),
  225.             'test' => array(
  226.                 'title' => 'Тестовая оплата',
  227.                 'currency' => array(
  228.                     1 => 'UAH',
  229.                     2 => 'EUR',
  230.                     3 => 'UAH',
  231.                 ),
  232.                 'class' => 'Test',
  233.                 'is_online' => 1
  234.             ),
  235.         );
  236.        
  237.         public $paidStatuses = array(
  238.             -1 => array(
  239.                 'title' => 'Изменённый',
  240.             ),
  241.             0 => array(
  242.                 'title' => 'Не сформированный',
  243.             ),
  244.             1 => array(
  245.                 'title' => 'Отправлен на оплату',
  246.             ),
  247.             2 => array(
  248.                 'title' => 'Оплачено',
  249.             ),
  250.             3 => array(
  251.                 'title' => 'Не прошёл',
  252.             ),
  253.             4 => array(
  254.                 'title' => 'В ожидании оффлайн',
  255.             ),
  256.             5 => array(
  257.                 'title' => 'Просрочен',
  258.             ),
  259.             6 => array(
  260.                 'title' => 'Аннулирован',
  261.             ),
  262.             7 => array(
  263.                 'title' => 'Частичная оплата',
  264.             ),
  265.             8 => array(
  266.                 'title' => 'Оплата Курьеру',
  267.             ),
  268.             9 => array(
  269.                 'title' => 'Передоплата',
  270.             ),
  271.             10 => array(
  272.                 'title' => 'Оплата в кассе'
  273.             )
  274.         );
  275.        
  276.         public $deliveryTypes = array(
  277.             1 => array(
  278.                 'title' => 'Электронный билет',
  279.             ),
  280.             2 => array(
  281.                 'title' => 'Курьер',
  282.             ),
  283.             3 => array(
  284.                 'title' => 'Забрать в кассе',
  285.             ),
  286.         );
  287.        
  288.         public $partners = array(
  289.             0 => array(
  290.                 'title' => 'В-тикет',
  291.             ),
  292.             1 => array(
  293.                 'title' => 'Карабас',
  294.             ),
  295.             10 => array(
  296.                 'title' => 'Премьера',
  297.             ),
  298.             11 => array(
  299.                 'title' => 'Интернет-билет',
  300.             ),
  301.             16 => array(
  302.                 'title' => 'ФлешБокс',
  303.             ),
  304.             17 => array(
  305.                 'title' => 'Кассир24'
  306.             )
  307.         );
  308.        
  309.         public $currencyList = array('uah', 'usd', 'eur', 'byr', 'rur');
  310.  
  311.         public function __construct($options = array()) {
  312.             $options['type'] = 'Order';
  313.  
  314.             if (!$GLOBALS['isSuper']) {
  315.                 unset($this->paymentTypes['card']['free']);
  316.             }
  317.         }
  318.  
  319.         public function create($eventInfo = false, $order_info) {
  320.  
  321.             $externalId = 0;
  322.             if ($eventInfo['partner_id'] == 1) {
  323.                 $params = array(
  324.                     'order_id' => $order_info['karabas_order_id'],
  325.                     'auth' => $order_info['karabas_auth'],
  326.                     'event_id' => $order_info['session_id']
  327.                 );
  328.                 if (false === ($externalId = $this->_karabasSubmitOrder($params))) {
  329.                     return false;
  330.                 }
  331.             }
  332.             if (!$GLOBALS['isLocal'] && !$GLOBALS['isTest'] && $order_info['payment'] == 'free') {
  333.                 return false;
  334.             }
  335.             // 1. Collecting data for creating order
  336.             $patern = '/[^абвгґдеєжзиіїйклмнопрстуфхцчшщьюяАБВГҐДЕЄЖЗИІЇЙКЛМНОПРСТУФХЦЧШЩЬЮЯЁёЪъЫыЭэa-zA-Z\-]/';
  337.             $orderData = array(
  338.                 'event_id' => $eventInfo['id'],
  339.                 'firstname' => preg_replace($patern, '', $order_info['firstname']),
  340.                 'lastname' =>  preg_replace($patern, '', $order_info['lastname']),
  341.                 'city_name' => ($order_info['country'] == 1 && $order_info['country-enter']) ? $order_info['country-enter'] : $order_info['city'],
  342.                 'city_id' => $order_info['city_id'],
  343.                 'email' => $order_info['email'],
  344.                 'mobile' => $order_info['number'],
  345.                 'seller_id' => $order_info['user_id'] ? $order_info['user_id'] : 0,
  346.                 'ip_address' => get_real_ip(),
  347.                 'date_created' => NOW,
  348.                 'payment_type' => $order_info['delivery'] == 3 ? 'offline' : $order_info['payment'],
  349.                 'payment_subtype' => $order_info['subpayment'][$order_info['payment']],
  350.                 'secret_code' => $this->getSecretCode(),
  351.                 'language_id' => $GLOBALS['lng']['id'],
  352.                 'paid_status' => ORDER_STATUS_NEW,
  353.                 'is_deposit' => 0,
  354.                 'is_concert' => $order_info['is_concert'] ? 1 : 0,
  355.                 'is_free' => isset($order_info['is_free']) && $order_info['is_free'] == 1 || $order_info['payment'] == 'free' ? 1 : 0,
  356.                 'partner_id' => $eventInfo['partner_id'],
  357.                 'external_id' => $externalId,
  358.                 'sub_domain' => $order_info['sub_domain'],
  359.                 'delivery_type' => in_array($order_info['delivery'], array_keys($this->deliveryTypes)) ? $order_info['delivery'] : 1,
  360.                 'delivery_price' => 0,
  361.                 'reserv_cancelling' => $order_info['delivery'] == 3 ? date("Y-m-d H:i:s", strtotime("+{$eventInfo['reservation_period']} HOURS")) : null
  362.             );
  363.  
  364.             if (in_array($orderData['payment_type'], array('osmp', 'WMTerminals'))) {
  365.                 $hourExpired = 24;
  366.             } else {
  367.                 if ($orderData['delivery_type'] == 3) {
  368.                     $hourExpired = $eventInfo['reservation_period'];
  369.                 } else {
  370.                     $hourExpired = 1;
  371.                 }
  372.             }
  373.             $dateExpired = date('Y-m-d H:i:s', strtotime('+' . $hourExpired . ' HOURS'));
  374.             // 2. Detecting currency for order: currency for user and currency for billing
  375.             if ($this->paymentTypes[$orderData['payment_type']]['subtypes']) {
  376.                 $orderData['price_currency'] = $this->paymentTypes[$orderData['payment_type']]['subtypes'][$orderData['payment_subtype']]['currency'][$GLOBALS['lng']['id']];
  377.             } else {
  378.                 $orderData['price_currency'] = $this->paymentTypes[$orderData['payment_type']]['currency'][$GLOBALS['lng']['id']];
  379.  
  380.                 // English version of site - payment only with card
  381.                 if ($GLOBALS['lng']['id'] == 2) {
  382.                     // User currency EUR
  383.                     $orderData['price_currency'] = 'EUR';
  384.                     // Billing currency UAH
  385.                     $orderData['billing_currency'] = 'UAH';
  386.                 }
  387.             }
  388.            
  389.             if (!$orderData['billing_currency'])
  390.                 $orderData['billing_currency'] = $orderData['price_currency'];
  391.            
  392.             // 3. Loading fees for current tickets types
  393.             $bookingFees = ginst('TicketTypePayment')->getByTicketTypes($eventInfo['ticketTypes']);
  394.             $paymentCommission = array();
  395.  
  396.             // 4. Initial values or order
  397.             $totals = array(
  398.                 'subtotal' => 0,
  399.                 'subtotal_billing' => 0,
  400.                 'fee' => 0,
  401.                 'fee_billing' => 0,
  402.             );
  403.             $discountsList = $itemsDiscounted = array();
  404.             $orderItems = $orderPlaces = array();
  405.             $total_discount = 0;
  406.            
  407.             $isCertificateDiscount = false;
  408.  
  409.             // 5. Checking if any discount exists and can be applied
  410.             if ($eventInfo['discounts'] && $_SESSION['event-' . $eventInfo['id']]['discounts']) {
  411.                 $discountsList = ginst('Discount')->getCodes($eventInfo['id'], $_SESSION['event-' . $eventInfo['id']]['discounts']);
  412.                
  413.                 if ($discountsList['res']['total_ticket'] == 12) {
  414.                     $isCertificateDiscount = true;
  415.                 }
  416.             }
  417.            
  418.             // 6. Going throught the tickets without places
  419.             $blockPlacesIds = array();
  420.             $placesIds = array();
  421.             if ($order_info['amount']) {
  422.                 foreach ($order_info['amount'] as $id => $am) {
  423.  
  424.                     if (!$am)
  425.                         continue;
  426.                    
  427.                     if ($eventInfo['ticketTypes'][$id]) {
  428.                         $orderItems[$id] = $eventInfo['ticketTypes'][$id];
  429.                     } else {
  430.                         $orderItems[$id] = ginst('TicketType')->getById($id);
  431.                     }
  432.                     $orderItems[$id]['amount'] = $am;
  433.                
  434.                     if ($eventInfo['partner_id'] == 10) {
  435.                         $ext_block_place_id = $GLOBALS['dbh']->getOne("SELECT external_id FROM t_ticket_type WHERE id = '{$id}'");
  436.                         $blockPlacesIds[$ext_block_place_id] = $am;
  437.                     }
  438.  
  439.                     if($eventInfo['partner_id'] == 11 && $eventInfo['ib_scheme'] != 1){
  440.                         $ibreserv = ginst('InternetBilet')->addToFanzoneReserve($eventInfo['external_id'], $orderItems[$id]['external_id'], $am);
  441.                         if (!$ibreserv) {
  442.                             ginst('InternetBilet')->clearBasket($eventInfo['external_id']);
  443.                             return false;
  444.                         }
  445.                         $ibTickets[$id] = $ibreserv->result_details->ticket_ids;
  446.                     }
  447.                    
  448.                     if ($eventInfo['partner_id'] == ginst('FlashBox')->getServerId()) {
  449.                         $tmpSeats = ginst('FlashBox')->getTicketTypeSeats($id, $am, $dateExpired);
  450.                         if (empty($tmpSeats)) {
  451.                             ginst('FlashBox')->updateTicketType($eventInfo['external_id']);
  452.                             return false;
  453.                         }
  454.                         $blockPlacesIds = array_merge($blockPlacesIds, $tmpSeats);
  455.                         foreach ($tmpSeats as $key => $tid) {
  456.                             $itemsDiscounted[$id][++$key]['external_id'] = $tid;
  457.                         }
  458.                     }
  459.                    
  460.                     // Calculating ticket price
  461.                     $orderItems[$id]['currency'] = $orderData['price_currency'];
  462.                     $orderItems[$id]['price'] = ceil(ginst('Currency')->convert($orderItems[$id]['price_single'], $orderData['price_currency'], $orderItems[$id]['price_currency']));
  463.  
  464.                     $orderItems[$id]['currency_billing'] = $orderData['billing_currency'];
  465.                     $orderItems[$id]['price_billing'] = ceil(ginst('Currency')->convert($orderItems[$id]['price_single'], $orderData['billing_currency'], $orderItems[$id]['price_currency']));
  466.                    
  467.                     // Checking for fees
  468.                     if (empty($paymentCommission)) {
  469.                         $paymentCommission = $bookingFees[$id][$orderData['payment_type']];
  470.                     }
  471.                    
  472.                     if (in_array(ginst('TicketType')->getGroupId($id), array(6, 7))) {
  473.                         $childTicketTypeId = ginst('TicketTypeRelation')->getChildTicketTypeId($id);
  474.                         if ($eventInfo['ticketTypes'][$childTicketTypeId]) {
  475.                             $childTicketType = $eventInfo['ticketTypes'][$childTicketTypeId];
  476.                         } else {
  477.                             $childTicketType = ginst('TicketType')->getById($childTicketTypeId);
  478.                         }
  479.                        
  480.                         $subTypeAmount = $order_info['sub_amount'][$id][$childTicketTypeId];
  481.                        
  482.                         $orderItems[$id]['price_single'] = $orderItems[$id]['price'] =
  483.                         $orderItems[$id]['price_print_single'] = $orderItems[$id]['price_digital'] =
  484.                         $orderItems[$id]['price_billing'] =
  485.                         $subTypeAmount * $childTicketType['price_single'];
  486.                        
  487.                         $orderItems[$id]['subtypes_amount'] = $subTypeAmount;
  488.                     }
  489.  
  490.                     /* Calculate discount */
  491.                     $tmpCount = 0;
  492.                     for ($i = 1; $i <= $am; $i++) {
  493.                         $params = array (
  494.                             'id' => $id,
  495.                             'price_single' => $orderItems[$id]['price_single'],
  496.                             'price_currency' => $orderItems[$id]['price_currency'],
  497.                             'price' => $orderItems[$id]['price'],
  498.                             'order_price_currency' => $orderData['price_currency'],
  499.                             'billing_currency' => $orderData['billing_currency'],
  500.                             'iteration' => $tmpCount,
  501.                         );
  502.                         $discountInfo = Element_Discount::calcDiscount($discountsList, $params);
  503.                         $itemsDiscounted[$id][$i] = (!empty($itemsDiscounted[$id][$i])? array_merge($itemsDiscounted[$id][$i], $discountInfo) : $discountInfo);
  504.                         $total_discount += $itemsDiscounted[$id][$i]['discount'];
  505.                        
  506.                         $params['price'] -= $itemsDiscounted[$id][$i]['discount'];
  507.                         $itemsDiscounted[$id][$i] = array_merge($itemsDiscounted[$id][$i], Element_Commission::calcFee($bookingFees, $params));
  508.                         $totals['fee'] += $itemsDiscounted[$id][$i]['fee'];
  509.                         $totals['fee_billing'] += $itemsDiscounted[$id][$i]['fee_billing'];
  510.                         $tmpCount = $itemsDiscounted[$id][$i]['iteration'];
  511.                     }
  512.                    
  513.                     $totals['subtotal'] += $am * $orderItems[$id]['price'];
  514.                     $totals['subtotal_billing'] += $am * $orderItems[$id]['price_billing'];
  515.  
  516.                 }
  517.             }
  518.            
  519.             // 7. Going throught the karabas tickets
  520.             if ($order_info['partner_id'] == 1) {
  521.                 $basket = ginst('Karabas')->getBasket(array(
  522.                     'order_id' => $orderData['external_id'],
  523.                     '__auth' => $order_info['karabas_auth']
  524.                 ));
  525.                 if(empty($basket->items)) {
  526.                     ginst('Karabas')->changeOrder($orderData['external_id']);
  527.                     return false;
  528.                 }
  529.                
  530.                 foreach ($basket->items as $itemElem) {
  531.                     if ($itemElem->event == $order_info['session_id']) {
  532.                         $type_id = 0;
  533.                         foreach ($eventInfo['ticketTypes'] as $ticketType) {
  534.                             if ($ticketType['title'] == $itemElem->zone && (int)$ticketType['price_single'] == (int)$itemElem->price) {
  535.                                 $type_id = $ticketType['id'];
  536.                                 $row = $ticketType;
  537.                                 $row['extra'] = 'Ряд '.($itemElem->row ? $itemElem->row : '' ).', Место '.($itemElem->number ? $itemElem->number.' ' : '').'('.$itemElem->zone.')';
  538.                                 break;
  539.                             }
  540.                         }
  541.                         if ($type_id == 0) {
  542.                             ginst('Karabas')->changeOrder($orderData['external_id']);
  543.                             return false;
  544.                         }
  545.                        
  546.                         $row['bar_code_type'] = 'code128';
  547.                         $row['bar_code'] = $itemElem->barCode;
  548.  
  549.                         $row['type_place_id'] = 0;
  550.                         $row['currency'] = $orderData['price_currency'];
  551.                         $row['price'] = ceil(ginst('Currency')->convert($itemElem->price, $orderData['price_currency'], $row['price_currency']));
  552.  
  553.                         $row['currency_billing'] = $orderData['billing_currency'];
  554.                         $row['price_billing'] = ceil(ginst('Currency')->convert($itemElem->price, $orderData['billing_currency'], $row['price_currency']));
  555.  
  556.                         $row['external_id'] = $itemElem->id;
  557.                         $totals['subtotal'] += $row['price'];
  558.                         $totals['subtotal_billing'] += $row['price_billing'];
  559.                        
  560.                         $params = array (
  561.                             'id' => $row['id'],
  562.                             'price_single' => $row['price_single'],
  563.                             'price_currency' => $row['price_currency'],
  564.                             'price' => $row['price'],
  565.                             'order_price_currency' => $orderData['price_currency'],
  566.                             'billing_currency' => $orderData['billing_currency']
  567.                         );
  568.                         $row = array_merge($row, Element_Discount::calcDiscount($discountsList, $params));
  569.                         $total_discount += $row['discount'];
  570.                        
  571.                         // Checking for fees
  572.                         if(empty($paymentCommission)){
  573.                             $paymentCommission = $bookingFees[$type_id][$orderData['payment_type']];
  574.                         }
  575.                         $params['price'] -= $row['discount'];
  576.                         $row = array_merge($row, Element_Commission::calcFee($bookingFees, $params));
  577.                         $totals['fee'] += $row['fee'];
  578.                         $totals['fee_billing'] += $row['fee_billing'];
  579.  
  580.                         $orderPlaces[] = $row;
  581.                        
  582.                     }
  583.                 }
  584.             } elseif ($order_info['partner_id'] == 11 && $eventInfo['ib_scheme'] > 0) {
  585.                 /* Romko's and Dimosha gavnokod for InternetBillet scheme*/
  586.                 $booking = ginst('InternetBilet')->bookingSubmit($eventInfo['external_id']);
  587.                 $orderData['external_id'] = $booking->booking_id;
  588.                
  589.                 foreach ($booking->places as $place) {
  590.                     foreach ($eventInfo['ticketTypes'] as $ticketType) {
  591.                         if ($ticketType['title'] == $place->place_sector && (int)$ticketType['price_single'] == (int)$place->price) {
  592.                             $type_id = $ticketType['id'];
  593.                             $row = $ticketType;
  594.                             $row['extra'] = 'Ряд '.($place->place_row_num ? $place->place_row_num : '' ).', Место '.($place->place_seat_num ? $place->place_seat_num.' ' : '').'('.$place->place_sector.')';
  595.                             break;
  596.                         }
  597.                     }
  598.                     $row['type_place_id'] = 0;
  599.                     $row['bar_code_type'] = 'code128';
  600.                     $row['bar_code'] = $place->barcode;
  601.                     $row['currency'] = $orderData['price_currency'];
  602.                     $row['price'] = ceil(ginst('Currency')->convert($place->price, $orderData['price_currency'], $row['price_currency']));
  603.                     $row['currency_billing'] = $orderData['billing_currency'];
  604.                     $row['price_billing'] = ceil(ginst('Currency')->convert($place->price, $orderData['billing_currency'], $row['price_currency']));
  605.                     $row['external_id'] = $place->ticket_id;
  606.                     $totals['subtotal'] += $row['price'];
  607.                     $totals['subtotal_billing'] += $row['price_billing'];
  608.                    
  609.                     $params = array (
  610.                         'id' => $row['id'],
  611.                         'price_single' => $row['price_single'],
  612.                         'price_currency' => $row['price_currency'],
  613.                         'price' => $row['price'],
  614.                         'order_price_currency' => $orderData['price_currency'],
  615.                         'billing_currency' => $orderData['billing_currency']
  616.                     );
  617.                     $row = array_merge($row, Element_Discount::calcDiscount($discountsList, $params));
  618.                     $total_discount += $row['discount'];
  619.                    
  620.                     if (empty($paymentCommission)) {
  621.                         $paymentCommission = $bookingFees[$type_id][$orderData['payment_type']];
  622.                     }
  623.                     $params['price'] -= $row['discount'];
  624.                     $row = array_merge($row, Element_Commission::calcFee($bookingFees, $params));
  625.                     $totals['fee'] += $row['fee'];
  626.                     $totals['fee_billing'] += $row['fee_billing'];
  627.                        
  628.                     $orderPlaces[] = $row;
  629.                 }
  630.             } else {
  631.                 // 8. Going throught the tickets with places
  632.                
  633.                 if (!empty($eventInfo['is_scheme'])) {
  634.                     if (!empty($order_info['place']) && is_array($order_info['place'])) {
  635.                         foreach ($order_info['place'] as $type_id => $type_places) {
  636.  
  637.                             if ($eventInfo['ticketTypes'][$type_id]) {
  638.                                 $ticketType = $eventInfo['ticketTypes'][$type_id];
  639.                             } else {
  640.                                 $ticketType = ginst('TicketType')->getById($type_id);
  641.                             }
  642.  
  643.                             $tmpCount = 0;
  644.                             foreach ($type_places as $type_place_id) {
  645.                                
  646.                                 $row = $ticketType;
  647.                                
  648.                                 if ($eventInfo['partner_id'] == 11 && $eventInfo['external_id'] > 0 && $eventInfo['ib_scheme'] != 1) {//input into basket of Internet bilet
  649.                                     $row['external_id'] = $GLOBALS['dbh']->getOne("SELECT external_id FROM t_ticket_type_place WHERE id = {$type_place_id}");
  650.                                     if (!ginst('InternetBilet')->addToHallReserve($row['external_id'])) {
  651.                                         ginst('InternetBilet')->clearBasket($eventInfo['external_id']);
  652.                                         return false;
  653.                                     }
  654.                                 }
  655.                                
  656.                                 if ($eventInfo['partner_id'] == ginst('FlashBox')->getServerId()) {
  657.                                     if (false === ($ticket_id = $this->_flashBoxCheckPlace($type_place_id))) {
  658.                                         return false;
  659.                                     }
  660.                                     $row['external_id'] = $blockPlacesIds[] = $ticket_id;
  661.                                 }
  662.                                
  663.                                 $row['type_place_id'] = $type_place_id;
  664.  
  665.                                 $row['currency'] = $orderData['price_currency'];
  666.                                 $row['price'] = ceil(ginst('Currency')->convert($row['price_single'], $orderData['price_currency'], $row['price_currency']));
  667.  
  668.                                 $row['currency_billing'] = $orderData['billing_currency'];
  669.                                 $row['price_billing'] = ceil(ginst('Currency')->convert($row['price_single'], $orderData['billing_currency'], $row['price_currency']));
  670.  
  671.                                 // Premiera :: collect external id's for places
  672.                                 if ($order_info['partner_id'] == 10) {
  673.                                     $ext_place_id = $GLOBALS['dbh']->getOne("
  674.                                         SELECT vsp.external_id
  675.                                         FROM t_venue_section_place AS vsp
  676.                                         LEFT JOIN t_ticket_type_place AS ttp ON vsp.id = ttp.place_id
  677.                                         WHERE ttp.id = '{$type_place_id}'
  678.                                     ");
  679.                                     if ($ext_place_id) {
  680.                                         $row['extra_data'] = ginst('Premiera')->getPlaceData($eventInfo['external_id'], $ext_place_id);
  681.                                         //$row['external_id'] = $ext_place_id;
  682.                                         $placesIds[] = $ext_place_id;
  683.                                     }
  684.                                 }
  685.                                
  686.                                 $params = array (
  687.                                     'id' => $row['id'],
  688.                                     'price_single' => $row['price_single'],
  689.                                     'price_currency' => $row['price_currency'],
  690.                                     'price' => $row['price'],
  691.                                     'order_price_currency' => $orderData['price_currency'],
  692.                                     'billing_currency' => $orderData['billing_currency'],
  693.                                     'iteration' => $tmpCount,
  694.                                 );
  695.                                 $disc = Element_Discount::calcDiscount($discountsList, $params);
  696.                                 $tmpCount = $disc['iteration'];
  697.                                 unset($disc['iteration']);
  698.                                 $row = array_merge($row, $disc);
  699.                                 $total_discount += $row['discount'];
  700.                                 // Adding ticket price for subtotals
  701.                                 $totals['subtotal'] += $row['price'];
  702.                                 $totals['subtotal_billing'] += $row['price_billing'];
  703.  
  704.                                 // Checking for fees
  705.                                 if (empty($paymentCommission)) {
  706.                                     $paymentCommission = $bookingFees[$type_id][$orderData['payment_type']];
  707.                                 }
  708.                                 $params['price'] -= $row['discount'];
  709.                                 $row = array_merge($row, Element_Commission::calcFee($bookingFees, $params));
  710.                                 $totals['fee'] += $row['fee'];
  711.                                 $totals['fee_billing'] += $row['fee_billing'];
  712.  
  713.                                 // Saving this ticket for future storring it to DB
  714.                                 $orderPlaces[] = $row;
  715.                             }
  716.                         }
  717.                     }
  718.                 }
  719.                 if ($eventInfo['partner_id'] == 11 && $eventInfo['external_id'] > 0 && $eventInfo['ib_scheme'] != 1) {//submit order to Internet-bilet
  720.                     $orderData['external_id'] = ginst('InternetBilet')->bookingSubmit($eventInfo['external_id'])->booking_id;
  721.                 }
  722.             }
  723.            
  724.             // Premiera :: send places for freezing
  725.             if ($eventInfo['partner_id'] == 10) {
  726.                 $orderResult = ginst('Premiera')->submitOrder($eventInfo['external_id'], $placesIds, $blockPlacesIds);
  727.                 // success operation
  728.                 if (isset($orderResult->PlaceOrderResult->ErrorCode) && $orderResult->PlaceOrderResult->ErrorCode == 0 || empty($orderResult->PlaceOrderResult->orderList->OrderPlaceResultEx)) {
  729.                     $places = $orderResult->PlaceOrderResult->orderList->OrderPlaceResultEx;
  730.                     if (!is_array($places)) {
  731.                         $tmp = $places;
  732.                         $places = array();
  733.                         $places[] = $tmp;
  734.                     }
  735.                     $cnt = array();
  736.                     foreach ($places as $place) {
  737.                         foreach ($orderItems as $key => $oItem) {
  738.                             if ($place->sectionID == $oItem['external_id']) {
  739.                                 $cnt[$key]++;
  740.                                 if (empty($place->ticketCode) || empty($place->placeID)) {
  741.                                     return false;
  742.                                 }
  743.                                 $itemsDiscounted[$key][$cnt[$key]]['bar_code'] = $place->ticketCode;
  744.                                 $itemsDiscounted[$key][$cnt[$key]]['external_id'] = $place->placeID;
  745.                                 $itemsDiscounted[$key][$cnt[$key]]['extra'] = $place->url;
  746.                                 break;
  747.                             }
  748.                         }
  749.                         foreach ($orderPlaces as $key => $oPlace) {
  750.                             if ($place->sectionID == $oPlace['extra_data']['sectionID'] && $place->rowID == $oPlace['extra_data']['rowID'] && $place->position == $oPlace['extra_data']['position']) {
  751.                                 if (empty($place->ticketCode) || empty($place->placeID)) {
  752.                                     return false;
  753.                                 }
  754.                                 $orderPlaces[$key]['bar_code'] = $place->ticketCode;
  755.                                 $orderPlaces[$key]['external_id'] = $place->placeID;
  756.                                 $orderPlaces[$key]['extra'] = $place->url;
  757.                                 break;
  758.                             }
  759.                         }
  760.                     }
  761.                 } else {
  762.                     ginst('Premiera')->logError(array('places' => $placesIds, 'fanzones' => $blockPlacesIds),$orderResult->PlaceOrderResult);
  763.                     return false;
  764.                 }
  765.             }
  766.            
  767.             // submit tickets in the FlashBox system
  768.             if ($order_info['partner_id'] == ginst('FlashBox')->getServerId()) {
  769.                 if (false === ($submitData = ginst('FlashBox')->submitOrder($blockPlacesIds, $hourExpired * 60))) {
  770.                     return false;
  771.                 }
  772.                 $orderData['external_id'] = $submitData->booking_code;
  773.             }
  774.            
  775.             if (empty($orderItems) && empty($orderPlaces)) {
  776.                 return false;
  777.             }
  778.            
  779.             $certificate = $this->checkCertificate(array(
  780.                 'event' => $eventInfo,
  781.                 'items' => $orderItems,
  782.                 'places' => $orderPlaces
  783.             ));
  784.             if (!empty($certificate)) {
  785.                 $orderItems[$certificate['id']] = $certificate;
  786.             }
  787.            
  788.             //add $total_discount
  789.             $orderData['price_subtotal'] = $totals['subtotal'] - $total_discount;
  790.             // count fees
  791.            
  792.             if(!empty($paymentCommission)){
  793.                 $feeInfo = $paymentCommission;
  794.                 $feePrice = 0;
  795.                 $payPrice = ginst('Currency')->convert($orderData['price_subtotal'], $feeInfo['fee_currency'], $orderData['price_currency']);
  796.                
  797.                 if (!($orderData['city_id'] == 10184 && $orderData['payment_type'] == 'courier')) {
  798.                     if ($feeInfo['fee_type'] == 'percents' || $feeInfo['fee_type'] == 'both') {
  799.                         $feePrice = $feeInfo['fee_percents'] / 100 * $payPrice;
  800.                     }
  801.  
  802.                     if ($feeInfo['fee_type'] == 'amount' || $feeInfo['fee_type'] == 'both') {
  803.                         $feePrice += $feeInfo['fee_single'];
  804.                     }
  805.  
  806.                     if ($feeInfo['fee_type'] == 'percents_plus') {
  807.                         if($payPrice * $feeInfo['fee_percents'] / 100 > $feeInfo['fee_single']){
  808.                             $feePrice = $payPrice * $feeInfo['fee_percents'] / 100;
  809.                         } else{
  810.                             $feePrice = $feeInfo['fee_single'];
  811.                         }
  812.                     }
  813.                 }
  814.                
  815.                 $fee = ginst('Currency')->convert($feePrice, $orderData['price_currency'], $feeInfo['fee_currency']);
  816.                 $fee_billing = ginst('Currency')->convert($feePrice, $orderData['billing_currency'], $feeInfo['fee_currency']);
  817.  
  818.                 $totals['fee'] += $fee;
  819.                 $totals['fee_billing'] += $fee_billing;
  820.             }
  821.            
  822.             $orderData['price_fee'] = ceil($totals['fee']);
  823.             $orderData['price_total'] = $orderData['price_subtotal'] + $orderData['price_fee'];
  824.            
  825.             //fee -
  826.             if ($discount_amount > $total_discount && $isCertificateDiscount) {
  827.                 $subtractFee = $discount_amount - $total_discount;
  828.                
  829.                 if ($subtractFee <  $orderData['delivery_price']) {
  830.                     $feeSubtract = $orderData['price_fee'] - $subtractFee;
  831.                 }
  832.                 else if ($subtractFee >  $orderData['delivery_price']) {
  833.                     $feeSubtract = $orderData['price_fee'];
  834.                 }
  835.                
  836.                 $feeSubtractBilling = $feeSubtract;
  837.                 $toTotalFeeBilling = 0;
  838.                
  839.                 if ($orderData['price_fee'] != $orderData['billing_fee'] && $discount_amount > $total_discount) {
  840.                     $subtractFee = $discount_amount - $total_discount;
  841.                    
  842.                     if ($subtractFee <  $orderData['delivery_price']) {
  843.                         $feeSubtractBilling = $orderData['price_fee'] - $subtractFee;
  844.                     }
  845.                     else if ($subtractFee >  $orderData['delivery_price']) {
  846.                         $feeSubtractBilling = $orderData['price_fee'];
  847.                     }
  848.                    
  849.                     $toTotalFeeBilling = $feeSubtractBilling - $feeSubtract;
  850.                 }
  851.                
  852.                 $orderData['price_total'] -= ($feeSubtract + $toTotalFeeBilling);
  853.                
  854.                 $total_discount += $feeSubtract + $toTotalFeeBilling;
  855.             }
  856.             $orderData['discount'] = $total_discount;
  857.             $total_discount_billing = ginst('Currency')->convert($total_discount, $orderData['billing_currency'], $orderData['price_currency']);
  858.             $orderData['billing_price'] = $totals['subtotal_billing'] + ceil($totals['fee_billing']) - $total_discount_billing;
  859.            
  860.             //додавання ціни за доставку
  861.             if ($order_info['delivery'] == 2) {
  862.                 $deliveryInfo = array();
  863.                 $deliveryExecuteData = array
  864.                 (
  865.                     'country' => $order_info['country'],
  866.                     'province' => $order_info['region'],
  867.                     'city' => $order_info['city_id']
  868.                 );
  869.                 $delType = ginst('Delivery')->getDeliveryType($order_info['city_id']);
  870.                 $delPeriod = ginst('Delivery')->getDeliveryPeriod($delType, $order_info['city_id']);
  871.                 $orderData['delivery_expired'] = date('Y-m-d H:i', strtotime($orderData['date_created']) + 60 * 60 * 24 * $delPeriod);
  872.                 if ($order_info['city_id'] == 10184 || true) {
  873.                     $deliveryInfo = ginst('Delivery')->getMostExpressRates($eventInfo['id'], $order_info['city_id']);
  874.                     $freeDeliveryRate = $GLOBALS['dbh']->getOne("SELECT `value` FROM t_delivery_settings WHERE alias = 'free_delivery_kyiv'");
  875.                     if ($orderData['price_total'] >= $freeDeliveryRate && $order_info['city_id'] == 10184) {
  876.                         $deliveryInfo['deliveryPrice'] = '0.00';
  877.                     }
  878.                    
  879.                     $deliveryTmp = array
  880.                     (
  881.                         'street' => $order_info['street'],
  882.                         'house' => $order_info['house'],
  883.                         'flat' => $order_info['flat'],
  884.                         'zip' => $order_info['zip'],
  885.                         'comment' => $order_info['comment'],
  886.                         'street_id' => $order_info['street_id']
  887.                     );
  888.                 } else {
  889.                     $deliveryData = array
  890.                     (
  891.                         'recipient_city' => $order_info['city'],
  892.                         'public_price' => $orderData['billing_price'],
  893.                         'delivery_typeid' => $order_info['delivery_subtype']
  894.                     );
  895.                     $deliveryInfo = ginst('Delivery')->getNewPostRates($deliveryData);
  896.                    
  897.                     if ($order_info['delivery_subtype'] == 3) {
  898.                         $deliveryTmp = array
  899.                         (
  900.                             'street' => $order_info['street'],
  901.                             'house' => $order_info['house'],
  902.                             'flat' => $order_info['flat'],
  903.                             'zip' => $order_info['zip']
  904.                         );
  905.                     } else {
  906.                         $deliveryTmp = array
  907.                         (
  908.                             'ware_id' => $order_info['ware_id']
  909.                         );
  910.                     }
  911.                 }
  912.                                
  913.                 if (empty($deliveryInfo['deliveryPeriod']) || empty($deliveryInfo['deliveryPrice'])) return false;
  914.                
  915.                 $GLOBALS['dbh']->autoExecute('t_address', $deliveryExecuteData + $deliveryTmp);
  916.  
  917.                 $GLOBALS['dbh']->autoExecute('t_delivery', array(
  918.                     'address_from' => '10184',
  919.                     'address_to' => $GLOBALS['dbh']->getOne('SELECT LAST_INSERT_ID()'),
  920.                     'd_date' => $orderData['date_created'],
  921.                     'duration' => date("Y-m-d H:i:s", ltime() + $deliveryInfo['deliveryPeriod'] * 24 * 60 * 60),
  922.                     'zone' => '1',
  923.                     'courier_payment' => '1',
  924.                     'status' => '1',
  925.                 ));
  926.                
  927.                 $deliveryLastInsId = $GLOBALS['dbh']->getOne('SELECT LAST_INSERT_ID()');
  928.                
  929.                 $orderData['delivery_price'] = ceil(ginst('Currency')->convert($deliveryInfo['deliveryPrice'], $orderData['price_currency'], $this->paymentTypes[$orderData['payment_type']]['currency'][$GLOBALS['lng']['id']]));
  930.                 $orderData['price_total'] += ceil(ginst('Currency')->convert($deliveryInfo['deliveryPrice'], $orderData['price_currency'], $this->paymentTypes[$orderData['payment_type']]['currency'][$GLOBALS['lng']['id']]));
  931.                 $orderData['billing_price'] += $orderData['delivery_price'];
  932.                
  933.             }
  934.                
  935.             if ($total_discount > 0 && $GLOBALS['lng']['id'] == 2) {
  936.                 $total_discount = ginst('Currency')->convert($total_discount, 'uah', 'eur');
  937.             }
  938.            
  939.             $orderData['billing_fee'] = ceil($totals['fee_billing']);
  940.  
  941.             // for orders with zero price
  942.             if ($orderData['price_total'] <= 0 && !$isCertificateDiscount && $total_discount > 0){
  943.                 $GLOBALS['cStatus']->setError($GLOBALS['smarty']->get_config_vars('form_field_error') . '<br/>'.$GLOBALS['smarty']->get_config_vars('form_wrong_discount'));
  944.                 return false;
  945.             } elseif ($orderData['price_total'] <= 0 && $isCertificateDiscount) {
  946.                 $orderData['payment_type'] = 'certificate';
  947.                 $orderData['payment_subtype'] = '';
  948.             } elseif ($orderData['price_total'] == 0 && !$isCertificateDiscount) {
  949.                 $orderData['is_free'] = 1;
  950.                 $orderData['payment_type'] = 'free';
  951.                 $orderData['payment_subtype'] = 'real';
  952.             }
  953.            
  954.             // 9. If order is free - then price is zero
  955.             if ($orderData['is_free'] || $orderData['price_total'] < 0 || ($orderData['price_total'] == 0 && $isCertificateDiscount)) {
  956.                
  957.                 $orderData['billing_fee'] = '0.00';
  958.                 $orderData['billing_currency'] = 'UAH';
  959.  
  960.                 $orderData['price_fee'] = '0.00';
  961.                 $orderData['price_total'] = '0.00';
  962.                 $orderData['price_subtotal'] = '0.00';
  963.                 $orderData['price_currency'] = $this->paymentTypes[$orderData['payment_type']]['currency'][$GLOBALS['lng']['id']];
  964.                 $orderData['delivery_price'] = '0.00';
  965.                
  966.                 if ($orderData['is_free']) {
  967.                     $orderData['billing_price'] = '0.00';
  968.                 }
  969.                 else {
  970.                    
  971.                     if($orderData['delivery_price'] != 0) {
  972.                         $orderData['billing_price'] = (float) $orderData['billing_price'] + (float) $orderData['delivery_price'];
  973.                         $orderData['price_total'] = (float) $orderData['price_total'] + (float) $orderData['delivery_price'];
  974.                     } else {
  975.                         $orderData['billing_price'] = '0.00';
  976.                     }
  977.                    
  978.                     $negativeSum = true;
  979.                 }
  980.             }
  981.            
  982.             // 10. Checking for promo - we have to save promo_id
  983.             $orderData['promo_id'] = ginst('User')->promoExists();
  984.            
  985.            
  986.             $orderData['is_external'] = (int) $_SESSION['token_user_id'];
  987.            
  988.             // Registration to concert.ua
  989.             $userId = ginst('User')->checkUserByMail($orderData['email']);
  990.             if ($userId == 0) {
  991.                 $pass = rand(10000000, 99999999);
  992.                 $userInfo = array(
  993.                     'password'  => $pass,
  994.                     'mobile'    => $orderData['mobile'],
  995.                     'firstname' => $orderData['firstname'],
  996.                     'lastname'  => $orderData['lastname'],
  997.                     'city_id'   => (int)$orderData['city_id'],
  998.                     'email'     => $orderData['email'],
  999.                     'date_added'=> NOW
  1000.                 );
  1001.                 $userId = ginst('User')->createUser($userInfo);
  1002.                 if (!empty($_SESSION['token_user_id'])) {
  1003.                     ginst('Notices')->userAuthInfo($userId);
  1004.                 } else {
  1005.                     ginst('Notices')->create_user($userInfo);
  1006.                 }
  1007.             }
  1008.             $orderData['client_id'] = $userId;
  1009.            
  1010.             // 11. Creating new order
  1011.             $GLOBALS['dbh']->autoExecute('t_order', $orderData);
  1012.  
  1013.             // 12. Generating unique hash for order
  1014.             $orderData['id'] = $GLOBALS['dbh']->getOne('SELECT LAST_INSERT_ID()');
  1015.             $orderData['hash'] = md5($orderData['id'] . '-' . $eventInfo['merchant_secret'] . '-' . NOW . '-' . time());
  1016.             $GLOBALS['dbh']->autoExecute('t_order', array('hash' => $orderData['hash']), DB_AUTOQUERY_UPDATE, ' id = ' . $orderData['id']);
  1017.             if(empty($order_info['format'])) {
  1018.                 $order_info['format'] = $eventInfo['ticket_format_id'];
  1019.             }
  1020.             // 12.а Додання номеру замовлення
  1021.             if (in_array($order_info['delivery'], array(2, 3))) {
  1022.                 if ($order_info['delivery'] == 2) {
  1023.                     $GLOBALS['dbh']->autoExecute('t_delivery', array('order_id' => $orderData['id']), DB_AUTOQUERY_UPDATE, ' id = ' . $deliveryLastInsId);
  1024.                 }
  1025.                 $ticketFormat = ginst('TicketFormat')->getById((int)$order_info['format']);
  1026.                 if (empty($ticketFormat) || $ticketFormat['alias'] == 'a4' || $ticketFormat['is_a4'] == 0) {
  1027.                     $order_info['format'] = ginst('TicketFormat')->getTicketFormatId('termonew');
  1028.                 }
  1029.             }
  1030.            
  1031.             //12. b
  1032.             if ($eventInfo['extended_form']) {
  1033.                
  1034.                 $imgPath = DOC_ROOT."/dynamic/user/extended";
  1035.                 if (!is_dir($imgPath)) {
  1036.                     mkdir($imgPath, 0777, true);
  1037.                 }
  1038.                 if ($orderData['is_concert']) {
  1039.                     $ext = $order_info['photo_ext'];
  1040.                     $ch = curl_init("http://www.concert.ua/dynamic/user/extended/" . md5($orderData['email']) . ".{$ext}");
  1041.                     $fp = fopen("dynamic/user/extended/{$orderData['id']}.{$order_info['photo_ext']}", 'wb');
  1042.                     curl_setopt($ch, CURLOPT_FILE, $fp);
  1043.                     curl_setopt($ch, CURLOPT_HEADER, 0);
  1044.                     curl_exec($ch);
  1045.                     curl_close($ch);
  1046.                     fclose($fp);
  1047.                 } else {
  1048.                     $ext = substr($_FILES['photo_ext']['name'], strrpos($_FILES['photo_ext']['name'], '.') + 1);
  1049.  
  1050.                     $newName = sprintf($imgPath . '/%s.%s', $orderData['id'], $ext);
  1051.  
  1052.                     move_uploaded_file($_FILES['photo_ext']['tmp_name'], $newName);
  1053.                 }
  1054.                
  1055.                 if ($eventInfo['id'] == 5313) {
  1056.                     $GLOBALS['dbh']->autoExecute('t_kazantip', array(
  1057.                         'order_id' => $orderData['id'],
  1058.                         'lastname' => $orderData['lastname'],
  1059.                         'firstname' => $orderData['firstname'],
  1060.                         'patronymic'  => $order_info['middlename'],
  1061.                         'photo_ext'  => $ext,
  1062.                         'passport'  => $order_info['passport'],
  1063.                         'email'  => $orderData['email'],
  1064.                         'mobile' => $orderData['mobile'],
  1065.                         'sex'  => $order_info['sex'],
  1066.                         'city'  => $orderData['city_name'],
  1067.                         'country'  => ginst('Country')->getCountryNameByCityId($orderData['city_id'])
  1068.                     ));
  1069.                 }
  1070.             }
  1071.  
  1072.             // 13. Storing tickets without places to DB
  1073.             $extraOrderData = array();
  1074.            
  1075.             if ($orderItems) {
  1076.                 $extraOrderData['price_total'] = (float) $orderData['price_total'];
  1077.                 $extraOrderData['billing_price'] = (float) $orderData['billing_price'];
  1078.                 $extraOrderData['billing_fee'] = (float) $orderData['billing_fee'];
  1079.                 $extraOrderData['price_fee'] = (float) $orderData['price_fee'];
  1080.                 foreach ($orderItems as $k => $row){
  1081.                     for ($i = 1; $i <= $row['amount']; $i++) {
  1082.                        
  1083.                         $fPrice = $row['price'];
  1084.                         $fPriceBilling = $row['price_billing'];
  1085.  
  1086.                         $GLOBALS['dbh']->autoExecute('t_ticket', array(
  1087.                             'type_id' => $row['id'],
  1088.                             'order_id' => $orderData['id'],
  1089.                             'bar_code' => (!empty($itemsDiscounted[$k][$i]['bar_code']) ? $itemsDiscounted[$k][$i]['bar_code'] : ''),
  1090.                             'reservation_id' => $row['reservation_id'],
  1091.                             'used_deposit_id' => 0,
  1092.                             'is_test' => 0,
  1093.                             'offline_comments' => $order_info['comment'],
  1094.                             'user_id' => $order_info['user_id'] ? $order_info['user_id'] : 0,
  1095.                             'is_offline' => $order_info['user_id'] ? 1 : 0,
  1096.                             'used_discount_code_id' => $itemsDiscounted[$k][$i]['used_discount_code_id'], //add
  1097.                             'format_id' => $row['group_id'] != 1 ? 1 : ($order_info['format'] ? $order_info['format'] : 1),
  1098.                             'is_hidden' => $order_info['is_hidden'] == 1 ? 1 : 0,
  1099.                             'price' => $row['price'] - (float) $itemsDiscounted[$k][$i]['discount'], //add $itemsDiscounted[$i]
  1100.                             'fee' => ($orderData['is_free'] ? 0 : (isset($itemsDiscounted[$k][$i]['fee']) ? $itemsDiscounted[$k][$i]['fee'] : $row['fee'])) ,
  1101.                             'currency' => $orderData['price_currency'],
  1102.                             'price_billing' => $row['price_billing'] - (float) $itemsDiscounted[$k][$i]['discount_billing'],
  1103.                             'fee_billing' => ($orderData['is_free'] ? 0 : (isset($itemsDiscounted[$k][$i]['fee_billing']) ? $itemsDiscounted[$k][$i]['fee_billing'] : $row['fee_billing'])),
  1104.                             'discount' => (float) $itemsDiscounted[$k][$i]['discount'],
  1105.                             'currency_billing' => $orderData['billing_currency'],
  1106.                             'ticket_date' => $order_info['ticket_date'],
  1107.                             'external_id' => $itemsDiscounted[$k][$i]['external_id'] ? $itemsDiscounted[$k][$i]['external_id'] : 0,
  1108.                             'extra' => $itemsDiscounted[$k][$i]['extra'] ? $itemsDiscounted[$k][$i]['extra'] : '',
  1109.                         ));
  1110.                         $ticketId = $GLOBALS['dbh']->getOne('SELECT LAST_INSERT_ID()');
  1111.  
  1112.                         if($order_info['partner_id'] == 11 && $eventInfo['ib_scheme'] != 1){
  1113.                             $GLOBALS['dbh']->autoExecute('t_ticket', array('external_id' => $ibTickets[$k][$i-1]), DB_AUTOQUERY_UPDATE, "id = {$ticketId}");
  1114.                         }
  1115.  
  1116.                         // check for package ticket type
  1117.                         if ($row['group_id'] != 1) {
  1118.                             $subItems = ginst('TicketTypeRelation')->getTicketTypeRelation($orderData['language_id'],$row['id']);
  1119.                             if (!$subItems)
  1120.                                 continue;
  1121.                            
  1122.                             if (in_array($row['group_id'], array(6, 7))) {
  1123.                                 $subItems = array_fill(0, $row['subtypes_amount'], $subItems[0]);
  1124.                             }
  1125.  
  1126.                             if (!$orderData['is_free'] && !$orderData['is_deposit']) {
  1127.                                 $extraOrderData['billing_fee'] -= $row['fee_billing'];
  1128.                                 $extraOrderData['price_fee'] -= $row['fee'];
  1129.                                 $extraOrderData['price_total'] -= $row['fee'];
  1130.                                 $extraOrderData['billing_price'] -= $row['fee'];
  1131.                             }
  1132.                            
  1133.                             $placeNumber = 0;
  1134.                             foreach ($subItems as $key => $item) {
  1135.                                 $bookingFee = ginst('TicketTypePayment')->getByTicketTypes(array($item['type_id'] => 1));
  1136.                                 $item['price'] = ceil(ginst('Currency')->convert($item['price_single'], $orderData['price_currency'], $item['price_currency']));
  1137.                                 $item['price_billing'] = ceil(ginst('Currency')->convert($item['price_single'], $orderData['billing_currency'], $item['price_currency']));
  1138.                                 $feePrice = 0;
  1139.                                
  1140.                                 $fPrice -= $item['price'];
  1141.                                 $fPriceBilling -= $item['price_billing'];
  1142.                                
  1143.                                 $params = array (
  1144.                                     'id' => $item['type_id'],
  1145.                                     'price_single' => $orderItems[$id]['price_single'],
  1146.                                     'price_currency' => $orderItems[$id]['price_currency'],
  1147.                                     'price' => $item['price'],
  1148.                                     'order_price_currency' => $orderData['price_currency'],
  1149.                                     'billing_currency' => $orderData['billing_currency']
  1150.                                 );
  1151.  
  1152.                                 $data = Element_Commission::calcFee($bookingFees, $params);
  1153.                                 $item['fee'] += $data['fee'];
  1154.                                 $item['fee_billing'] += $data['fee_billing'];
  1155.                                                            
  1156.                                 if (!$orderData['is_free']) {
  1157.                                     $extraOrderData['billing_fee'] += $item['fee_billing'];
  1158.                                     $extraOrderData['price_fee'] += $item['fee'];
  1159.                                     $extraOrderData['price_total'] += $item['fee'];
  1160.                                     $extraOrderData['billing_price'] += $item['fee_billing'];
  1161.                                 }
  1162.                                
  1163.                                 $placeNumber += 1;
  1164.                                
  1165.                                 $subTicketData = array(
  1166.                                     'type_id' => $item['type_id'],
  1167.                                     'order_id' => $orderData['id'],
  1168.                                     'is_test' => 0,
  1169.                                     'offline_comments' => $order_info['comment'],
  1170.                                     'user_id' => $order_info['user_id'] ? $order_info['user_id'] : 0,
  1171.                                     'is_offline' => $order_info['user_id'] ? 1 : 0,
  1172.                                     'format_id' => $order_info['format'] ? $order_info['format'] : 1,
  1173.                                     'is_hidden' => $order_info['is_hidden'] == 1 ? 1 : 0,
  1174.                                     'price' => $item['price'],
  1175.                                     'fee' => ($orderData['is_free']) ? 0 : $item['fee'],
  1176.                                     'currency' => $orderData['price_currency'],
  1177.                                     'price_billing' => $item['price_billing'],
  1178.                                     'fee_billing' => ($orderData['is_free']) ? 0 : $item['fee_billing'],
  1179.                                     'currency_billing' => $orderData['billing_currency'],
  1180.                                     'parent_ticket_id' => $ticketId,
  1181.                                     'ticket_date' => $order_info['ticket_date']
  1182.                                 );
  1183.                                
  1184.                                 if (in_array($row['group_id'], array(6, 7))) {
  1185.                                     $subTicketData += array(
  1186.                                         'place_number' => $placeNumber,
  1187.                                         'parent_type_id' => $row['id']
  1188.                                     );
  1189.                                 }
  1190.                                
  1191.                                 $GLOBALS['dbh']->autoExecute('t_ticket', $subTicketData);
  1192.                             }
  1193.                            
  1194.                             if (in_array($row['group_id'], array(6, 7))) {
  1195.                                 $fPrice = $fPriceBilling = ceil(ginst('Currency')->convert(
  1196.                                     $row['tax_price'],
  1197.                                     $orderData['price_currency'],
  1198.                                     $row['tax_price_currency']
  1199.                                 ));
  1200.                                 if ($row['group_id'] == 7) {
  1201.                                     $fPrice *= $placeNumber;
  1202.                                     $fPriceBilling *= $placeNumber;
  1203.                                 }
  1204.                                 $extraOrderData['price_total'] += $fPrice;
  1205.                                 $extraOrderData['billing_price'] += $fPrice;
  1206.                                 $extraOrderData['tax_price'] = $fPrice;
  1207.                             }
  1208.                            
  1209.                             $ticketData = array(
  1210.                                 //'is_detached' => 1,
  1211.                                 'price' => $fPrice,
  1212.                                 'fee' => 0,
  1213.                                 'price_billing' => $fPriceBilling,
  1214.                                 'fee_billing' => 0
  1215.                             );
  1216.                            
  1217.                             if (in_array($row['group_id'], array(6, 7))) {
  1218.                                 $ticketData += array(
  1219.                                     'places_amount' => $placeNumber
  1220.                                 );
  1221.                             }
  1222.                            
  1223.                             // setting advanced ticket as detached to prevent second detaching
  1224.                             $GLOBALS['dbh']->autoExecute('t_ticket', $ticketData, DB_AUTOQUERY_UPDATE, ' id = ' . $ticketId);
  1225.                         }
  1226.                     }
  1227.                 }
  1228.             }
  1229.  
  1230.             // update order fee  
  1231.             if (!empty($extraOrderData)) {
  1232.                 $GLOBALS['dbh']->autoExecute('t_order', $extraOrderData, DB_AUTOQUERY_UPDATE, 'id = ' . $orderData['id']);
  1233.             }
  1234.             // 14. Storing tickets without places to DB
  1235.             if ($orderPlaces) {
  1236.                 foreach ($orderPlaces as $row) {
  1237.                     if ($orderData['partner_id'] == 0) {
  1238.                         $row['bar_code'] = '';
  1239.                     }
  1240.                     // Create ticket
  1241.                     $GLOBALS['dbh']->autoExecute('t_ticket', array(
  1242.                         'type_id' => $row['id'],
  1243.                         'order_id' => $orderData['id'],
  1244.                         'type_place_id' => $row['type_place_id'],
  1245.                         'bar_code' => (!empty($row['bar_code']) ? $row['bar_code'] : ''),
  1246.                         'bar_code_type' => (!empty($row['bar_code_type']) ? $row['bar_code_type'] : 'ean13'),
  1247.                         'reservation_id' => 0,
  1248.                         'used_deposit_id' => 0,
  1249.                         'is_test' => 0,
  1250.                         'offline_comments' => $order_info['comment'],
  1251.                         'user_id' => $order_info['user_id'] ? $order_info['user_id'] : 0,
  1252.                         'is_offline' => $order_info['user_id'] ? 1 : 0,
  1253.                         'used_discount_code_id' => $row['used_discount_code_id'], //add
  1254.                         'format_id' => $order_info['format'] ? $order_info['format'] : 1,
  1255.                         'is_hidden' => $order_info['is_hidden'] == 1 ? 1 : 0,
  1256.                         'price' => $row['price'] - (float) $row['discount'], //add $itemsDiscounted[$i]
  1257.                         'fee' => $orderData['is_free'] ? 0 : $row['fee'],
  1258.                         'currency' => $orderData['price_currency'],
  1259.                         'price_billing' => $row['price_billing'] - (float) $row['discount_billing'],
  1260.                         'fee_billing' => $orderData['is_free'] ? 0 : $row['fee_billing'],
  1261.                         'discount' => (float) $row['discount'],
  1262.                         'currency_billing' => $orderData['billing_currency'],
  1263.                         'ticket_date' => $order_info['ticket_date'],
  1264.                         'external_id' => $row['external_id'] ? $row['external_id'] : 0,
  1265.                         'extra' => $row['extra'] ? $row['extra'] : '',
  1266.                     ));
  1267.  
  1268.                     // Update place as reserved
  1269.                     $GLOBALS['dbh']->autoExecute('t_ticket_type_place', array(
  1270.                         'is_reserved' => 1,
  1271.                         'date_cancelling' => $dateExpired
  1272.                     ), DB_AUTOQUERY_UPDATE, ' id = ' . $row['type_place_id']);
  1273.                 }
  1274.             }
  1275.            
  1276.             if ($orderData['price_total'] == 0 && (isset($negativeSum) || $isCertificateDiscount)) {
  1277.                 ginst('Order')->apply($orderData['id'], false, array('sms_notify' => true, 'end_page_redirect' => true));
  1278.                 $orderData['negative_sum'] = true;
  1279.             }
  1280.  
  1281.             if ($order_info['delivery'] == 1) {
  1282.                 ginst('Api')->internalCreateBooking($orderData['id']);
  1283.                 if (!empty($_SESSION['token_user_id'])) {
  1284.                     $GLOBALS['dbh']->autoExecute('t_order', array(
  1285.                         'seller_id' => $_SESSION['token_user_id'],
  1286.                         'is_external' => $_SESSION['token_user_id']
  1287.                     ), DB_AUTOQUERY_UPDATE, ' id = ' . $orderData['id']);
  1288.                     $GLOBALS['dbh']->autoExecute('t_ticket', array(
  1289.                         'user_id' => $_SESSION['token_user_id']
  1290.                     ), DB_AUTOQUERY_UPDATE, ' order_id = ' . $orderData['id']);
  1291.                     unset($_SESSION['token_user_id']);
  1292.                 }
  1293.             }
  1294.             if ($eventInfo['partner_id'] == ginst('Kassir24')->getServerId()) {
  1295.                 if (ginst('Kassir24')->submitOrder($orderData['id']) === false) {
  1296.                     return false;
  1297.                 }
  1298.             }
  1299.            
  1300.             unset($_SESSION['event-' . $eventInfo['id']]);
  1301.             unset($_SESSION['event-' . $eventInfo['id']]['discounts']);
  1302.             unset($_SESSION['reservation-' . $eventInfo['id']]);
  1303.  
  1304.             return $orderData;
  1305.         }
  1306.        
  1307.         public function duplicate($order_id = false) {
  1308.             if (!$order_id)
  1309.                 return false;
  1310.  
  1311.             $orderInfo = $GLOBALS['dbh']->getRow('SELECT * FROM t_order WHERE id = ?', array($order_id));
  1312.            
  1313.             if ($orderInfo['partner_id'] == 1) {
  1314.                 ginst('Karabas')->changeOrder($orderInfo['external_id']);
  1315.                 return false;
  1316.             }
  1317.            
  1318.             $eventInfo = ginst('Event')->getById($orderInfo['event_id']);
  1319.             $newOrderInfo = $orderInfo;
  1320.             $newOrderInfo['secret_code'] = $this->getSecretCode();
  1321.  
  1322.             ginst('TicketTypePlace')->updateReservedPlaces();
  1323.  
  1324.  
  1325.             // 1. Creating new entry in t_order table
  1326.             unset($newOrderInfo['id']);
  1327.  
  1328.             $newOrderInfo['paid_status'] = ORDER_STATUS_NEW;
  1329.             $newOrderInfo['ip_address'] = get_real_ip();
  1330.             $newOrderInfo['date_created'] = NOW;
  1331.  
  1332.             $GLOBALS['dbh']->autoExecute('t_order', $newOrderInfo);
  1333.  
  1334.             $new_order_id = $newOrderInfo['id'] = $GLOBALS['dbh']->getOne('SELECT LAST_INSERT_ID()');
  1335.             $newOrderInfo['hash'] = md5($newOrderInfo['id'] . '-' . $eventInfo['merchant_secret'] . '-' . NOW . '-' . time());
  1336.  
  1337.             $GLOBALS['dbh']->autoExecute('t_order', array(
  1338.                 'hash' => $newOrderInfo['hash'],
  1339.                     ), DB_AUTOQUERY_UPDATE, ' id = ' . $newOrderInfo['id']);
  1340.  
  1341.  
  1342.             // 2. Creating new entries in t_ticket table
  1343.             $tickets = $GLOBALS['dbh']->getAll('SELECT * FROM t_ticket WHERE order_id = ?', array($order_id));
  1344.  
  1345.             $isGood = true;
  1346.             $ticketTypePlaceIds = array();
  1347.  
  1348.             foreach ($tickets as $ticket) {
  1349.                 unset($ticket['id']);
  1350.  
  1351.                 $ticket['order_id'] = $new_order_id;
  1352.                 $ticket['is_canceled'] = 0;
  1353.  
  1354.                 $GLOBALS['dbh']->autoExecute('t_ticket', $ticket);
  1355.  
  1356.                 if (!$ticket['reservation_id'] && !$ticket['parent_ticket_id'] && !$ticket['used_deposit_id']) {
  1357.                     // Checking for availibility and enough amount for purchase
  1358.                     if (!isset($eventInfo['ticketTypes'][$ticket['type_id']]) || !$eventInfo['ticketTypes'][$ticket['type_id']]['cnt_max']) {
  1359.                         $isGood = false;
  1360.                         break;
  1361.                     } else {
  1362.                         $eventInfo['ticketTypes'][$ticket['type_id']]['cnt_max']--;
  1363.                     }
  1364.                 }
  1365.  
  1366.                 if ($ticket['type_place_id']) {
  1367.  
  1368.                     // We have to check that this place is available
  1369.  
  1370.                     $tmp = $GLOBALS['dbh']->getRow('SELECT * FROM t_ticket_type_place WHERE id = ?', array($ticket['type_place_id']));
  1371.  
  1372.                     if ($tmp['id'] && !$tmp['is_reserved'] && !$tmp['is_sold']) {
  1373.                         $ticketTypePlaceIds[] = $ticket['type_place_id'];
  1374.                     } else {
  1375.                         $isGood = false;
  1376.                         break;
  1377.                     }
  1378.                 }
  1379.             }
  1380.  
  1381.             if ($isGood) {
  1382.  
  1383.                 // 3. Updating entries in t_ticket_type_place table
  1384.                 if ($ticketTypePlaceIds) {
  1385.                     $GLOBALS['dbh']->autoExecute('t_ticket_type_place', array(
  1386.                         'is_reserved' => 1,
  1387.                         'date_cancelling' => $orderInfo['payment_type'] == 'osmp' ? date('Y-m-d H:i:s', strtotime('+24 HOURS')) : date('Y-m-d H:i:s', strtotime('+60 MINUTES')),
  1388.                             ), DB_AUTOQUERY_UPDATE, ' id IN (' . implode(',', $ticketTypePlaceIds) . ')');
  1389.                 }
  1390.  
  1391.                 return $new_order_id;
  1392.             } else {
  1393.  
  1394.                 // Deleting cloned order
  1395.                 $GLOBALS['dbh']->query('DELETE FROM t_order WHERE id = ?', array($new_order_id));
  1396.  
  1397.                 return false;
  1398.             }
  1399.         }
  1400.  
  1401.         public function get($order_id, $field_name = 'id', $is_cache = true, $is_force = false) {
  1402.  
  1403.             if (!$order_id)
  1404.                 return;
  1405.             if ($this->cache[$order_id] && $is_cache)
  1406.                 return $this->cache[$order_id];
  1407.  
  1408.             $tmp = $GLOBALS['dbh']->getRow('
  1409.                 SELECT t_order.*, t_event.session_id, t_event.date_event
  1410.                 FROM t_order
  1411.                 LEFT JOIN t_event ON t_event.id = t_order.event_id
  1412.                 WHERE t_order.' . $field_name . ' = ?', array($order_id));
  1413.  
  1414.             if (!$tmp['id'])
  1415.                 return;
  1416.             $order_id = $tmp['id'];
  1417.  
  1418.             $orderInfo = $tmp;
  1419.  
  1420.             if (!$orderInfo['secret_code']) {
  1421.                 $orderInfo['secret_code'] = $this->getSecretCode();
  1422.  
  1423.                 $GLOBALS['dbh']->autoExecute($this->table_name, array(
  1424.                     'secret_code' => $orderInfo['secret_code'],
  1425.                         ), DB_AUTOQUERY_UPDATE, ' id = ' . $order_id);
  1426.             }
  1427.  
  1428.             if (!$orderInfo['id']) {
  1429.                 unset($this->cache[$order_id]);
  1430.                 return;
  1431.             }
  1432.  
  1433.             $orderInfo['items'] = $GLOBALS['dbh']->getAll('
  1434.                 SELECT
  1435.                     t_ticket_type.*, t_ticket.*, t_ticket_type_content.title,t_ticket_type.certificate_id AS cer_id, t_ticket_type_content.title_print, t_reservation.bar_code AS reservation_bar_code, t_ticket.price AS ticket_price, t_ticket.currency AS ticket_currency,
  1436.                     t_event_content.title AS event_title,
  1437.                     t_event.alias AS event_alias,
  1438.                     t_ticket_deposit.id AS deposit_id, t_ticket_deposit.deposit_price, t_ticket_deposit.deposit_code,
  1439.                     t_ticket_deposit.deposit_currency,
  1440.                     t_discount_code.code AS discount_code, t_discount_event.is_percents, t_discount_event.amount AS discount_amount, t_discount_event.with_discount
  1441.                 FROM
  1442.                     t_ticket
  1443.                 LEFT JOIN t_ticket_type ON (t_ticket_type.id = t_ticket.type_id)
  1444.                 LEFT JOIN t_event ON (t_event.id = t_ticket_type.event_id)
  1445.                 LEFT JOIN t_event_content ON (t_event_content.id = t_ticket_type.event_id AND t_event_content.language_id = ?)
  1446.                 LEFT JOIN t_ticket_type_content ON (t_ticket_type.id = t_ticket_type_content.id AND t_ticket_type_content.language_id = ?)
  1447.                 LEFT JOIN t_reservation ON (t_ticket.reservation_id = t_reservation.id)
  1448.                 ' . ($orderInfo['is_deposit'] ? ' LEFT JOIN t_ticket_deposit ON (t_ticket.id = t_ticket_deposit.deposited_ticket_id ) ' : '
  1449.                 LEFT JOIN t_ticket_deposit ON (t_ticket.used_deposit_id = t_ticket_deposit.id )
  1450.                 ') . '
  1451.                 LEFT JOIN t_discount_code ON (t_ticket.used_discount_code_id = t_discount_code.id )
  1452.                 LEFT JOIN t_discount_event ON (t_discount_event.discount_id = t_discount_code.discount_id  AND t_discount_event.event_id = t_event.id)
  1453.                 WHERE
  1454.                     t_ticket.order_id = ?
  1455.                 ', array($orderInfo['language_id'], $orderInfo['language_id'], $orderInfo['id']));
  1456.  
  1457.  
  1458.             $orderInfo['packages'] = array();
  1459.             $orderInfo['items_unique'] = array();
  1460.             $orderInfo['items_count'] = 0;
  1461.             $orderInfo['places'] = array();
  1462.             $orderInfo['deposit_price_full'] = $orderInfo['deposit_price_left'] = '';
  1463.             $cur = '';
  1464.            
  1465.             foreach ($orderInfo['items'] as $k => $row) {
  1466.                 if (!isset($orderInfo['tickets_format_id']) && $row['group_id'] == 1) {
  1467.                     $orderInfo['tickets_format_id'] = $row['format_id'];
  1468.                 }
  1469.                 $orderInfo['groups'][$row['group_id']] = 1;
  1470.                 $orderInfo['types'][$row['type_id']] = 1;
  1471.                 $orderInfo['items_count']++;
  1472.                
  1473.                 if (!isset($orderInfo['items_unique'][$row['type_id']])) {
  1474.                     $orderInfo['items_unique'][$row['type_id']] = $row;
  1475.                     $orderInfo['items_unique'][$row['type_id']]['amount'] = 1;
  1476.                 } else {
  1477.                     $orderInfo['items_unique'][$row['type_id']]['amount']++;
  1478.                 }
  1479.  
  1480.                 if ($row['group_id'] == 2) {
  1481.                     $orderInfo['packages'][$row['id']] = $row;
  1482.                 }
  1483.  
  1484.                 if ($row['type_place_id']) {
  1485.                     $orderInfo['places'][$row['type_place_id']] = array();
  1486.                 }
  1487.             }
  1488.  
  1489.             if ($orderInfo['places']) {
  1490.                 $orderInfo['places'] = ginst('Place')->getQuotaByIds(array_keys($orderInfo['places']));
  1491.             }
  1492.  
  1493.             $orderInfo['payment_title'] = $this->paymentTypes[$orderInfo['payment_type']]['title'];
  1494.  
  1495.             if ($orderInfo['payment_subtype']) {
  1496.                 $orderInfo['currency_title'] = $this->paymentTypes[$orderInfo['payment_type']]['subtypes'][$orderInfo['payment_subtype']];
  1497.             } else {
  1498.                 $orderInfo['currency_title'] = $this->paymentTypes[$orderInfo['payment_type']]['currency'];
  1499.             }
  1500.  
  1501.             $orderInfo['currency_title'] = $orderInfo['price_currency'];
  1502.  
  1503.             if (in_array($orderInfo['paid_status'], array(ORDER_STATUS_COMPLETE, ORDER_STATUS_COURIER, ORDER_STATUS_PREPAY)) && !$orderInfo['is_deposit']) {
  1504.                 foreach ($orderInfo['items'] as $k => $row) {
  1505.                     $bcImg = ginst('Barcode')->getImage(array(
  1506.                         'code' => $row['bar_code'],
  1507.                         'code_type' => $row['bar_code_type'],
  1508.                         'type' => 'ticket',
  1509.                         'is_force' => $is_force,
  1510.                             ));
  1511.  
  1512.                     $orderInfo['items'][$k]['bar_code_image'] = $bcImg['filename'];
  1513.                     $orderInfo['items'][$k]['bar_code_image_vertical'] = $bcImg['filename_vert'];
  1514.                     $orderInfo['items'][$k]['bar_code_image_vertical1'] = $bcImg['filename_vert1'];
  1515.                     $orderInfo['items'][$k]['bar_code_image_large'] = $bcImg['filename_large'];
  1516.                     $orderInfo['items'][$k]['bar_code_image_custom'] = $bcImg['filename_custom'];
  1517.                     $orderInfo['items'][$k]['bar_code_image_custom1'] = $bcImg['filename_custom1'];
  1518.  
  1519.                     $orderInfo['items'][$k] = ginst('TicketType')->fixFields($orderInfo['items'][$k]);
  1520.  
  1521.                 }
  1522.             }
  1523.  
  1524.             $orderInfo['payment'] = $this->paymentTypes[$orderInfo['payment_type']];
  1525.  
  1526.             // Left to pay
  1527.             $orderInfo['price_left'] = $orderInfo['billing_price'] - $orderInfo['paid_total'];
  1528.  
  1529.             // Seconds left to confirm
  1530.             if ($orderInfo['paid_status'] == ORDER_STATUS_NEW) {
  1531.                 $orderInfo['seconds_left'] = ORDER_CONFIRM_TIME + ( strtotime($orderInfo['date_created']) - strtotime(NOW) );
  1532.             }
  1533.            
  1534.             if ($orderInfo['delivery_type'] == 2) {
  1535.                
  1536.                 if ($orderInfo['city_id'] == 10184 || true) {
  1537.                     $orderInfo['addr'] = ginst('Delivery')->getMostExpressDeliveryContent($order_id);
  1538.                     $orderInfo['manager_email'] = ginst('Delivery')->getManagerEmails();
  1539.                 } else {
  1540.                     $orderInfo['addr'] = ginst('Delivery')->getNewPostDeliveryContent($order_id);
  1541.                 }
  1542.                
  1543.                 $orderInfo['delivery_status'] = $GLOBALS['dbh']->getOne('SELECT
  1544.                                                                             name_ua
  1545.                                                                         FROM t_delivery_status AS ds
  1546.                                                                         LEFT JOIN t_most_express_content AS mec ON ds.`status` = mec.`code`
  1547.                                                                         WHERE ds.`order_id` = ? ORDER BY order_id DESC', array($orderInfo['id']));
  1548.                
  1549.             }
  1550.  
  1551.             $this->cache[$order_id] = $orderInfo;
  1552.  
  1553.             return $orderInfo;
  1554.            
  1555.         }
  1556.        
  1557.         /**
  1558.          * Returns short information by order
  1559.          *
  1560.          * @global object $dbh
  1561.          * @param int $orderId
  1562.          * @param array $fields - fields are necessary to get from table
  1563.          * @author y.stefanyuk
  1564.          * @return array
  1565.          */
  1566.         public function getShortInfo($orderId = null, $fields = array())
  1567.         {
  1568.             global $dbh;
  1569.            
  1570.             if (!$orderId || !$fields) {
  1571.                 return;
  1572.             }
  1573.            
  1574.             $order = $dbh->getRow("
  1575.                 SELECT " . implode(",", $fields). "
  1576.                 FROM {$this->table_name}
  1577.                 WHERE `id` = ?
  1578.             ", array($orderId));
  1579.  
  1580.             return $order;
  1581.         }
  1582.  
  1583.         public function apply($order_id, $response_message = "", $params = array(), $confirmOrder = array()) {
  1584.  
  1585.             if (!isset($params['email_notify']))
  1586.                 $params['email_notify'] = true;
  1587.             if (!isset($params['generate_pdf']))
  1588.                 $params['generate_pdf'] = true;
  1589.             $cache = true;
  1590.             if(!empty($params['false_cache'])){
  1591.                 $cache = false;
  1592.             }
  1593.             $orderInfo = $this->get($order_id, 'id', $cache);
  1594.             $logFile = fopen(DOC_ROOT ."log/apply_". date("Y-F") .".log", "a");
  1595.             fwrite($logFile, "\n".date('Y-m-d H:i:s')."\n");
  1596.             fwrite($logFile, 'orderId: '.$order_id."\n");
  1597.             $debug = debug_backtrace();
  1598.             foreach($debug as $ind => $info) {
  1599.                 fwrite($logFile, 'index: '.$ind."\n");
  1600.                 fwrite($logFile, 'file: '.$info['file']."\n");
  1601.                 if (!empty($info['args'])) {
  1602.                     fwrite($logFile, 'args: '.serialize($info['args'])."\n");
  1603.                 }
  1604.             }
  1605.             fclose($logFile);
  1606.            
  1607.             if ($orderInfo['paid_status'] == ORDER_STATUS_COMPLETE ||
  1608.                 $orderInfo['paid_status'] == ORDER_STATUS_FAILED ||
  1609.                 $orderInfo['paid_status'] == ORDER_STATUS_PREPAY
  1610.             )
  1611.                 return;
  1612.            
  1613.             // 1. Updating status of order - for preventing duplicates of paid orders
  1614.            
  1615.             if ($orderInfo['partner_id'] == 10 && $orderInfo['paid_status'] != ORDER_STATUS_COURIER) {
  1616.                 foreach ($orderInfo['items'] as $item) {
  1617.                     $payTicketRes = ginst('Premiera')->payTicket($item['external_id']);
  1618.                     if ($payTicketRes == 0) {
  1619.                         $GLOBALS['dbh']->query("UPDATE `t_ticket` SET `bar_code_type` = 'code128' WHERE `external_id` = '{$item['external_id']}' AND `order_id` = '{$order_id}' ");
  1620.                     } else {
  1621.                         return false;
  1622.                     }
  1623.                 }
  1624.             }
  1625.            
  1626.             if ($orderInfo['delivery_type'] == 1) {
  1627.                 if (in_array($orderInfo['paid_status'], array(ORDER_STATUS_NEW, ORDER_STATUS_PROCESSING, ORDER_STATUS_OFFLINE, ORDER_STATUS_PARTIALLY))) {
  1628.                     if ($orderInfo['partner_id'] == 1) {
  1629.                         if (!$this->karabasSetOrderStatus($orderInfo['id'])) {
  1630.                             return false;
  1631.                         }
  1632.                     }
  1633.                     if ($orderInfo['partner_id'] == 11) {
  1634.                         if (!$this->ibConfirmOrder(array('ext_id' => $orderInfo['external_id'], 'order_id' => $orderInfo['id']), '1')) {
  1635.                             return false;
  1636.                         };
  1637.                     }
  1638.                     if ($orderInfo['partner_id'] == ginst('FlashBox')->getServerId()) {
  1639.                         if (!$this->_flashBoxConfirmOrder($order_id)) {
  1640.                             return false;
  1641.                         }
  1642.                     }
  1643.                     if ($orderInfo['partner_id'] == ginst('Kassir24')->getServerId()) {
  1644.                         if (!ginst('Kassir24')->confirmOrder($order_id)) {
  1645.                             return false;
  1646.                         }
  1647.                     }
  1648.                     $GLOBALS['dbh']->autoExecute($this->table_name, array(
  1649.                         'paid_status' => ORDER_STATUS_COMPLETE,
  1650.                         'paid_description' => $response_message,
  1651.                         'date_confirmed' => NOW,
  1652.                     ), DB_AUTOQUERY_UPDATE, ' id = ' . $orderInfo['id']);
  1653.                 } else {
  1654.                     return;
  1655.                 }
  1656.             } elseif ($orderInfo['delivery_type'] == 2) {
  1657.                 if (in_array($orderInfo['paid_status'], array(ORDER_STATUS_PROCESSING, ORDER_STATUS_OFFLINE, ORDER_STATUS_PARTIALLY))) {
  1658.                     if ($orderInfo['partner_id'] == 1) {
  1659.                         if (!$this->karabasSetOrderStatus($orderInfo['id'])) {
  1660.                             return false;
  1661.                         }
  1662.                     }
  1663.                     if ($orderInfo['partner_id'] == 11) {
  1664.                         if (!$this->ibConfirmOrder(array('ext_id' => $orderInfo['external_id'], 'order_id' => $orderInfo['id']), '2')) {
  1665.                             return false;
  1666.                         };
  1667.                     }
  1668.                     if ($orderInfo['partner_id'] == ginst('FlashBox')->getServerId()) {
  1669.                         if (!$this->_flashBoxConfirmOrder($order_id)) {
  1670.                             return false;
  1671.                         }
  1672.                     }
  1673.                     if ($orderInfo['partner_id'] == ginst('Kassir24')->getServerId()) {
  1674.                         if (!ginst('Kassir24')->confirmOrder($order_id)) {
  1675.                             return false;
  1676.                         }
  1677.                     }
  1678.                     $GLOBALS['dbh']->autoExecute($this->table_name, array(
  1679.                         'paid_status' => ORDER_STATUS_PREPAY,
  1680.                         'paid_description' => $response_message,
  1681.                         'date_confirmed' => NOW,
  1682.                     ), DB_AUTOQUERY_UPDATE, ' id = ' . $orderInfo['id']);
  1683.                 } elseif ($orderInfo['paid_status'] == ORDER_STATUS_COURIER) {
  1684.                     if ($orderInfo['partner_id'] == 1) {
  1685.                         if (!$this->karabasSetOrderStatus($orderInfo['id'])) {
  1686.                             return false;
  1687.                         }
  1688.                     }
  1689.                     if ($orderInfo['partner_id'] == 11) {
  1690.                         if (!$this->ibConfirmOrder(array('ext_id' => $orderInfo['external_id'], 'order_id' => $orderInfo['id']), '3')) {
  1691.                             return false;
  1692.                         };
  1693.                     }
  1694.                     $GLOBALS['dbh']->autoExecute($this->table_name, array(
  1695.                         'paid_status' => ORDER_STATUS_COMPLETE,
  1696.                         'paid_description' => $response_message,
  1697.                         'date_confirmed' => NOW,
  1698.                     ), DB_AUTOQUERY_UPDATE, ' id = ' . $orderInfo['id']);
  1699.                     return;
  1700.                 } else {
  1701.                     if ($orderInfo['partner_id'] == 1) {
  1702.                         if (!$this->karabasSetOrderStatus($orderInfo['id'], 3)) {
  1703.                             return false;
  1704.                         }
  1705.                     }
  1706.                     if ($orderInfo['partner_id'] == 11) {
  1707.                         $deliveryPeriod = 11;
  1708.                         $deliveryDate = date('d.m.Y H:i', strtotime($orderInfo['date_created']) + 60 * 60 * 24 * $deliveryPeriod);
  1709.                         $GLOBALS['dbh']->query("UPDATE `t_order` SET `delivery_expired` = STR_TO_DATE('{$deliveryDate}','%d.%m.%Y %H:%i') WHERE `id` = {$orderInfo['id']}");
  1710.                     }
  1711.                     if ($orderInfo['partner_id'] == ginst('FlashBox')->getServerId()) {
  1712.                         if (!$this->_flashBoxConfirmOrder($order_id)) {
  1713.                             return false;
  1714.                         }
  1715.                     }
  1716.                     if ($orderInfo['partner_id'] == ginst('Kassir24')->getServerId()) {
  1717.                         if (!ginst('Kassir24')->confirmOrder($order_id)) {
  1718.                             return false;
  1719.                         }
  1720.                     }
  1721.                     $GLOBALS['dbh']->autoExecute($this->table_name, array(
  1722.                         'paid_status' => ORDER_STATUS_COURIER,
  1723.                         'paid_description' => $response_message,
  1724.                         'date_confirmed' => NOW,
  1725.                     ), DB_AUTOQUERY_UPDATE, ' id = ' . $orderInfo['id']);
  1726.                 }
  1727.             } elseif ($orderInfo['delivery_type'] == 3) {
  1728.                 if ($orderInfo['paid_status'] == ORDER_STATUS_CASH) {
  1729.                     if ($orderInfo['partner_id'] == 1) {
  1730.                         if (!$this->karabasSetOrderStatus($orderInfo['id'])) {
  1731.                             return false;
  1732.                         }
  1733.                     }
  1734.                     if ($orderInfo['partner_id'] == 11) {
  1735.                         if (!$this->ibConfirmOrder(array('ext_id' => $orderInfo['external_id'], 'order_id' => $orderInfo['id']), '3')) {
  1736.                             return false;
  1737.                         };
  1738.                     }
  1739.                     if ($orderInfo['partner_id'] == ginst('FlashBox')->getServerId()) {
  1740.                         if (!$this->_flashBoxConfirmOrder($order_id)) {
  1741.                             return false;
  1742.                         }
  1743.                     }
  1744.                     if ($orderInfo['partner_id'] == ginst('Kassir24')->getServerId()) {
  1745.                         if (!ginst('Kassir24')->confirmOrder($order_id)) {
  1746.                             return false;
  1747.                         }
  1748.                     }
  1749.                     $GLOBALS['dbh']->autoExecute($this->table_name, array(
  1750.                         'paid_status' => ORDER_STATUS_COMPLETE,
  1751.                         'date_confirmed' => NOW,
  1752.                     ), DB_AUTOQUERY_UPDATE, ' id = ' . $orderInfo['id']);
  1753.                     return;
  1754.                 } else {
  1755.                     if ($orderInfo['partner_id'] == 1) {
  1756.                         if (!$this->karabasSetOrderStatus($orderInfo['id'], 3)) {
  1757.                             return false;
  1758.                         }
  1759.                     }
  1760.                     if ($orderInfo['partner_id'] == 11) {
  1761.                         $deliveryPeriod = 11;
  1762.                         $deliveryDate = date('d.m.Y H:i', strtotime($orderInfo['date_created']) + 60 * 60 * 24 * $deliveryPeriod);
  1763.                         $GLOBALS['dbh']->query("UPDATE `t_order` SET `delivery_expired` = STR_TO_DATE('{$deliveryDate}','%d.%m.%Y %H:%i') WHERE `id` = {$orderInfo['id']}");
  1764.                     }
  1765.                     $GLOBALS['dbh']->autoExecute('t_order', array(
  1766.                         'paid_status' => ORDER_STATUS_CASH,
  1767.                         'date_confirmed' => NOW,
  1768.                     ), DB_AUTOQUERY_UPDATE, ' id = ' . $orderInfo['id']);
  1769.                 }
  1770.                
  1771.             }
  1772.  
  1773.             $ticketTypes = $eventInfo = $notifyAdmins = $newItems = $instructionFiles = array();
  1774.            
  1775.             if ($orderInfo['event_id'])
  1776.                 $eventInfo = ginst('Event')->getById($orderInfo['event_id']);
  1777.            
  1778.            
  1779.             $orderInfo = $this->get($orderInfo['id'], 'id', false);
  1780.  
  1781.             $reservationId = 0;
  1782.            
  1783.             // 0. Going throught all items and checking for packages
  1784.             foreach ($orderInfo['items'] as $i => $row) {
  1785.                 if ($row['group_id'] != 1 && $row['is_detached'] == 0) {
  1786.                     if ($row['group_id'] == 2 && $row['cer_id'] > 0) {
  1787.  
  1788.                         $result = ginst('TicketCertificate')->getCerCodes($row['cer_id'], $row['type_id']);
  1789.  
  1790.                         $orderInfo['items'][$i]['bar_code'] = $result['code'];
  1791.                         $orderInfo['items'][$i]['bar_code_type'] = $result['code_type'];
  1792.  
  1793.                         $GLOBALS['dbh']->autoExecute('t_ticket', array(
  1794.                             'cert_id' => $result['id'],
  1795.                                 ), DB_AUTOQUERY_UPDATE, ' id = ' . $orderInfo['items'][$i]['id']);
  1796.  
  1797.                         $orderInfo['items'][$i]['cert_id'] = $result['id'];
  1798.                     }
  1799.  
  1800.                     // setting advanced ticket as detached to prevent second detaching
  1801.                     $GLOBALS['dbh']->autoExecute('t_ticket', array(
  1802.                         'is_detached' => 1,
  1803.                             ), DB_AUTOQUERY_UPDATE, ' id = ' . $row['id']);
  1804.                 }
  1805.             }
  1806.  
  1807.             foreach ($orderInfo['items'] as $i => $row) {
  1808.                 // prevent applay ticket if it saled or reserved
  1809.                 if (!empty($row['type_place_id'])) {
  1810.                     $aPlace = ginst('TicketTypePlace')->getPlace($row['type_place_id']);
  1811.                     if (!empty($aPlace) && $aPlace['is_sold'] == 1 && !in_array($orderInfo['partner_id'], array(16, 17))) {
  1812.                         $GLOBALS['dbh']->autoExecute('t_ticket', array(
  1813.                             'is_canceled' => 1,
  1814.                                 ), DB_AUTOQUERY_UPDATE, ' id = ' . $row['id']);
  1815.                         continue;
  1816.                     }
  1817.                 }
  1818.  
  1819.                 $orderInfo['items'][$i]['ticket_type'] = ginst('TicketType')->getById($row['type_id']);
  1820.                
  1821.                 // Some tickets we dont need to print - so checking
  1822.                 if ($orderInfo['items'][$i]['ticket_type']['is_print']) {
  1823.                     $orderInfo['items'][$i]['date_printed'] = NOW;
  1824.  
  1825.                     // 1. Generating barcode
  1826.                     if (!$orderInfo['items'][$i]['bar_code'] && $orderInfo['partner_id'] == 0) {
  1827.                         $barCode = ginst('Ticket')->getBarCode(array(
  1828.                             'type' => 'ticket',
  1829.                             'ticket_id' => $row['id'],
  1830.                             'ticket_type_id' => $row['type_id'],
  1831.                             'place_id' => $row['type_place_id'],
  1832.                             'code_type' => $orderInfo['items'][$i]['ticket_type']['code_type'],
  1833. //                          'is_test' => $orderInfo['is_test'] || $orderInfo['items'][$i]['is_test'] || $orderInfo['payment_type'] == 'free' ? 1 : 0,
  1834.                                 ));
  1835.                         $orderInfo['items'][$i]['bar_code'] = $barCode['code'];
  1836.                         $orderInfo['items'][$i]['bar_code_type'] = $barCode['type'];
  1837.                     } else {
  1838.                         if(empty($orderInfo['items'][$i]['cert_id'])){
  1839.                             $orderInfo['items'][$i]['bar_code_type'] = $orderInfo['items'][$i]['ticket_type']['code_type'];
  1840.                         }
  1841.                     }
  1842.  
  1843.                     $bcImg = ginst('Barcode')->getImage(array(
  1844.                         'code' => $orderInfo['items'][$i]['bar_code'],
  1845.                         'code_type' => $orderInfo['items'][$i]['bar_code_type'],
  1846.                         'type' => 'ticket',
  1847.                         'is_force' => true,
  1848.                             ));
  1849.  
  1850.                     $orderInfo['items'][$i]['bar_code_image'] = $bcImg['filename'];
  1851.                     $orderInfo['items'][$i]['bar_code_image_vertical'] = $bcImg['filename_vert'];
  1852.                     $orderInfo['items'][$i]['bar_code_image_vertical1'] = $bcImg['filename_vert1'];
  1853.                     $orderInfo['items'][$i]['bar_code_image_large'] = $bcImg['filename_large'];
  1854.                     $orderInfo['items'][$i]['bar_code_image_custom'] = $bcImg['filename_custom'];
  1855.                     $orderInfo['items'][$i]['bar_code_image_custom1'] = $bcImg['filename_custom1'];
  1856.  
  1857.                     if ($params['generate_pdf']) {
  1858.                         // 2. Generating PDF
  1859.                         $orderInfo['items'][$i]['pdf'] = ginst('Ticket')->generatePDF(array(
  1860.                             'event' => $eventInfo,
  1861.                             'order' => $orderInfo,
  1862.                             'ticket' => $orderInfo['items'][$i],
  1863.                             'is_filename' => 1,
  1864.                             'force' => $params['is_force'] ? 1 : 0,
  1865.                         ), 'pdf');
  1866.                     }
  1867.  
  1868.                     if ($params['email_notify'] && $params['generate_pdf'] && $orderInfo['delivery_type'] == 1) {
  1869.                         // 2.1. Attaching file to email
  1870.                         $GLOBALS['oEmail']->attach($orderInfo['items'][$i]['pdf'], '', true);
  1871.                     }
  1872.  
  1873.                     // 3. Updating ticket as paid
  1874.                     $GLOBALS['dbh']->autoExecute('t_ticket', array(
  1875.                         'bar_code' => $orderInfo['items'][$i]['bar_code'],
  1876.                         'bar_code_type' => $orderInfo['items'][$i]['bar_code_type'],
  1877.                         'date_printed' => $orderInfo['items'][$i]['date_printed'],
  1878.                         'is_printed' => 1,
  1879.                             ), DB_AUTOQUERY_UPDATE, ' id = ' . $orderInfo['items'][$i]['id']);
  1880.  
  1881.  
  1882.                     /* Add ticket barcode as discount code to the discount */
  1883.                     if (!empty($orderInfo['items'][$i]['ticket_type']['discount_id'])) {
  1884.                         $discountCodeId = $GLOBALS['dbh']->getOne("SELECT id FROM t_discount_code WHERE discount_id = '{$orderInfo['items'][$i]['ticket_type']['discount_id']}' AND code = '{$orderInfo['items'][$i]['bar_code']}' ");
  1885.                         if (empty($discountCodeId)) {
  1886.                             $GLOBALS['dbh']->autoExecute('t_discount_code', array(
  1887.                                 'discount_id' => $orderInfo['items'][$i]['ticket_type']['discount_id'],
  1888.                                 'code' => $orderInfo['items'][$i]['bar_code'],
  1889.                                 'date_created' => NOW,
  1890.                             ));
  1891.                         }
  1892.                     }
  1893.                 }
  1894.  
  1895.                 // 4. Saving amount of each ticket type if it's not test ticket
  1896.                 if (!$orderInfo['items'][$i]['is_test']) {
  1897.                     if (!$ticketTypes[$orderInfo['items'][$i]['type_id']])
  1898.                         $ticketTypes[$orderInfo['items'][$i]['type_id']] = 0;
  1899.                     $ticketTypes[$orderInfo['items'][$i]['type_id']] += 1;
  1900.                 }
  1901.  
  1902.                 // 5. Saving notify emails
  1903.                 if ($row['is_notify'] && $row['notify_email']) {
  1904.                     $notifyAdmins[$row['notify_email']] = 1;
  1905.                 }
  1906.  
  1907.                 // 6. If used discount - then marking it as used
  1908.                 if ($orderInfo['items'][$i]['used_discount_code_id']) {
  1909.                     $discount = $GLOBALS['dbh']->getRow("
  1910.                         SELECT dc.id, de.multi, de.ticket_amount
  1911.                         FROM t_discount_code AS dc
  1912.                         LEFT JOIN t_discount_event AS de ON de.discount_id = dc.discount_id AND de.event_id = '{$orderInfo['event_id']}'
  1913.                         WHERE dc.id = '{$orderInfo['items'][$i]['used_discount_code_id']}' ");
  1914.                     if ($discount['multi'] == 1 && $discount['ticket_amount'] == 0) {
  1915.                         $GLOBALS['dbh']->query("UPDATE t_discount_code SET time_used = time_used + 1 WHERE id = '{$orderInfo['items'][$i]['used_discount_code_id']}'");
  1916.                     } else {
  1917.                         $GLOBALS['dbh']->query("UPDATE t_discount_code SET time_used = time_used + 1, is_used = '1', date_used = NOW() WHERE id = '{$orderInfo['items'][$i]['used_discount_code_id']}'");
  1918.                     }
  1919.                 }
  1920.  
  1921.                 // 7. Some events used as discounts for others
  1922.                 ginst('Discount')->tryAddCode($orderInfo['event_id'], $orderInfo['items'][$i]['bar_code']);
  1923.  
  1924.                 // 8. Ticket with place
  1925.                 if ($orderInfo['items'][$i]['type_place_id'] && !$orderInfo['items'][$i]['parent_ticket_id']) {
  1926.                     // We have to mark the place as sold
  1927.                     if ($orderInfo['delivery_type'] != 3) {
  1928.                         $GLOBALS['dbh']->autoExecute('t_ticket_type_place', array(
  1929.                             'is_sold' => 1,
  1930.                             'date_sold' => NOW,
  1931.                             'sold_ticket_id' => $orderInfo['items'][$i]['id'],
  1932.                                 ), DB_AUTOQUERY_UPDATE, ' id = ' . $orderInfo['items'][$i]['type_place_id']);
  1933.                     }
  1934.                 }
  1935.  
  1936.                 // 9. Instruction can present for ticket type
  1937.                 if ($orderInfo['items'][$i]['instruction_file'] && !isset($instructionFiles[$orderInfo['items'][$i]['instruction_file']]) && $params['email_notify']) {
  1938.                     // Preventing for duplicates
  1939.                     $instructionFiles[$orderInfo['items'][$i]['instruction_file']] = 1;
  1940.  
  1941.                     $instructionFile = DOC_ROOT . web_file(array(
  1942.                                 'id' => $orderInfo['items'][$i]['type_id'],
  1943.                                 'row' => ginst('TicketType')->fields['instruction_file'],
  1944.                                 'name' => $orderInfo['items'][$i]['instruction_file'],
  1945.                             ));
  1946.  
  1947.                     // Attaching instruction to mail
  1948.                     $GLOBALS['oEmail']->attach($instructionFile, $orderInfo['items'][$i]['instruction_file'], true);
  1949.                 }
  1950.  
  1951.                 // 10. Saving reservation_id if it's present
  1952.                 if ($row['reservation_id']) {
  1953.                     $reservationId = $row['reservation_id'];
  1954.                     if (!$reservationIds[$row['reservation_id']])
  1955.                         $reservationIds[$row['reservation_id']] = 1;
  1956.                     else
  1957.                         $reservationIds[$row['reservation_id']]++;
  1958.                 }
  1959.             }
  1960.  
  1961.             if ($reservationId) {
  1962.                 // 4. Marking as used reservation - if it's present in order
  1963.                 $GLOBALS['dbh']->autoExecute('t_reservation', array(
  1964.                     'is_used' => 1,
  1965.                     'date_used' => NOW,
  1966.                     'order_id' => $orderInfo['id'],
  1967.                     'amount_used' => $reservationIds[$reservationId],
  1968.                         ), DB_AUTOQUERY_UPDATE, ' id = ' . $reservationId);
  1969.             }
  1970.            
  1971.             $orderInfo = $this->get($orderInfo['id'], 'id', false);
  1972.             if(empty($orderInfo['discount'])) {
  1973.                 $discountInfo = $GLOBALS['dbh']->getRow("SELECT
  1974.                                                             `de`.*
  1975.                                                         FROM
  1976.                                                             `t_discount_code` AS `dc`
  1977.                                                             LEFT JOIN `t_discount_event` AS `de` ON `de`.`discount_id` = `dc`.`discount_id`
  1978.                                                         WHERE
  1979.                                                             `de`.`event_id` = '{$orderInfo['event_id']}'
  1980.                                                             AND `dc`.`code` = '{$orderInfo['items'][$i]['discount_code']}';");
  1981.                 $discount = 0;
  1982.                 $usedDiscount = 0;
  1983.                 if ($discountInfo['ticket_amount'] == 12) {
  1984.                     foreach($orderInfo['items'] as $row_temp) {
  1985.  
  1986.                         if ($usedDiscount >= $row_temp['discount_amount']) {
  1987.                             continue;
  1988.                         }
  1989.  
  1990.                         $subtract = $row_temp['discount_amount'] - $usedDiscount;
  1991.                         if ($subtract >= $row_temp['price_billing']) {
  1992.                             $discount += $row_temp['price_billing'];
  1993.                             $usedDiscount += $row_temp['price_billing'];
  1994.                         }
  1995.                         else if ($subtract < $row_temp['price_billing']) {
  1996.                             $discount += $subtract;
  1997.                             $usedDiscount += $subtract;
  1998.                         }
  1999.                     }
  2000.                     $orderInfo['discount'] = ginst('Currency')->convert($discount, $orderInfo['price_currency'],'UAH');
  2001.                 }
  2002.             }
  2003.            
  2004.             if (!($orderInfo['payment_type'] == 'offline' && $orderInfo['payment_subtype'] == 'pdf') && $params['email_notify'] ) {
  2005.                 // 6. Send email to customer
  2006.                 if ($orderInfo['delivery_type'] == 1) {
  2007.                     if (isset($orderInfo['promo_id']) && !empty($orderInfo['promo_id'])){
  2008.                         $orderInfo['promo_notify_email'] = $GLOBALS['dbh']->getOne("
  2009.                             SELECT notify_email
  2010.                             FROM t_user
  2011.                             WHERE t_user.id = ".$orderInfo['promo_id']
  2012.                         );
  2013.                         $orderInfo['promo_name'] = $GLOBALS['dbh']->getOne("
  2014.                             SELECT name
  2015.                             FROM t_user
  2016.                             WHERE t_user.id = ".$orderInfo['promo_id']
  2017.                         );
  2018.                         if(!empty($orderInfo['promo_name'])){
  2019.                             $orderInfo['promo_name'] = toAscii($orderInfo['promo_name']);
  2020.                             $orderInfo['promo_name'] = preg_replace('/\W+/','_',$orderInfo['promo_name']);
  2021.                         }
  2022.                     }
  2023.                    
  2024.                     ginst('Notices')->order_complete($orderInfo, $eventInfo, $discount_code);
  2025.                 } elseif ($orderInfo['delivery_type'] == 2) {
  2026.                     if ($orderInfo['city_id'] == 10184 || true) {
  2027.                         ginst('Courier')->sendReport($orderInfo, $eventInfo);
  2028.                     } else {
  2029.                         $newpostOrderData = simplexml_load_string(ginst('Delivery')->createInvoice($orderInfo));
  2030.                         $GLOBALS['dbh']->autoExecute('t_delivery', array('newpost_order_id' => (string)$newpostOrderData->order->attributes()->np_id), DB_AUTOQUERY_UPDATE, ' order_id = ' . $orderInfo['id']);
  2031.                     }
  2032.                     ginst('Notices')->delivery_report_user($orderInfo, $eventInfo);
  2033.                 } elseif($orderInfo['delivery_type'] == 3) {
  2034.                     ginst('Notices')->reservationComplete($orderInfo['id']);
  2035.                 }
  2036.  
  2037.             }
  2038.            
  2039.             $discount = 0;
  2040.             // Визначення знижки і кількості товарів
  2041.             if(empty($orderInfo['discount'])) {
  2042.                 if ($discountInfo['ticket_amount'] != 12) {
  2043.                     foreach($orderInfo['items'] as $row_temp) {
  2044.                         if ($row['is_percents'] == 0) {
  2045.                             $discount += $row_temp['discount_amount'];
  2046.                         } elseif ($discountInfo['is_percents'] == 1) {
  2047.                             $discount += $row_temp['price_billing'] / 100 * $discountInfo['discount_amount'];
  2048.                         }
  2049.                         if (!($row['group_id'] == 2 && $row_temp['cert_id'] == 0)) {
  2050.                             $orderInfo['items_count_user']++;
  2051.                         }
  2052.                     }
  2053.                     $orderInfo['discount'] = ginst('Currency')->convert($discount, $orderInfo['price_currency'],'UAH');
  2054.                 }
  2055.             }
  2056.  
  2057.             // 7. Notify administrators of ticket types
  2058.             if ($notifyAdmins && $params['email_notify'] && !$orderInfo['items'][0]['is_hidden'] && $orderInfo['payment_subtype'] <> 'test') {
  2059.                 if (isset($orderInfo['promo_id']) && !empty($orderInfo['promo_id'])){
  2060.                     $orderInfo['promo_site'] = ginst('User')->promoSite($orderInfo['promo_id']);
  2061.                 } else {
  2062.                     $orderInfo['promo_site'] = "v-ticket.com.ua";
  2063.                 }
  2064.                 $offline_user = array();
  2065.                 if (!empty($orderInfo['items'][0]['user_id'])) {
  2066.                     $offline_user = ginst('User')->info(array('id' => $orderInfo['items'][0]['user_id']));
  2067.                 }
  2068.                
  2069.                 $sNotifyAdmins = implode(',', array_keys($notifyAdmins));
  2070.                
  2071.                 ginst('Notices')->order_notify($eventInfo, $orderInfo, $sNotifyAdmins);
  2072.                
  2073.             }
  2074.  
  2075.             // 8. SMS notify
  2076.             if ($params['sms_notify'] == true && $orderInfo['delivery_type'] == 1) {
  2077.                
  2078.                 $textSms = $GLOBALS['dbh']->getOne("                   
  2079.                     SELECT IFNULL(`nc1`.`sms`,`nc2`.`sms`) AS `sms`
  2080.                     FROM `t_notices` AS `n`
  2081.                     LEFT JOIN `t_notices_content` AS `nc1` ON `nc1`.`id` = `n`.`id` AND `nc1`.`language_id` = " . $GLOBALS['lng']['id'] . "
  2082.                     LEFT JOIN `t_notices_content` AS `nc2` ON `nc2`.`id` = `n`.`id` AND `nc2`.`language_id` = 1
  2083.                     WHERE `n`.`alias` = 'order_complete'
  2084.                 ");
  2085.  
  2086.                 $textSms = preg_replace('/%EMAIL%/', $orderInfo['email'], $textSms);
  2087.                 $textSms = preg_replace('/%SENDTICKETS%/', (count($orderInfo['items']) > 1 ? ' otpravleny tvoi bilety' : ' otpravlen tvoj bilet'), $textSms);
  2088.                 $textSms = preg_replace('/%THISTICKET%/', (count($orderInfo['items']) > 1 ? 'eti zhe bilety' : 'etot zhe bilet'), $textSms);
  2089.                 $textSms = preg_replace('/%LINKTICKET%/', ginst('Order')->getQuickUrl($orderInfo), $textSms);
  2090.                        
  2091.                 $res = ginst('Sms')->send(
  2092.                     $orderInfo['mobile'], $textSms, array(
  2093.                         'item_type' => 'order',
  2094.                         'item_id' => $orderInfo['id']
  2095.                     )
  2096.                 );
  2097.             } elseif ($orderInfo['delivery_type'] == 2) {
  2098.                 if ($orderInfo['paid_status'] == ORDER_STATUS_COURIER) {
  2099.                     $textSms = $GLOBALS['dbh']->getOne("       
  2100.                         SELECT IFNULL(`nc1`.`sms`,`nc2`.`sms`) AS `sms`
  2101.                         FROM `t_notices` AS `n`
  2102.                         LEFT JOIN `t_notices_content` AS `nc1` ON `nc1`.`id` = `n`.`id` AND `nc1`.`language_id` = " . $GLOBALS['lng']['id'] . "
  2103.                         LEFT JOIN `t_notices_content` AS `nc2` ON `nc2`.`id` = `n`.`id` AND `nc2`.`language_id` = 1
  2104.                         WHERE `n`.`alias` = 'delivery_report_user'
  2105.                     ");
  2106.  
  2107.                     $textSms = preg_replace('/%ORDER_ID%/', $orderInfo['id'], $textSms);
  2108.                     $textSms = preg_replace('/%PERIOD%/', $orderInfo['addr']['period'], $textSms);
  2109.                     $textSms = preg_replace('/%PRICE_TOTAL%/', $orderInfo['price_total'], $textSms);
  2110.  
  2111.                     $res = ginst('Sms')->send(
  2112.                         $orderInfo['mobile'], $textSms, array(
  2113.                             'item_type' => 'order',
  2114.                             'item_id' => $orderInfo['id']
  2115.                         )
  2116.                     );
  2117.                 } else {
  2118.                     $textSms = $GLOBALS['dbh']->getOne("
  2119.                         SELECT IFNULL(`nc1`.`sms`,`nc2`.`sms`) AS `sms`
  2120.                         FROM `t_notices` AS `n`
  2121.                         LEFT JOIN `t_notices_content` AS `nc1` ON `nc1`.`id` = `n`.`id` AND `nc1`.`language_id` = " . $GLOBALS['lng']['id'] . "
  2122.                         LEFT JOIN `t_notices_content` AS `nc2` ON `nc2`.`id` = `n`.`id` AND `nc2`.`language_id` = 1
  2123.                         WHERE `n`.`alias` = 'delivery_report_user_prepay'
  2124.                     ");
  2125.  
  2126.                     $textSms = preg_replace('/%ORDER_ID%/', $orderInfo['id'], $textSms);
  2127.                     $textSms = preg_replace('/%PERIOD%/', $orderInfo['addr']['period'], $textSms);
  2128.                     $textSms = preg_replace('/%PRICE_TOTAL%/', $orderInfo['price_total'], $textSms);
  2129.  
  2130.                     $res = ginst('Sms')->send(
  2131.                         $orderInfo['mobile'], $textSms, array(
  2132.                             'item_type' => 'order',
  2133.                             'item_id' => $orderInfo['id']
  2134.                         )
  2135.                     );
  2136.                 }
  2137.             } elseif($orderInfo['delivery_type'] == 3) {
  2138.                 ginst('Offline')->sendSMS($orderInfo['id']);
  2139.             }
  2140.  
  2141.             // 9. Updating counters of selled tickets
  2142.             ginst('TicketType')->updateCounters($eventInfo['id']);
  2143.            
  2144.             // 10. Notification administrators about end of quote
  2145.             $ticketTypesInfo = ginst('TicketType')->culcTicketsRemainder($eventInfo['id']);
  2146.  
  2147.             if ($ticketTypesInfo) {
  2148.                 //ginst('Notices')->quoteExpires($eventInfo['id'], $ticketTypesInfo);
  2149.             }
  2150.            
  2151.             // Спеціальний код відправки даних для ТиНаказанТіпа
  2152.             if ($orderInfo['event_id'] == 5313) {
  2153.                 $kazantipInfo = $GLOBALS['dbh']->getRow("
  2154.                     SELECT *
  2155.                     FROM t_kazantip
  2156.                     WHERE order_id = ?
  2157.                 ", 0, array($orderInfo['id']));
  2158.  
  2159.                 $res = ginst('RemoteConnection')->getData(array(
  2160.                     'url' => 'https://z-viza.kazantip.info/cgi-bin/remote.fcgi',
  2161.                     'post' => 1,
  2162.                     'header' => 1,
  2163.                     'ssl' => 0,
  2164.                     'params' => array (
  2165.                         'login' => 'concertua',
  2166.                         'passwd' => 'nHmnd2187fjKms',
  2167.                         'action' => 'add_online_paid_viza',
  2168.                         'number' => $orderInfo['items'][0]['bar_code'],
  2169.                         'client_category_id' => 13,
  2170.                         'country' => $kazantipInfo['country'],
  2171.                         'city' => $kazantipInfo['city'],
  2172.                         'email' => $kazantipInfo['email'],
  2173.                         'phone' => $kazantipInfo['mobile'],
  2174.                         'last_name' => $kazantipInfo['lastname'],
  2175.                         'first_name' => $kazantipInfo['firstname'],
  2176.                         'patronymic'  => $kazantipInfo['patronymic'],
  2177.                         'passport' => $kazantipInfo['passport'],
  2178.                         'gender' => $kazantipInfo['sex'] ? 'male' : 'female',
  2179.                         'price' => $orderInfo['price_total'],
  2180.                         'foto' => "@" . DOC_ROOT . "dynamic/user/extended/{$orderInfo['id']}.{$kazantipInfo['photo_ext']}"
  2181.                     )
  2182.                 ));
  2183.                        
  2184.                 $kazantipRes = explode("|", $res);
  2185.  
  2186.                 $kazantipSuccess = explode("=", $kazantipRes[0]);
  2187.  
  2188.                 $kazantipDesc = 'Success';
  2189.                 if (!$kazantipSuccess[1]) {
  2190.                     $kazantipError = explode("=", $kazantipRes[1]);
  2191.                     $kazantipDesc = $kazantipError[1];
  2192.                 }
  2193.                
  2194.                 $GLOBALS['dbh']->autoExecute('t_kazantip', array(
  2195.                     'success' => $kazantipSuccess[1],
  2196.                     'description' => $kazantipDesc,
  2197.                 ), DB_AUTOQUERY_UPDATE, ' order_id = ' . $orderInfo['id']);
  2198.                        
  2199.                 mkdir(DOC_ROOT."log", '0775', true);
  2200.                 $fres = fopen(DOC_ROOT."log/kazantip_".date("Y-F").".log", "a");
  2201.                 fwrite($fres, date('Y-m-d H:i:s')."\n");
  2202.                 fwrite($fres, $res ."\n\n");
  2203.                 fclose($fres);
  2204.             }
  2205.                        
  2206.             // 11. Appling the booking
  2207.             ginst('Api')->internalApplyBooking($orderInfo['id']);
  2208.         }
  2209.  
  2210.         public function resend($orderInfo, $params = array()) {
  2211.  
  2212.             $eventInfo = ginst('Event')->getById($orderInfo['event_id']);
  2213.  
  2214.             $instructionFiles = array();
  2215.  
  2216.             if (!$orderInfo['is_deposit']) {
  2217.                 foreach ($orderInfo['items'] as $i => $row) {
  2218.  
  2219.                     $bcImg = ginst('Barcode')->getImage(array(
  2220.                         'code' => $orderInfo['items'][$i]['bar_code'],
  2221.                         'code_type' => $orderInfo['items'][$i]['bar_code_type'],
  2222.                         'type' => 'ticket',
  2223.                             ));
  2224.  
  2225.                     $orderInfo['items'][$i]['bar_code_image'] = $bcImg['filename'];
  2226.                     $orderInfo['items'][$i]['bar_code_image_vertical'] = $bcImg['filename_vert'];
  2227.                     $orderInfo['items'][$i]['bar_code_image_vertical1'] = $bcImg['filename_vert1'];
  2228.                     $orderInfo['items'][$i]['bar_code_image_large'] = $bcImg['filename_large'];
  2229.                     $orderInfo['items'][$i]['bar_code_image_custom'] = $bcImg['filename_custom'];
  2230.                     $orderInfo['items'][$i]['bar_code_image_custom1'] = $bcImg['filename_custom1'];
  2231.  
  2232.                     $orderInfo['items'][$i]['ticket_type'] = ginst('TicketType')->getById($row['type_id']);
  2233.  
  2234.                     $orderInfo['items'][$i]['pdf'] = ginst('Ticket')->generatePDF(array(
  2235.                         'event' => $eventInfo,
  2236.                         'order' => $orderInfo,
  2237.                         'ticket' => $orderInfo['items'][$i],
  2238.                         'force' => true,
  2239.                         'is_filename' => 1,
  2240.                             ), 'pdf');
  2241.  
  2242.  
  2243.                     if ($orderInfo['items'][$i]['instruction_file'] && !isset($instructionFiles[$orderInfo['items'][$i]['instruction_file']])) {
  2244.                         // Preventing for duplicates
  2245.                         $instructionFiles[$orderInfo['items'][$i]['instruction_file']] = 1;
  2246.  
  2247.                         $instructionFile = DOC_ROOT . web_file(array(
  2248.                                     'id' => $orderInfo['items'][$i]['type_id'],
  2249.                                     'row' => ginst('TicketType')->fields['instruction_file'],
  2250.                                     'name' => $orderInfo['items'][$i]['instruction_file'],
  2251.                                 ));
  2252.  
  2253.                         // Attaching instruction to mail
  2254.                         $GLOBALS['oEmail']->attach($instructionFile, $orderInfo['items'][$i]['instruction_file'], true);
  2255.                     }
  2256.                     if($orderInfo['delivery_type'] != 2){
  2257.                         $GLOBALS['oEmail']->attach($orderInfo['items'][$i]['pdf'], '', true);
  2258.                     }
  2259.                 }
  2260.             }
  2261.  
  2262.             // 5. Send email to customer
  2263.             /**
  2264.              * TODO: for New Post!
  2265.              */
  2266.             if ($orderInfo['delivery_type'] == 2) {
  2267.                 ginst('Courier')->sendReport($orderInfo);
  2268.             } else {
  2269.                 // Attaching ticket
  2270.                 ginst('Notices')->order_complete($orderInfo, $eventInfo, $discount_code);              
  2271.             }
  2272.            
  2273.             $this->addLog(array(
  2274.                 'order_id' => $orderInfo['id'],
  2275.                 'action' => 'resend-email',
  2276.                 'info' => array(
  2277.                     'email' => $orderInfo['email'],
  2278.                     'subject' => $GLOBALS['oEmail']->sSubject,
  2279.                     'text' => $GLOBALS['oEmail']->text,
  2280.                     'text_html' => $GLOBALS['oEmail']->text_html,
  2281.                 ),
  2282.             ));
  2283.  
  2284.             // 8. SMS notify
  2285.             if ($params['sms_notify'] == true) {
  2286.                 // Generating shor url for order
  2287.  
  2288.                 $shortUrl = ginst('Order')->shortUrl();
  2289.  
  2290.                 $sms = $GLOBALS['dbh']->getOne("
  2291.                     SELECT `nc`.`sms`
  2292.                     FROM `t_notices` AS `n`
  2293.                     LEFT JOIN `t_notices_content` AS `nc` ON `nc`.`id` = `n`.`id` AND `nc`.`language_id` = 1
  2294.                     WHERE `n`.`alias` = 'order_resend'
  2295.                 ");
  2296.  
  2297.                 $sms = preg_replace('/%EMAIL%/', $orderInfo['email'], $sms);
  2298.                 $sms = preg_replace('/%SENDTICKETS%/', (count($orderInfo['items']) > 1 ? 'otpravleny tvoi bilety' : 'otpravlen tvoj bilet'), $sms);
  2299.  
  2300.                 $res = ginst('Sms')->send(
  2301.                         $orderInfo['mobile'], $sms, array(
  2302.                     'item_type' => 'order',
  2303.                     'item_id' => $orderInfo['id']
  2304.                         )
  2305.                 );
  2306.  
  2307.                 $this->addLog(array(
  2308.                     'order_id' => $orderInfo['id'],
  2309.                     'action' => 'resend-sms',
  2310.                     'info' => array(
  2311.                         'mobile' => $orderInfo['mobile'],
  2312.                         'text' => $sms,
  2313.                     ),
  2314.                 ));
  2315.             }
  2316.         }
  2317.  
  2318.         public function failed($order_id, $response_message) {
  2319.             $orderInfo = $this->get($order_id);
  2320.  
  2321.             if (
  2322.                     $orderInfo['paid_status'] == ORDER_STATUS_COMPLETE ||
  2323.                     $orderInfo['paid_status'] == ORDER_STATUS_FAILED
  2324.             )
  2325.                 return;
  2326.             switch ($orderInfo['partner_id']) {
  2327.                 case 1:
  2328.                     ginst('Karabas')->cancelOrder($orderInfo['external_id'], 'failed order');
  2329.                     break;
  2330.                 case 10:
  2331.                     ginst('Premiera')->cancelOrder($orderInfo['id']);
  2332.                     break;
  2333.                 case ginst('FlashBox')->getServerId():
  2334.                     $this->_flashBoxCancelOrder($orderInfo['id']);
  2335.                     break;
  2336.                 case ginst('Kassir24')->getServerId():
  2337.                     ginst('Kassir24')->cancelOrder($orderInfo['id']);
  2338.                     break;
  2339.             }
  2340.            
  2341.             // 1. Updating status of order
  2342.             $GLOBALS['dbh']->autoExecute($this->table_name, array(
  2343.                 'paid_status' => ORDER_STATUS_FAILED,
  2344.                 'paid_description' => $response_message,
  2345.                 'date_confirmed' => NOW,
  2346.                     ), DB_AUTOQUERY_UPDATE, ' id = ' . $orderInfo['id']);
  2347.  
  2348.             $eventInfo = ginst('Event')->getById($orderInfo['event_id']);
  2349.  
  2350.             if ($orderInfo['payment_type'] == 'liqpay') {
  2351.                
  2352.                 ginst('Notices')->order_failed($orderInfo);
  2353.                 // 2. Sending notification about failing
  2354. //              $GLOBALS['oEmail']->send(array(
  2355. //                  'template' => 'order_failed',
  2356. //                  'to' => $orderInfo['email'],
  2357. //                  'data' => array(
  2358. //                      'eventInfo' => $eventInfo,
  2359. //                      'order' => $orderInfo,
  2360. //                  ),
  2361. //                  'item_type' => 'order-failed',
  2362. //                  'item_id' => $orderInfo['id'],
  2363. //              ));
  2364.             }
  2365.         }
  2366.  
  2367.         public function checkSelectedLocation($order_info) {
  2368.             $res = true;
  2369.            
  2370.             if ($order_info['country'] == 'none' || $order_info['country'] == 'null' || $order_info['country'] == 'no data') {
  2371.                 $res = false;
  2372.             }
  2373.             if ($order_info['region'] == 'none' || $order_info['region'] == 'null' || $order_info['region'] == 'no data') {
  2374.                 $res = false;
  2375.             }
  2376.             if ($order_info['city_id'] == 'none' || $order_info['city_id'] == 'null' || $order_info['city_id'] == 'no data') {
  2377.                 $res = false;
  2378.             }
  2379.            
  2380.             return $res;
  2381.         }
  2382.        
  2383.         public $userFields = array('firstname', 'lastname', 'city', 'email', 'number');
  2384.         public $addressFields = array('street', 'house', 'flat', 'zip');
  2385.  
  2386.         public function checkFields($eventInfo, $order_info, $errors = true) {
  2387.             $res = '';
  2388.  
  2389.             foreach ($this->userFields as $name) {
  2390.                 if (!trim($order_info[$name])) {
  2391.                     $res .= ($res ? '<br/>' : '') . '&bull; ' . $GLOBALS['smarty']->get_config_vars('form_' . $name) . ' ' . $GLOBALS['smarty']->get_config_vars('form_field_required');
  2392.                 }
  2393.             }
  2394.            
  2395.             if (!in_array($order_info['delivery'], array_keys($this->deliveryTypes))
  2396.                     || $order_info['delivery'] == 1 && $eventInfo['eticket_enabled'] == 0
  2397.                     || $order_info['delivery'] == 2 && $eventInfo['delivery_enabled'] == 0
  2398.                     || $order_info['delivery'] == 3 && $eventInfo['reservation_enabled'] == 0) {
  2399.                 $res .= ($res ? '<br/>' : '') . '&bull; ' . $GLOBALS['smarty']->get_config_vars('form_wrong_delivery');
  2400.             }
  2401.            
  2402.             if ($order_info['delivery'] == 2) {
  2403.                 /*if (($order_info['city_id'] == 10184 && in_array($order_info['delivery_subtype'], array(3,4)))
  2404.                     || $order_info['city_id'] != 10184 && $order_info['delivery_subtype'] == 3) {*/
  2405.                    
  2406.                     foreach ($this->addressFields as $address) {
  2407.                         if (!trim($order_info[$address])) {
  2408.                             $res .= ($res ? '<br/>' : '') . '&bull; ' . $GLOBALS['smarty']->get_config_vars('form_wrong_' . $address);
  2409.                         }
  2410.                     }
  2411.  
  2412.                     $deliveryData = ginst('Delivery')->getMostExpressRates($eventInfo['id'], $order_info['city_id']);
  2413.  
  2414.                     if (!$deliveryData['deliveryPeriod']) {
  2415.                         $res .= ($res ? '<br/>' : '') . '&bull; ' . $GLOBALS['smarty']->get_config_vars('form_wrong_date');
  2416.                     }
  2417.                 /*} else {
  2418.                     if (empty($order_info['ware_id']) || $order_info['ware_id'] <= 0) {
  2419.                         $res .= ($res ? '<br/>' : '') . '&bull; ' . $GLOBALS['smarty']->get_config_vars('form_wrong_waren');
  2420.                     }
  2421.                 }*/
  2422.             }
  2423.  
  2424.             // checking for correct mobile number
  2425.             if (!ginst('Sms')->checkNumber($order_info['number'])) {
  2426.                 $res .= ($res ? '<br/>' : '') . '&bull; ' . $GLOBALS['smarty']->get_config_vars('form_wrong_number');
  2427.             }
  2428.  
  2429.             // checking email
  2430.             if (trim($order_info['email']) && !check_email($order_info['email'])) {
  2431.                 $res .= ($res ? '<br/>' : '') . '&bull; ' . $GLOBALS['smarty']->get_config_vars('form_wrong_email');
  2432.             }
  2433.  
  2434.             if (in_array($order_info['delivery'], array_keys($this->deliveryTypes)) && $order_info['delivery'] != 3) {
  2435.                 if (!$this->paymentTypes[$order_info['payment']] && !$GLOBALS['bIsAdmin']) {
  2436.                     $res .= ($res ? '<br/>' : '') . '&bull; ' . $GLOBALS['smarty']->get_config_vars('form_wrong_payment');
  2437.                 } elseif ($this->paymentTypes[$order_info['payment']]['subtypes'] && !$GLOBALS['bIsAdmin']) {
  2438.                     if (!$this->paymentTypes[$order_info['payment']]['subtypes'][$order_info['subpayment'][$order_info['payment']]]) {
  2439.                         $res .= ($res ? '<br/>' : '') . '&bull; ' . $GLOBALS['smarty']->get_config_vars('form_wrong_subpayment');
  2440.                     }
  2441.                 }
  2442.             }
  2443.            
  2444.             /*$forbiddenMail = array('mail.ru', 'ukr.net', 'inbox.ru', 'bk.ru', 'list.ru');
  2445.             // don't check email when order is in status delivery by courier
  2446.             if($order_info['delivery'] != 2){
  2447.                 foreach ($forbiddenMail as $name) {
  2448.                     if (strpos(strtolower($order_info['email']), '@' . $name) !== false) {
  2449.                         $res .= ($res ? '<br/>' : '') . '&bull; ' . $GLOBALS['smarty']->get_config_vars('form_email_forbidden');
  2450.                         break;
  2451.                     }
  2452.                 }
  2453.             }
  2454.             */
  2455.  
  2456.             if ($GLOBALS['bIsAdmin'] && !$order_info['types']) {
  2457.                 $res .= ($res ? '<br/>' : '') . '&bull; ' . $GLOBALS['smarty']->get_config_vars('form_no_tickets_selected');
  2458.             }
  2459.  
  2460.             if (!empty($eventInfo['allFree']) && $eventInfo['allFree'] == 1) {
  2461.  
  2462.                 $row = $GLOBALS['dbh']->getRow('SELECT * FROM t_order WHERE event_id = ? AND mobile = ? AND paid_status = 2 LIMIT 1', array($eventInfo['id'], $order_info['number']));
  2463.                 if (!empty($row['id']) && !$GLOBALS['isLocal']) {
  2464.                     // already in use mobile
  2465.                     $res .= ($res ? '<br/>' : '') . '&bull; ' . $GLOBALS['smarty']->get_config_vars('order_mobile_number_already_in_use');
  2466.                 }
  2467.                 $row = $GLOBALS['dbh']->getRow('SELECT * FROM t_order WHERE event_id = ? AND email = ? AND paid_status = 2 LIMIT 1', array($eventInfo['id'], $order_info['email']));
  2468.                 if (!empty($row['id']) && !$GLOBALS['isLocal']) {
  2469.                     // already in use email
  2470.                     $res .= ($res ? '<br/>' : '') . '&bull; ' . $GLOBALS['smarty']->get_config_vars('order_email_already_in_use');
  2471.                 }
  2472.                 $row = $GLOBALS['dbh']->getRow('SELECT * FROM t_order WHERE event_id = ? AND ip_address = ? AND paid_status = 2 LIMIT 1', array($eventInfo['id'], get_real_ip()));
  2473.                 if (!empty($row['id']) /* && !$GLOBALS['isLocal'] */) {
  2474.                     // already in use email
  2475.                     $res .= ($res ? '<br/>' : '') . '&bull; ' . $GLOBALS['smarty']->get_config_vars('order_ip_already_in_use');
  2476.                 }
  2477.             }
  2478.            
  2479.             if ($eventInfo['extended_form']) {
  2480.                
  2481.                 if (!$order_info['is_concert']) {
  2482.                     if ($_FILES['photo_ext']['error'] === 0) {
  2483.                         preg_match('/\.(jpeg|png|jpg)$/i', $_FILES["photo_ext"]["name"], $match);
  2484.  
  2485.                         if (empty($match[1])) {
  2486.                             $res .= ($res ? '<br/>' : '') . '&bull; ' . $GLOBALS['smarty']->get_config_vars('form_wrong_photo_ext');
  2487.                         } else {
  2488.                             if ($_FILES['photo_ext']['size'] > 3 * 1024 * 1024) {
  2489.                                 $res .= ($res ? '<br/>' : '') . '&bull; ' . $GLOBALS['smarty']->get_config_vars('form_wrong_photo_ext');
  2490.                             } else {
  2491.                                 $imageInfo = getimagesize($_FILES['photo_ext']['tmp_name']);
  2492.  
  2493.                                 if ($imageInfo[0] < 1024 || $imageInfo[1] < 768) {
  2494.                                     $res .= ($res ? '<br/>' : '') . '&bull; ' . $GLOBALS['smarty']->get_config_vars('form_wrong_photo_dimantion');
  2495.                                 }
  2496.                             }
  2497.                         }
  2498.                     } else {
  2499.                         $res .= ($res ? '<br/>' : '') . '&bull; ' . $GLOBALS['smarty']->get_config_vars('form_wrong_photo');
  2500.                     }
  2501.                 }
  2502.                
  2503.                 if (!trim($order_info['passport'])) {
  2504.                     $res .= ($res ? '<br/>' : '') . '&bull; ' . $GLOBALS['smarty']->get_config_vars('form_wrong_passport');
  2505.                 }
  2506.                
  2507.                 if (!in_array($order_info['sex'], array(0, 1))) {
  2508.                     $res .= ($res ? '<br/>' : '') . '&bull; ' . $GLOBALS['smarty']->get_config_vars('form_wrong_sex');
  2509.                 }
  2510.  
  2511.             }
  2512.            
  2513.             if ($res && $errors) {
  2514.                 $GLOBALS['cStatus']->setError('<br/>' . $res);
  2515.             }
  2516.             return $res ? false : true;
  2517.         }
  2518.        
  2519.         public function checkCountTickets($eventInfo, $order_info, $errors = true) {
  2520.             $res = '';
  2521.             // checking for correct ticket types selected and amounts
  2522.             $totalTickets = 0;
  2523.            
  2524.             if ($eventInfo['partner_id'] == 1 || ($eventInfo['partner_id'] == 11 && $eventInfo['ib_scheme'] > 0)) {
  2525.                 $totalTickets = count($order_info['place']);
  2526.             } else {
  2527.                 if (!empty($order_info['amount'])) {
  2528.                     foreach ($order_info['amount'] as $id => $am) {
  2529.                         $totalTickets += (int) $am;
  2530.                         if ($am && !isset($eventInfo['ticketTypes'][$id])) {
  2531.                             $res .= ($res ? '<br/>' : '') . '&bull; ' . $GLOBALS['smarty']->get_config_vars('form_wrong_tickets_selected');
  2532.                             break;
  2533.                         } elseif ($am > 10 || !empty($eventInfo['allFree']) && $eventInfo['allFree'] == 1 && $am > 2) {
  2534.                             $res .= ($res ? '<br/>' : '') . '&bull; ' . $GLOBALS['smarty']->get_config_vars('form_wrong_tickets_amount') . ' ' . $eventInfo['ticketTypes'][$id]['title'];
  2535.                         } elseif (isset($eventInfo['ticketTypes'][$id]['cnt_max']) && $am > $eventInfo['ticketTypes'][$id]['cnt_max'] && $eventInfo['ticketTypes'][$id]['cnt_max'] > 0) {
  2536.                             $res .= ($res ? '<br/>' : '') . '&bull; ' . $GLOBALS['smarty']->get_config_vars('form_wrong_tickets_amount') . ' ' . $eventInfo['ticketTypes'][$id]['title'];
  2537.                         }
  2538.                     }
  2539.                 }
  2540.                 // checking for correct places selected
  2541.                 if ($eventInfo['is_scheme'] && $order_info['place']) {
  2542.  
  2543.                     $placesQuota = ginst('Place')->getQuota($eventInfo['id']);
  2544.                    
  2545.                     $reservedPlaces = '';
  2546.                     $soldedPlaces = '';
  2547.  
  2548.                     foreach ($order_info['place'] as $type_id => $places) {
  2549.                         foreach ($places as $place_id) {
  2550.                             if ($placesQuota[$place_id]['active_type'] == 0 || $placesQuota[$place_id]['is_soldout'] == 1) {
  2551.                                 $res .= ($res ? '<br/>' : '') . '&bull; ' . $GLOBALS['smarty']->get_config_vars('form_wrong_tickets_selected');
  2552.                                 break;
  2553.                             } elseif (!(isset($placesQuota[$place_id]) && !$placesQuota[$place_id]['is_sold'])) {
  2554.                                 $soldedPlaces .= ($soldedPlaces ? ', ' : '' ) . $placesQuota[$place_id]['title_full'];
  2555.                             } elseif ($placesQuota[$place_id]['is_reserved']) {
  2556.                                 $reservedPlaces .= ($reservedPlaces ? ', ' : '' ) . $placesQuota[$place_id]['title_full'];
  2557.                             }
  2558.                             $totalTickets += 1;
  2559.                         }
  2560.                     }
  2561.                     if ($soldedPlaces) {
  2562.                         $res .= ($res ? '<br/>' : '') . '&bull; ' . sprintf($GLOBALS['smarty']->get_config_vars('form_wrong_tickets_selected_with_place_sold'), $soldedPlaces);
  2563.                     }
  2564.                     if ($reservedPlaces) {
  2565.                         $res .= ($res ? '<br/>' : '') . '&bull; ' . sprintf($GLOBALS['smarty']->get_config_vars('form_wrong_tickets_selected_with_place'), $reservedPlaces);
  2566.                     }
  2567.                 }
  2568.             }
  2569.             if (!$totalTickets) {
  2570.                 $res .= ($res ? '<br/>' : '') . '&bull; ' . $GLOBALS['smarty']->get_config_vars('form_select_tickets_please');
  2571.             } elseif ($totalTickets > 10) {
  2572.                 $res .= ($res ? '<br/>' : '') . '&bull; ' . $GLOBALS['smarty']->get_config_vars('form_select_tickets_more_then10');
  2573.             }
  2574.             if ($res && $errors) {
  2575.                 $GLOBALS['cStatus']->setError($res);
  2576.             }
  2577.        
  2578.             return $res ? false : true;
  2579.         }
  2580.  
  2581.         public function getSecretCode() {
  2582.  
  2583.             $code = '';
  2584.  
  2585.             while (1) {
  2586.                 $code = rand(10000000, 99999999);
  2587.                 $code .= rand(10, 99);
  2588.                 $r = $GLOBALS['dbh']->getOne('SELECT id FROM t_order WHERE secret_code = ? LIMIT 1', array($code));
  2589.                 if (!$r)
  2590.                     break;
  2591.             }
  2592.  
  2593.             return $code;
  2594.         }
  2595.  
  2596.         public function checkSecretCode($code = false) {
  2597.             return preg_match('/^(\d{10})$/', $code);
  2598.         }
  2599.  
  2600.         public function getQuickUrl($orderInfo) {
  2601.             return "http://v-ticket.com.ua/q/" . $orderInfo['secret_code'] . "";
  2602.         }
  2603.  
  2604.         public function partiallyPay($order_id = false, $amount = 0, $currency = 'UAH') {
  2605.  
  2606.             if (!$order_id)
  2607.                 return false;
  2608.  
  2609.             $orderInfo = $this->get($order_id);
  2610.  
  2611.             // Saving payment
  2612.             $GLOBALS['dbh']->autoExecute('t_order_payment', array(
  2613.                 'order_id' => $order_id,
  2614.                 'date_paid' => NOW,
  2615.                 'payment_type' => $orderInfo['payment_type'],
  2616.                 'amount' => $amount,
  2617.                 'currency' => $currency,
  2618.             ));
  2619.  
  2620.             // Updating order as partial paid
  2621.             $GLOBALS['dbh']->autoExecute('t_order', array(
  2622.                 'paid_status' => ORDER_STATUS_PARTIALLY,
  2623.                 'paid_total' => $orderInfo['paid_total'] + $amount,
  2624.                     ), DB_AUTOQUERY_UPDATE, ' id = ' . $order_id);
  2625.  
  2626.             ginst('TicketType')->updateCounters($orderInfo['event_id']);
  2627.             // Notify user about partially paid order
  2628.             $smsText = $GLOBALS['dbh']->getOne("
  2629.                     SELECT `nc`.`sms`
  2630.                     FROM `t_notices` AS `n`
  2631.                     LEFT JOIN `t_notices_content` AS `nc` ON `nc`.`id` = `n`.`id` AND `nc`.`language_id` = 1
  2632.                     WHERE `n`.`alias` = 'partiallyPay'
  2633.             ");
  2634.             $smsText = preg_replace('/%AMOUNT%/', sprintf('%0.2f', $amount), $smsText);
  2635.             $smsText = preg_replace('/%CHANGE%/', sprintf('%0.2f', $orderInfo['billing_price'] - $orderInfo['paid_total'] - $amount), $smsText);
  2636.             $smsText = preg_replace('/%SECRET_CODE%/', $orderInfo['secret_code'], $smsText);
  2637.            
  2638.             ginst('Sms')->send(
  2639.                     $orderInfo['mobile'], $smsText, array(
  2640.                 'item_type' => 'order',
  2641.                 'item_id' => $orderInfo['id']
  2642.                     )
  2643.             );
  2644.         }
  2645.  
  2646.         public function cancel($orderInfo = false, $reason_text = '', $new_status = ORDER_STATUS_CANCELLED) {
  2647.            
  2648.             switch ($orderInfo['partner_id']) {
  2649.                 case 1:// remove ticket from basket if Karabas Event
  2650.                     ginst('Karabas')->cancelOrder($orderInfo['external_id'], $reason_text);
  2651.                     break;
  2652.                 case 10: // cancel Premiera order tickets
  2653.                     ginst('Premiera')->cancelOrder($orderInfo['id']);
  2654.                     break;
  2655.                 case 11:
  2656.                     ginst('InternetBilet')->bookingCancel($orderInfo['external_id']);
  2657.                     break;
  2658.                 case ginst('FlashBox')->getServerId():
  2659.                     $this->_flashBoxCancelOrder($orderInfo['id']);
  2660.                     break;
  2661.                 case ginst('Kassir24')->getServerId():
  2662.                     if (!ginst('Kassir24')->refundOrder($orderInfo['id'])) {
  2663.                         return false;
  2664.                     }
  2665.                     break;
  2666.             }
  2667.             //canceled New Post order
  2668.             if ($orderInfo['delivery_type'] == 2 && $orderInfo['city_id'] != 10184 && false) {
  2669.                 ginst('Delivery')->cancelInvoice($orderInfo['addr']['np_order_id']);
  2670.             }
  2671.  
  2672.             if ($new_status == ORDER_STATUS_CANCELLED && !in_array($orderInfo['paid_status'], array(ORDER_STATUS_COMPLETE, ORDER_STATUS_COURIER, ORDER_STATUS_OFFLINE, ORDER_STATUS_PREPAY, ORDER_STATUS_CASH)))
  2673.                 return false;
  2674.  
  2675.             // 1. Cancelling order
  2676.             $GLOBALS['dbh']->autoExecute('t_order', array(
  2677.                 'paid_status' => $new_status,
  2678.                 'date_cancelled' => NOW,
  2679.                 'cancelled_reason' => $reason_text,
  2680.                     ), DB_AUTOQUERY_UPDATE, 'id = ' . $orderInfo['id']);
  2681.  
  2682.  
  2683.             // 2. Cancelling tickets
  2684.             if (!$orderInfo['items']) {
  2685.                 $orderInfo = $this->get($orderInfo['id']);
  2686.             }
  2687.            
  2688.             if ($orderInfo['items']) {
  2689.                 $tid = $pid = array();
  2690.                 foreach ($orderInfo['items'] as $row) {
  2691.                     $tid[] = $row['id'];
  2692.                     if ($row['type_place_id']) {
  2693.                         $pid[] = $row['type_place_id'];
  2694.                     }
  2695.                 }
  2696.                
  2697.                 // Cancelling tickets
  2698.                 if ($tid) {
  2699.                     $GLOBALS['dbh']->autoExecute('t_ticket', array(
  2700.                         'is_canceled' => 1,
  2701.                             ), DB_AUTOQUERY_UPDATE, 'id IN (' . implode(',', $tid) . ')');
  2702.                    
  2703.                     $GLOBALS['dbh']->autoExecute('t_barcode_external', array(
  2704.                         'is_used' => 0,
  2705.                         'date_used' => null,
  2706.                         'ticket_id' => null
  2707.                     ), DB_AUTOQUERY_UPDATE, 'ticket_id IN (' . implode(',', $tid) . ')');
  2708.                 }
  2709.  
  2710.  
  2711.                 // Cancelling places
  2712.                 if ($pid) {
  2713.                     $GLOBALS['dbh']->autoExecute('t_ticket_type_place', array(
  2714.                         'is_sold' => 0,
  2715.                         'is_reserved' => 0,
  2716.                             ), DB_AUTOQUERY_UPDATE, 'id IN (' . implode(',', $pid) . ')');
  2717.                 }
  2718.             }
  2719.  
  2720.             // 3. Updating counters of sold tickets
  2721.             ginst('TicketType')->updateCounters($orderInfo['event_id']);
  2722.            
  2723.             // 4. Cancelation of booking
  2724.             ginst('Api')->internalCancelBooking($orderInfo['id'], $reason_text);
  2725.  
  2726.             // 5. Logging about cancelling
  2727.             ginst('Order')->addLog(array(
  2728.                 'order_id' => $orderInfo['id'],
  2729.                 'action' => 'cancelled',
  2730.                 'info' => array(
  2731.                     'reason' => $reason_text,
  2732.                     'old_status' => $orderInfo['paid_status'],
  2733.                     'new_status' => $new_status,
  2734.                 ),
  2735.             ));
  2736.  
  2737.             return true;
  2738.         }
  2739.        
  2740.         public static function getTopDJLogs($orderId = null)
  2741.         {
  2742.             $paymentInfo = array();
  2743.            
  2744.             topdjDB_connect();
  2745.                    
  2746.             $merchantOrder = $GLOBALS['dbh2']->getRow('SELECT * FROM t_merchant_order WHERE merchant_id = ? AND merchant_order_id = ?', array(
  2747.                 self::$_mIdTopDJ,
  2748.                 $orderId
  2749.                     ));
  2750.  
  2751.             if ($merchantOrder['id']) {
  2752.  
  2753.                 $aMerchantOrderStatuses = array(
  2754.                     0 => 'Отправлен на оплату',
  2755.                     1 => 'Оплачен',
  2756.                     2 => 'Не прошёл',
  2757.                 );
  2758.  
  2759.                 $paymentInfo[] = array(
  2760.                     'title' => 'Создан заказ мерчанта на TopDJ',
  2761.                     'date_log' => $merchantOrder['date_created'],
  2762.                     'amount' => $merchantOrder['amount'],
  2763.                     'currency' => $merchantOrder['currency'],
  2764.                     'info' => 'ID: ' . $merchantOrder['id'] . '<br/>Статус: ' . $aMerchantOrderStatuses[$merchantOrder['paid_status']]
  2765.                 );
  2766.  
  2767.                 $paidOrderInfo = $GLOBALS['dbh2']->getRow('SELECT * FROM t_paid_order WHERE item_id = ? AND service_type = ?', array(
  2768.                     $merchantOrder['id'],
  2769.                     'merchant-order'
  2770.                         ));
  2771.  
  2772. //              $paidOrderInfo['id'] = 22190;
  2773. //              $txt = file_get_contents("http://topdj.ua/log/card_trans_2011-April.log");
  2774. //              $txt = explode("\n\n", $txt);
  2775. //              exit;
  2776.  
  2777.                 if ($paidOrderInfo['id']) {
  2778.  
  2779.                     $text = '';
  2780.  
  2781.                     if ($paidOrderInfo['status'] <> 1) {
  2782.                         // Trying to extract information about this order
  2783. //                      $info = unserialize($paidOrderInfo['status_info']);
  2784.  
  2785.                         if ($paidOrderInfo['payment_type'] == 'liqpay') {
  2786.                             $text = '';
  2787.                         } elseif ($paidOrderInfo['payment_type'] == 'card_uah') {
  2788.  
  2789.                             // Extracting information from log
  2790.  
  2791.                             $txt = file_get_contents("http://topdj.ua/log/card_trans_" . date("Y-F", strtotime($paidOrderInfo['date_created'])) . ".log");
  2792.                             $txt = explode("\n\n", $txt);
  2793.                             foreach ($txt as $t) {
  2794.                                 $t = explode("\n", $t);
  2795.                                 if ($t[0] == $paidOrderInfo['id']) {
  2796.                                     $t = unserialize($t[1]);
  2797.                                     $text = '<b>Ошибка на русском</b><br/>' . iconv('windows-1251', 'utf-8', $t['message'] . "<br/><br/>" . $t['other']['description_admin']);
  2798.                                     $text .= '<br/><br/><b>Ошибка на английском</b><br/>' . iconv('windows-1251', 'utf-8', $t['message_en'] . "<br/><br/>" . $t['other']['transaction']['ReasonCodeDesc']);
  2799.                                     break;
  2800.                                 }
  2801.                             }
  2802.                         }
  2803.                     }
  2804.  
  2805.                     $aTopDJOrderStatuses = array(
  2806.                         0 => 'Не сформирован',
  2807.                         1 => 'Успешно оплачен',
  2808.                         2 => 'Отправлен на оплату',
  2809.                         3 => 'Не прошёл',
  2810.                         4 => 'Ожидаем подтверждения',
  2811.                     );
  2812.  
  2813.                     $paymentInfo[] = array(
  2814.                         'title' => 'Создан заказ для оплаты через TopDJ',
  2815.                         'date_log' => $paidOrderInfo['date_created'],
  2816.                         'amount' => $paidOrderInfo['amount'],
  2817.                         'currency' => $paidOrderInfo['currency_code'],
  2818.                         'info' => 'ID: ' . $paidOrderInfo['id'] . '<br/>Статус: ' . $paidOrderInfo['status'] . ($text ? '<br/><br/>' . $text : '')
  2819.                     );
  2820.                 }
  2821.             }
  2822.            
  2823.             return $paymentInfo;
  2824.            
  2825.         }
  2826.        
  2827.         public static function getOrderSecretCode($value = null, $field = 'id')
  2828.         {
  2829.             if (!$value) return 0;
  2830.            
  2831.             $secretCode = $GLOBALS['dbh']->getOne("
  2832.                 SELECT `secret_code`
  2833.                 FROM `t_order`
  2834.                 WHERE `$field` = ?", array($value)
  2835.             );
  2836.             return $secretCode;
  2837.         }
  2838.  
  2839.         public $sTableOrderLog = 't_order_log';
  2840.         public $aLogActions = array(
  2841.             'liqpay-wait' => array(
  2842.                 'title' => 'Liqpay: Заказ переведён в статус "Wait Secure"',
  2843. //          'info_template' => '%EMAIL%',
  2844.             ),
  2845.             'failed' => array(
  2846.                 'title' => 'Оплата не прошла',
  2847.                 'info_template' => 'Причина: %MESSAGE%',
  2848.             ),
  2849.             'cancelled' => array(
  2850.                 'title' => 'Аннулирован',
  2851.                 'info_template' => '%REASON%',
  2852.             ),
  2853.             'manual-apply' => array(
  2854.                 'title' => 'Смена статуса вручную на: "Оплачено"',
  2855.                 'info_template' => 'Предыдущий статус: %STATUS%<br/>Причина: %REASON%',
  2856.             ),
  2857.             'confirm-order' => array(
  2858.                 'title' => 'Смена статуса вручную на: "Оплачено"',
  2859.                 'info_template' => 'Предыдущий статус: %STATUS%',
  2860.             ),
  2861.             'resend-email' => array(
  2862.                 'title' => 'Повторная отправка e-mail',
  2863.                 'info_template' => '%EMAIL%',
  2864.             ),
  2865.             'resend-sms' => array(
  2866.                 'title' => 'Повторная отправка sms',
  2867.                 'info_template' => '%MOBILE%<br/>%TEXT%',
  2868.             ),
  2869.             'change-email' => array(
  2870.                 'title' => 'Изменение e-mail',
  2871.                 'info_template' => 'Старый: %EMAIL_OLD%<br/>Новый: %EMAIL_NEW%',
  2872.             ),
  2873.             'generate-pdf' => array(
  2874.                 'title' => 'Генерация билета',
  2875.                 'info_template' => 'Формат: %FORMAT%<br/>Штрих-код: %BAR_CODE%',
  2876.             ),
  2877.             're-generate-pdf' => array(
  2878.                 'title' => 'Повторная генерация билета',
  2879.                 'info_template' => 'Формат: %FORMAT%<br/>Штрих-код: %BAR_CODE%',
  2880.             ),
  2881.             'download-pdf' => array(
  2882.                 'title' => 'Скачать билет',
  2883.                 'info_template' => 'Формат: %FORMAT%<br/>Штрих-код: %BAR_CODE%',
  2884.             ),
  2885.             'delete-reserve' => array(
  2886.                 'title' => 'Снятия с резерва',
  2887.                 'info_template' => 'Предыдущий статус: %STATUS%<br/>Причина: %REASON%',
  2888.             ),
  2889.             'stop-selling' => array(
  2890.                 'title' => 'Продажа остановлена',
  2891.                 'info_template' => 'Предыдущий статус: %STATUS%',
  2892.             ),
  2893.         );
  2894.  
  2895.         public function addLog($params) {
  2896.  
  2897.             if (!$params['order_id'])
  2898.                 return false;
  2899.  
  2900.             $GLOBALS['dbh']->autoExecute($this->sTableOrderLog, array(
  2901.                 'order_id' => $params['order_id'],
  2902.                 'user_id' => $params['user_id'] ? $params['user_id'] : $GLOBALS['aUser']['id'],
  2903.                 'ip_address' => get_real_ip(),
  2904.                 'action' => $params['action'],
  2905.                 'info' => serialize($params['info']),
  2906.                 'date_log' => formatTime('Y-m-d H:i:s', microtime()),
  2907.             ));
  2908.         }
  2909.  
  2910.         public function getLog($order_id = false) {
  2911.  
  2912.             $tmp = $GLOBALS['dbh']->getAll(
  2913.                     '
  2914.             SELECT
  2915.                 tol.*,
  2916.                 t_user.firstname, t_user.lastname
  2917.             FROM
  2918.                 ' . $this->sTableOrderLog . ' AS tol
  2919.                     LEFT JOIN t_user oN (tol.user_id = t_user.id)
  2920.             WHERE
  2921.                 tol.order_id = ?
  2922.             ORDER BY date_log DESC, id DESC
  2923.         ', array($order_id)
  2924.             );
  2925.  
  2926.             foreach ($tmp as $k => $row) {
  2927.                 $tmp[$k]['info'] = unserialize($row['info']);
  2928.  
  2929.                 $tmp[$k]['info_text'] = $this->aLogActions[$row['action']]['info_template'];
  2930.  
  2931.                 foreach ($tmp[$k]['info'] as $n => $v) {
  2932.                     $tmp[$k]['info_text'] = str_replace('%' . strtoupper($n) . '%', $v, $tmp[$k]['info_text']);
  2933.                 }
  2934.             }
  2935.  
  2936.             return $tmp;
  2937.         }
  2938.        
  2939.         public function checkLog($order_id = false) {
  2940.             $tmp = $GLOBALS['dbh']->getRow('
  2941.                 SELECT ol.action
  2942.                 FROM t_order_log AS ol
  2943.                 WHERE ol.order_id = ?
  2944.                 ORDER BY ol.date_log DESC
  2945.                 LIMIT 1
  2946.                 ', array($order_id));
  2947.             if ($tmp['action'] == 'confirm-order')
  2948.                 return true;
  2949.             else
  2950.                 return false;
  2951.         }
  2952.        
  2953.         public function checkOrder($orderId = 0)
  2954.         {
  2955.             $orderInfo = $this->get($orderId);
  2956.             foreach ($orderInfo['items_unique'] as $typyId => $item) {
  2957.                 $cntAvailable = $item['cnt_limit'] - $item['cnt_selled'] - $item['cnt_reserved'] -
  2958.                     $item['cnt_stock'] - $item['cnt_booked'];
  2959.                 if ($item['is_place'] == 0 && $cntAvailable < $item['amount']) {
  2960.                     return false;
  2961.                 }
  2962.             }
  2963.             return true;
  2964.         }
  2965.        
  2966.         /**
  2967.          * Submit Karabas Order
  2968.          *
  2969.          * @param array $params contains ID of the order, auth key and karabas event ID
  2970.          * @access private
  2971.          * @author Chak
  2972.          * @return int Order ID on success
  2973.          */
  2974.         private function _karabasSubmitOrder($params)
  2975.         {
  2976.             $basket = ginst('Karabas')->getBasket(array(
  2977.                 'order_id' => $params['order_id'],
  2978.                 '__auth' => $params['auth']
  2979.             ));
  2980.             if (isset($basket->CommandStatus) && !empty($basket->CommandStatus) || !isset($basket->CommandStatus)) {
  2981.                 return false;
  2982.             }
  2983.             $externalId = $basket->orderId;
  2984.             $isExternalId = $GLOBALS['dbh']->getOne("
  2985.                 SELECT id
  2986.                 FROM t_order
  2987.                 WHERE partner_id = 1 AND external_id = ? ", array($externalId));
  2988.             if (isset($isExternalId)) {
  2989.                 $data = ginst('Karabas')->changeOrder($externalId);
  2990.                 return false;
  2991.             }
  2992.            
  2993.             // checking basket for tickets from another event
  2994.             if (!empty($basket->items)) {
  2995.                 foreach ($basket->items as $item) {
  2996.                     if ($item->event != $params['event_id']) {
  2997.                         ginst('Karabas')->removeTicket(array(
  2998.                             '__auth' => $params['auth'],
  2999.                             'ticket_id' => $item->id
  3000.                         ));
  3001.                     }
  3002.                 }
  3003.             }
  3004.            
  3005.             $data = ginst('Karabas')->submitOrder($externalId);
  3006.             if (isset($data->CommandStatus) && $data->CommandStatus != 0 || !isset($data->CommandStatus)) {
  3007.                 return false;
  3008.             }
  3009.            
  3010.             return $externalId;
  3011.         }
  3012.        
  3013.         /**
  3014.          * Set karabas order to the current status
  3015.          * @param int $orderId - order id
  3016.          * @param int $status - order status (1 - apply; 3 - delivery)
  3017.          * @return boolean true if success
  3018.          */
  3019.         private function karabasSetOrderStatus($orderId = 0, $status = 1)
  3020.         {  
  3021.             $orderInfo = $this->get($orderId);
  3022.             // hardcode::start for Promoter Id 273 Национальный академический Театр Русской Драмы им. Леси Украинки
  3023.             $promoterId = $GLOBALS['dbh']->getOne("
  3024.                 SELECT promoter_id
  3025.                 FROM t_event
  3026.                 WHERE id = ? ", array($orderInfo['event_id']));
  3027.             // hardcode::end
  3028.             $params = array (
  3029.                 'order_id' => $orderInfo['external_id'],
  3030.                 'format' => ($promoterId == 273 ? 8 : $orderInfo['items'][0]['format_id']),
  3031.                 'payment_type' => $orderInfo['payment_type']
  3032.             );
  3033.             if ($status == 1) {
  3034.                 $statusOrder = ginst('Karabas')->confirmOrder($params);
  3035.             } else {
  3036.                 $deliveryPeriod = ($orderInfo['city_id'] != 10184 ? $orderInfo['addr']['period'] + 5 : 4);
  3037.                 $deliveryDate = $params['delivery_date'] = date('d.m.Y H:i', strtotime($orderInfo['date_created']) + 60 * 60 * 24 * $deliveryPeriod);
  3038.                 $statusOrder = ginst('Karabas')->deliveryOrder($params);
  3039.             }
  3040.             if (!empty($statusOrder->status) && $statusOrder->status == $status) {
  3041.                 if (!empty($statusOrder->tickets)) {
  3042.                     foreach ($statusOrder->tickets as $ticket) {
  3043.                         if (!empty($ticket->Barcode)) {
  3044.                             $GLOBALS['dbh']->query("UPDATE t_ticket SET bar_code = '{$ticket->Barcode}', bar_code_type = 'code128' WHERE order_id = '{$orderInfo['id']}' AND external_id = '{$ticket->id}' ");
  3045.                         }
  3046.                     }
  3047.                 }
  3048.                 if ($statusOrder->status == 3) {
  3049.                     $GLOBALS['dbh']->query("UPDATE `t_order` SET `delivery_expired` = STR_TO_DATE('{$deliveryDate}','%d.%m.%Y %H:%i') WHERE `id` = {$orderInfo['id']}");
  3050.                 }
  3051.             } else {
  3052.                 return false;
  3053.             }
  3054.  
  3055.             return true;
  3056.         }
  3057.        
  3058.         /**
  3059.          * Method return all orders in offline
  3060.          *
  3061.          * @access public
  3062.          * @author Yuriy Stefanyuk
  3063.          * @param int $eventId
  3064.          * @return array
  3065.          */
  3066.         public function getOfflineOrders($eventId = false)
  3067.         {
  3068.             if (!$eventId) return;
  3069.            
  3070.             $tmp = $GLOBALS['dbh']->getAll("
  3071.                 SELECT id, lastname, firstname, city_name, email, mobile, price_total, secret_code,
  3072.                     CASE partner_id
  3073.                         WHEN 1 THEN 'Karabas'
  3074.                         WHEN 10 THEN 'Premiera'
  3075.                         WHEN 11 THEN 'Internet bilet'
  3076.                      END AS partner_name,
  3077.                     external_id
  3078.                 FROM " . $this->table_name . "
  3079.                 WHERE event_id = ? AND paid_status = 4
  3080.                 ", array($eventId)
  3081.             );
  3082.            
  3083.             return $tmp;
  3084.         }
  3085.        
  3086.         /**
  3087.          * Method canceling all offline orders
  3088.          *
  3089.          * @access public
  3090.          * @author Yuriy Stefanyuk
  3091.          * @param int $eventId
  3092.          * @return void
  3093.          */
  3094.         public function cancelingOfflineOrders($eventId = false)
  3095.         {
  3096.             if (!$eventId) return;
  3097.             $mobiles = array();
  3098.             $event = ginst('Event')->getNotTerminatedEvents($eventId, 1);
  3099.  
  3100.             $offlineOrders = ginst('Order')->getOfflineOrders($event['id']);
  3101.             if (!$offlineOrders) return;
  3102.  
  3103.  
  3104.             foreach ($offlineOrders as $order) {
  3105.                 ginst('Order')->addLog(array(
  3106.                     'order_id' => $order['id'],
  3107.                     'action' => 'stop-selling',
  3108.                     'info' => array(
  3109.                         'status' => 'Остановка продаж'
  3110.                     ),
  3111.                 ));
  3112.  
  3113.                 if ($order['external_id'] > 0) {
  3114.                     ginst('Karabas')->cancelOrder($order['external_id'], 'stop selling');
  3115.                     $GLOBALS['dbh']->autoExecute('t_order', array(
  3116.                         'paid_status' => 6,
  3117.                         'cancelled_reason' => 'Продажа остановлена',
  3118.                     ), DB_AUTOQUERY_UPDATE, 'id = '.$order['id']);
  3119.  
  3120.                     $GLOBALS['dbh']->autoExecute('t_ticket', array(
  3121.                         'is_canceled' => 1,
  3122.                     ), DB_AUTOQUERY_UPDATE, 'order_id = '.$order['id']);
  3123.                 } else {
  3124.                     $GLOBALS['dbh']->autoExecute('t_order', array(
  3125.                         'paid_status' => 6,
  3126.                         'cancelled_reason' => 'Продажа остановлена',
  3127.                     ), DB_AUTOQUERY_UPDATE, 'id = '.$order['id']);
  3128.  
  3129.                     $GLOBALS['dbh']->autoExecute('t_ticket', array(
  3130.                         'is_canceled' => 1,
  3131.                     ), DB_AUTOQUERY_UPDATE, 'order_id = '.$order['id']);
  3132.  
  3133.                     $tickets = $GLOBALS['dbh']->getCol("SELECT type_place_id FROM t_ticket WHERE order_id = " . $order['id'] . " AND type_place_id IS NOT NULL");
  3134.  
  3135.                     $placesId = implode(",",$tickets);
  3136.  
  3137.                     if (!empty($placesId)) {
  3138.                         $GLOBALS['dbh']->autoExecute('t_ticket_type_place', array(
  3139.                             'is_reserved' => 0,
  3140.                             'date_cancelling' => 'NULL',
  3141.                         ), DB_AUTOQUERY_UPDATE, ' id IN ('.$placesId.') AND is_sold = 0 AND is_booking = 0');
  3142.                     }
  3143.  
  3144.                 }
  3145.             }
  3146.         }
  3147.        
  3148.         /**
  3149.          * Method return all orders in courier delivery
  3150.          *
  3151.          * @access public
  3152.          * @author Yuriy Stefanyuk
  3153.          * @param int $eventId
  3154.          * @return array
  3155.          */
  3156.         public function getCourierOrders($eventId = false)
  3157.         {
  3158.             if (!$eventId) return;
  3159.            
  3160.             $tmp = $GLOBALS['dbh']->getAll("
  3161.                 SELECT DISTINCT
  3162.                     `o`.`id`, `o`.`lastname`, `o`.`firstname`, `o`.`email`, `o`.`mobile`, `o`.`price_total`, `o`.`external_id`, LOWER(`o`.`billing_currency`) AS `billing_currency`,
  3163.                     `ec`.`title`, `d`.`newpost_order_id` AS `np_order_id`, `nw`.address, `d`.`id` AS `delivery_id`,
  3164.                     `cn`.`name` AS `country`, `c`.`name` AS `city`, `r`.`name` AS `province`,
  3165.                     `a`.`street`, `a`.`house`, `a`.`flat`, `a`.`zip`, `a`.`ware_id`
  3166.                 FROM
  3167.                     `t_order` AS `o`
  3168.                 INNER JOIN `t_event_content` AS `ec` ON `ec`.`id` = `o`.`event_id` AND `ec`.`language_id` = ?
  3169.                 INNER JOIN `t_ticket` AS `t` ON `t`.`order_id` = `o`.`id`
  3170.                 INNER JOIN `t_delivery` AS `d` ON `d`.`order_id` = `o`.`id`
  3171.                 INNER JOIN `t_address` AS `a` ON `d`.`address_to` = `a`.`id`
  3172.                 INNER JOIN `city` AS `c` ON `c`.`city_id` = `a`.`city`
  3173.                 INNER JOIN `country` AS `cn` ON `cn`.`country_id` = `a`.`country`
  3174.                 INNER JOIN `region` AS `r` ON `r`.`region_id` = `a`.`province`
  3175.                 LEFT JOIN `t_newpost_warenhouse` AS `nw` ON `nw`.`ware_id` = `a`.`ware_id`
  3176.                 WHERE
  3177.                     `o`.`event_id` = ? AND `o`.`paid_status` = 8
  3178.                 ORDER BY `o`.`date_created` DESC"
  3179.                 , array($GLOBALS['lng']['id'],$eventId)
  3180.             );
  3181.            
  3182.             return $tmp;
  3183.         }
  3184.        
  3185.         public function ibConfirmOrder($params = array(), $str = ''){
  3186.             $confirmOrder = ginst('InternetBilet')->bookingConfirm($params['ext_id']);
  3187.             if(!$confirmOrder){
  3188.                 return false;
  3189.             }
  3190.             if (!empty($confirmOrder->places)) {
  3191.                 foreach($confirmOrder->places as $place){
  3192.                     $GLOBALS['dbh']->autoExecute("t_ticket", array('bar_code' => $place->barcode, 'bar_code_type'=>'code128'), DB_AUTOQUERY_UPDATE, "order_id = '{$params['order_id']}' AND external_id = '{$place->ticket_id}'");
  3193.                 }
  3194.             }
  3195.             return true;
  3196.         }
  3197.        
  3198.        
  3199.         private function _flashBoxConfirmOrder($orderId)
  3200.         {
  3201.             $order = $this->get($orderId);
  3202.             $tickets = ginst('FlashBox')->payTicket($order['external_id']);
  3203.             if (empty($tickets)) {
  3204.                 //cancel order
  3205.                 return false;
  3206.             }
  3207.             foreach ($order['items'] as $item) {
  3208.                 foreach ($tickets->purchase_tickets as $ticket) {
  3209.                     if ($ticket->ticket_id == $item['external_id'] && $ticket->purchase_status == 'ok') {
  3210.                         $GLOBALS['dbh']->autoExecute("t_ticket", array(
  3211.                             'bar_code' => $ticket->baracode,
  3212.                             'bar_code_type' => 'code128'
  3213.                         ), DB_AUTOQUERY_UPDATE, "order_id = '{$orderId}' AND external_id = '{$ticket->ticket_id}'");
  3214.                         if (empty($item['type_place_id'])) {
  3215.                             $GLOBALS['dbh']->autoExecute("t_ticket_type_seat", array(
  3216.                                 'is_used' => 1,
  3217.                                 'date_used' => NOW,
  3218.                                 'ticket_id' => $item['id']
  3219.                             ), DB_AUTOQUERY_UPDATE, "external_id = '{$ticket->ticket_id}' AND type_id = '{$item['type_id']}'");
  3220.                         }
  3221.                         break;
  3222.                     }
  3223.                 }
  3224.             }
  3225.             return true;
  3226.         }
  3227.        
  3228.         private function _flashBoxCancelOrder($orderId)
  3229.         {
  3230.             $order = $this->get($orderId);
  3231.             foreach ($order['items'] as $item) {
  3232.                 $ticket = ginst('FlashBox')->removeTicket(array(
  3233.                     'ticket_id' => $item['external_id'],
  3234.                     'barcode' => $item['bar_code']
  3235.                 ));
  3236.                 if (empty($ticket)) {
  3237.                     return false;
  3238.                 }
  3239.                 if (empty($item['type_place_id'])) {
  3240.                     $GLOBALS['dbh']->autoExecute("t_ticket_type_seat", array(
  3241.                         'is_used' => 0
  3242.                     ), DB_AUTOQUERY_UPDATE, "external_id = '{$ticket->ticket_id}' AND type_id = '{$item['type_id']}' AND ticket_id = '{$item['id']}'");
  3243.                 }
  3244.             }
  3245.             return true;
  3246.         }
  3247.        
  3248.         /**
  3249.          * Check place for status on FlashBox system
  3250.          * @param int $placeId place ID on the scheme
  3251.          * @author Chak
  3252.          * @return int ticket id on success
  3253.          */
  3254.         private function _flashBoxCheckPlace($placeId = 0)
  3255.         {
  3256.             $id = $GLOBALS['dbh']->getOne("SELECT external_id FROM t_ticket_type_place WHERE id = ? ", array($placeId));
  3257.             $status = ginst('FlashBox')->getTicketStatus($id);
  3258.             if (empty($status) || $status->ticket_status != 'available') {
  3259.                 if ($status->ticket_status == 'sold') {
  3260.                     $GLOBALS['dbh']->autoExecute('t_ticket_type_place', array(
  3261.                         'is_sold' => 1
  3262.                     ), DB_AUTOQUERY_UPDATE, ' id = ' . $placeId);
  3263.                 } elseif ($status->ticket_status == 'booked') {
  3264.                     $GLOBALS['dbh']->autoExecute('t_ticket_type_place', array(
  3265.                         'is_reserved' => 1,
  3266.                         'date_cancelling' => null
  3267.                     ), DB_AUTOQUERY_UPDATE, ' id = ' . $placeId);
  3268.                 }
  3269.                 return false;
  3270.             }
  3271.             return $status->ticket_id;
  3272.         }
  3273.        
  3274.         /**
  3275.          * Method updates all reserved order where date cancelling reservation < now
  3276.          *
  3277.          * @access public
  3278.          * @author Yuriy Stefanyuk
  3279.          * @param int $eventId
  3280.          * @return void
  3281.          */
  3282.         public function updateReservedOrders($eventId = null)
  3283.         {
  3284.             if (!$eventId) return;
  3285.             $orders = $GLOBALS['dbh']->getAll("SELECT * FROM t_order WHERE reserv_cancelling < NOW() AND paid_status = 10 AND event_id = ? ", array($eventId));
  3286.            
  3287.             if (!$orders) return;
  3288.  
  3289.             foreach ($orders as $order) {
  3290.                 $this->cancel($order, 'Время для выкупа резервации закончилось', ORDER_STATUS_TIMEOUT);
  3291.             }
  3292.         }
  3293.        
  3294.         /**
  3295.          * Повертає всі продажі продавців церез сейл
  3296.          *
  3297.          * @global object $dbh
  3298.          * @global object $aUser
  3299.          * @param array $clause
  3300.          * @return array
  3301.          */
  3302.         public function getSaleOrders($clause)
  3303.         {
  3304.             global $dbh, $aUser;
  3305.            
  3306.             $sLimit = $clause['limit'];
  3307.             $sWhere = '';
  3308.            
  3309.             if (!$aUser['is_admin']) {
  3310.                 $sWhere = " AND o.client_id = {$aUser['id']}";
  3311.             }
  3312.            
  3313.             if(!empty($clause['where'])) {
  3314.                 $sWhere .= $clause['where'];
  3315.             }
  3316.            
  3317.             $ordersIds = $dbh->getCol("
  3318.                 SELECT SQL_CALC_FOUND_ROWS
  3319.                     o.id
  3320.                 FROM t_order AS o
  3321.                 INNER JOIN t_event AS e ON e.id = o.event_id
  3322.                 INNER JOIN t_event_content AS ec ON (ec.id, ec.language_id) = ROW(e.id, 1)
  3323.                 INNER JOIN t_venue_content AS vc ON (vc.id, vc.language_id) = ROW(e.venue_id, 1)
  3324.                 WHERE o.payment_type = 'offline' {$sWhere}             
  3325.                 ORDER BY o.id DESC LIMIT {$sLimit}
  3326.             ");
  3327.            
  3328.             $totalOrders = $dbh->getOne('SELECT FOUND_ROWS()');
  3329.            
  3330.             if (empty($ordersIds)) {
  3331.                 $ordersIds[] = 0;
  3332.             }
  3333.            
  3334.             $ordersInfo = $dbh->getAssoc("
  3335.                 SELECT
  3336.                 o.id, COUNT(t.id) AS ticket_cnt, o.firstname as client_firstname, o.lastname as client_lastname, o.price_total, o.mobile, o.email, o.paid_status,
  3337.                 DATE_FORMAT(e.date_event, '%d.%m.%Y / %H:%i') AS date_event, ec.title AS event_title,
  3338.                 vc.title AS venue_title, pc.title AS promoter_title,
  3339.                 u.firstname, u.lastname, DATE_FORMAT(o.date_confirmed, '%d.%m.%Y %H:%i') as date_confirmed
  3340.             FROM t_order AS o
  3341.             LEFT JOIN t_ticket AS t ON t.order_id = o.id
  3342.             LEFT JOIN t_event AS e ON e.id = o.event_id
  3343.             LEFT JOIN t_event_content AS ec ON (ec.id, ec.language_id) = ROW(e.id, 1)
  3344.             LEFT JOIN t_venue AS v ON v.id = e.venue_id
  3345.             LEFT JOIN t_venue_content AS vc ON (vc.id, vc.language_id) = ROW(e.venue_id, 1)
  3346.             LEFT JOIN t_promoter AS p ON p.id = e.promoter_id
  3347.             LEFT JOIN t_promoter_content AS pc ON (pc.id, pc.language_id) = ROW(e.promoter_id, 1)
  3348.             LEFT JOIN t_user AS u ON u.id = o.client_id WHERE o.id IN (!) GROUP BY o.id ORDER BY o.id DESC
  3349.             ", 0, array(implode(', ', $ordersIds)));
  3350.            
  3351.             foreach ($ordersInfo as $orderId => $order) {
  3352.                 $ordersInfo[$orderId]['paid_status'] = $this->paidStatuses[$order['paid_status']]['title'];
  3353.             }
  3354.            
  3355.             return array(
  3356.                 'orders' => $ordersInfo,
  3357.                 'totals' => $totalOrders
  3358.             );
  3359.         }
  3360.        
  3361.         /**
  3362.          * Assign special certificate for each ticket in the order
  3363.          * @param array $params input params
  3364.          * @return array certicate datas
  3365.          */
  3366.         public function checkCertificate($params = array())
  3367.         {
  3368.             $result = array();
  3369.             if (empty($params['event']['certificate_id'])) {
  3370.                 return $result;
  3371.             }
  3372.             foreach ($params['event']['ticketTypes_all'] as $type) {
  3373.                 if ($type['certificate_id'] == $params['event']['certificate_id']) {
  3374.                     $result = $type;
  3375.                     break;
  3376.                 }
  3377.             }
  3378.             $amount = 0;
  3379.             if (!empty($params['items'])) {
  3380.                 foreach($params['items'] as $item) {
  3381.                     if ($item['group_id'] == 1) {
  3382.                         $amount += $item['amount'];
  3383.                     }
  3384.                 }
  3385.             }
  3386.             if (!empty($params['places'])) {
  3387.                 $amount += count($params['places']);
  3388.             }
  3389.             $result['amount'] = $amount;
  3390.            
  3391.             return $result;
  3392.         }
  3393.     }
  3394.  
  3395. endif;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement