Completed
Push — trunk ( 0e7a2e...6a6c5e )
by SuperNova.WS
07:28
created

metamatter.php (1 issue)

Labels
Severity
1
<?php
2
3
global $debug;
4
5
// Придумать какой статус должен быть у глобальных ответов, что бы не перекрывать статусы платежных систем
6
// Может добавить спецстатус "Ответ системы платежа" и парсить дальше getMessage
7
// см constants.php
8
9
use Modules\sn_module;
0 ignored issues
show
This use statement conflicts with another class in this namespace, sn_module. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
10
11
include_once('common.' . substr(strrchr(__FILE__, '.'), 1));
12
13
if (!SN::$gc->modules->countModulesInGroup('payment')) {
14
  sys_redirect('dark_matter.php');
15
  die();
16
}
17
18
global $config;
19
20
lng_include('payment');
21
lng_include('infos');
22
23
$template = gettemplate('metamatter', true);
24
25
// $player_currency_default = player_load_option($user, PLAYER_OPTION_CURRENCY_DEFAULT);
26
$player_currency_default = SN::$user_options[PLAYER_OPTION_CURRENCY_DEFAULT];
27
$player_currency = sys_get_param_str('player_currency', $player_currency_default);
28
empty(SN::$lang['pay_currency_list'][$player_currency]) ? ($player_currency = $player_currency_default ? $player_currency_default : SN::$config->payment_currency_default) : false;
29
// $player_currency_default != $player_currency ? player_save_option($user, PLAYER_OPTION_CURRENCY_DEFAULT, $player_currency) : false;
30
$player_currency_default != $player_currency ? SN::$user_options[PLAYER_OPTION_CURRENCY_DEFAULT] = $player_currency : false;
31
32
//// Конвертация ММ в ТМ
33
//if(sys_get_param('mm_convert_do')) {
34
//  try {
35
//    if(!($mm_convert = sys_get_param_id('mm_convert'))) {
36
//      throw new exception($lang['pay_msg_mm_convert_wrong_amount'], ERR_ERROR);
37
//    }
38
//
39
//    sn_db_transaction_start();
40
//    $user = db_user_by_id($user['id'], true);
41
//    if($mm_convert > mrc_get_level($user, null, RES_METAMATTER)) {
42
//      throw new exception($lang['pay_msg_mm_convert_not_enough'], ERR_ERROR);
43
//    }
44
//
45
//    $payment_comment = sprintf("Игрок сконвертировал %d Метаматерии в Тёмную Материю", $mm_convert);
46
//    if(!mm_points_change($user['id'], RPG_CONVERT_MM, -$mm_convert, $payment_comment)) {
47
//      throw new exception($lang['pay_msg_mm_convert_mm_error'], ERR_ERROR);
48
//    }
49
//    if(!rpg_points_change($user['id'], RPG_CONVERT_MM, $mm_convert, $payment_comment)) {
50
//      throw new exception($lang['pay_msg_mm_convert_dm_error'], ERR_ERROR);
51
//    }
52
//
53
//    $template->assign_block_vars('result', array(
54
//      'STATUS'  => ERR_NONE,
55
//      'MESSAGE' => sprintf('Конвертация %1$s единиц Метаматерии в %1$s единиц Тёмной Материи успешно произведена', pretty_number($mm_convert)),
56
//    ));
57
//
58
//    sn_db_transaction_commit();
59
//  } catch(exception $e) {
60
//    sn_db_transaction_rollback();
61
//    $template->assign_block_vars('result', $response = array(
62
//      'STATUS'  => $e->getCode(),
63
//      'MESSAGE' => $e->getMessage(),
64
//    ));
65
//  }
66
//}
67
68
// Таблица скидок
69
$prev_discount = 0;
70
if (isset(sn_module_payment::$bonus_table) && is_array(sn_module_payment::$bonus_table)) {
71
  foreach (sn_module_payment::$bonus_table as $sum => $discount) {
72
    if ($discount && $discount != $prev_discount) {
73
      $template->assign_block_vars('discount', array(
74
        'SUM'          => $sum,
75
        'DISCOUNT'     => $discount * 100,
76
        'DISCOUNT_ONE' => 1 + $discount,
77
        'TEXT'         => sprintf(SN::$lang['pay_mm_bonus_each'], HelperString::numberFloorAndFormat($sum), round($discount * 100)),
78
      ));
79
      $prev_discount = $discount;
80
    }
81
  }
82
}
83
84
// Результат платежа
85
if ($payment_id = sys_get_param_id('payment_id')) {
86
  $payment = doquery("SELECT * FROM {{payment}} WHERE `payment_id` = {$payment_id} LIMIT 1;", true);
87
  if ($payment && $payment['payment_user_id'] == $user['id']) {
88
    if ($payment['payment_status'] == PAYMENT_STATUS_COMPLETE) {
89
      $template->assign_block_vars('result', array('MESSAGE' => sprintf(SN::$lang['pay_msg_mm_purchase_complete'], $payment['payment_dark_matter_paid'], $payment['payment_module_name'], $payment['payment_dark_matter_gained'])));
90
    }
91
    if ($payment['payment_status'] == PAYMENT_STATUS_NONE) {
92
      $template->assign_block_vars('result', array(
93
        'MESSAGE' => sprintf(SN::$lang['pay_msg_mm_purchase_incomplete'], $payment['payment_dark_matter_paid'], $payment['payment_module_name']),
94
        'STATUS'  => 1,
95
      ));
96
    }
97
    if ($payment['payment_test']) {
98
      $template->assign_block_vars('result', array(
99
        'MESSAGE' => sprintf(SN::$lang['pay_msg_mm_purchase_test']),
100
        'STATUS'  => -1,
101
      ));
102
    }
103
  }
104
}
105
106
$unit_available_amount_list = &sn_module_payment::$bonus_table;
107
108
$request = array(
109
  'metamatter' => sys_get_param_float('metamatter'),
110
);
111
112
if (!$request['metamatter']) {
113
  unset($_POST);
114
}
115
116
$payment_methods_available = array_combine(array_keys(sn_module_payment::$payment_methods), array_fill(0, count(sn_module_payment::$payment_methods), null));
117
array_walk($payment_methods_available, function (&$value, $index) {
118
  $value = !empty(sn_module_payment::$payment_methods[$index]) ? array_combine(array_keys(sn_module_payment::$payment_methods[$index]), array_fill(0, count(sn_module_payment::$payment_methods[$index]), null)) : $value;
119
});
120
121
$payment_module_valid = false;
122
$payment_module_request = sys_get_param_str('payment_module');
123
foreach (SN::$gc->modules->getModulesInGroup('payment', true) as $module_name => $module) {
124
  /**
125
   * @var sn_module $module
126
   */
127
128
  if (!is_object($module) || !$module->isActive()) {
129
    continue;
130
  }
131
132
  lng_include($module_name, $module->getRootRelative());
133
134
  foreach (sn_module_payment::$payment_methods as $payment_type_id => $available_methods) {
135
    foreach ($available_methods as $payment_method => $payment_currency) {
136
      if (isset($module->manifest['payment_method'][$payment_method])) {
137
        $payment_methods_available[$payment_type_id][$payment_method][$module_name] = $module->manifest['payment_method'][$payment_method];
138
      }
139
    }
140
  }
141
142
  $payment_module_valid = $payment_module_valid || $module_name == $payment_module_request;
143
}
144
145
global $template_result;
146
// Доступные платежные методы
147
foreach ($payment_methods_available as $payment_type_id => $payment_methods) {
148
  if (empty($payment_methods)) {
149
    continue;
150
  }
151
152
  $template_result['.']['payment'][$payment_type_id] = array(
153
    'ID'   => $payment_type_id,
154
    'NAME' => SN::$lang['pay_methods'][$payment_type_id],
155
  );
156
  foreach ($payment_methods as $payment_method_id => $module_list) {
157
    if (empty($module_list)) {
158
      continue;
159
    }
160
    $template_result['.']['payment'][$payment_type_id]['.']['method'][$payment_method_id] = array(
161
      'ID'         => $payment_method_id,
162
      'NAME'       => SN::$lang['pay_methods'][$payment_method_id],
163
      'IMAGE'      => isset(sn_module_payment::$payment_methods[$payment_type_id][$payment_method_id]['image'])
164
        ? sn_module_payment::$payment_methods[$payment_type_id][$payment_method_id]['image'] : '',
165
      'NAME_FORCE' => isset(sn_module_payment::$payment_methods[$payment_type_id][$payment_method_id]['name']),
166
      'BUTTON'     => isset(sn_module_payment::$payment_methods[$payment_type_id][$payment_method_id]['button']),
167
    );
168
    foreach ($module_list as $payment_module_name => $payment_module_method_details) {
169
      $template_result['.']['payment'][$payment_type_id]['.']['method'][$payment_method_id]['.']['module'][] = array(
170
        'MODULE' => $payment_module_name,
171
      );
172
    }
173
  }
174
175
  if (empty($template_result['.']['payment'][$payment_type_id]['.'])) {
176
    unset($template_result['.']['payment'][$payment_type_id]);
177
  }
178
}
179
180
$template->assign_recursive($template_result);
181
182
$payment_type_selected = sys_get_param_int('payment_type');
183
$payment_method_selected = sys_get_param_int('payment_method');
184
185
$payment_module_valid = $payment_module_valid && (!$payment_method_selected || isset($payment_methods_available[$payment_type_selected][$payment_method_selected][$module_name]));
186
187
// If payment_module invalid - making it empty OR if there is only one payment_module - selecting it
188
if ($payment_module_valid) {
189
  // $payment_module = $payment_module; // Really - do nothing
190
} elseif ($payment_type_selected && count($payment_methods_available[$payment_type_selected][$payment_method_selected]) == 1) {
191
  reset($payment_methods_available[$payment_type_selected][$payment_method_selected]);
192
  $payment_module_request = key($payment_methods_available[$payment_type_selected][$payment_method_selected]);
193
} elseif (SN::$gc->modules->countModulesInGroup('payment') == 1) {
194
  $payment_module_request = $module_name;
195
} else {
196
  $payment_module_request = '';
197
}
198
199
if ($payment_type_selected && $payment_method_selected) {
200
  foreach ($payment_methods_available[$payment_type_selected][$payment_method_selected] as $module_name => $temp) {
201
    $template->assign_block_vars('payment_module', array(
202
      'ID'          => $module_name,
203
      'NAME'        => SN::$lang["module_{$module_name}_name"],
204
      'DESCRIPTION' => SN::$lang["module_{$module_name}_description"],
205
    ));
206
  }
207
}
208
209
foreach (SN::$lang['pay_currency_list'] as $key => $value) {
210
  $course = get_exchange_rate($key);
211
  if (!$course) {
212
    continue;
213
  }
214
  $template->assign_block_vars('exchange', array(
215
    'SYMBOL'          => $key,
216
    'TEXT'            => $value,
217
    'COURSE_DIRECT'   => HelperString::numberFormat($course, 4),
218
    'COURSE_REVERSE'  => HelperString::numberFormat(1 / $course, 4),
219
    'MM_PER_CURRENCY' => HelperString::numberFormat(sn_module_payment::currency_convert(1, $key, 'MM_'), 2),
220
    'LOT_PRICE'       => sn_module_payment::currency_convert(get_mm_cost(), 'MM_', $key),
221
    'DEFAULT'         => $key == SN::$config->payment_currency_default,
222
  ));
223
}
224
225
if ($request['metamatter'] && $payment_module_request) {
226
  try {
227
    $paymentModuleReal = SN::$gc->modules->getModule($payment_module_request);
228
    if(!is_object($paymentModuleReal)) {
229
      throw new Exception('{ Менеджер модулей вернул null вместо платёжного модуля для }' . $payment_module_request, ERR_ERROR);
230
    }
231
    /**
232
     * @var sn_module_payment $paymentModuleReal
233
     */
234
235
    // Any possible errors about generating paylink should be raised in module!
236
    $pay_link = $paymentModuleReal->compile_request($request);
237
238
    // Поддержка дополнительной информации
239
    if (is_array($pay_link['RENDER'])) {
240
      foreach ($pay_link['RENDER'] as $html_data) {
241
        $template->assign_block_vars('render', $html_data);
242
        if (isset($html_data['VALUE']) && is_array($html_data['VALUE'])) {
243
          foreach ($html_data['VALUE'] as $value_id => $value_value) {
244
            $template->assign_block_vars('render.value', array(
245
              'FIELD' => $value_id,
246
              'VALUE' => $value_value,
247
            ));
248
          }
249
        }
250
      }
251
    }
252
253
    // Поддержка передачи данных для многошаговых платежных систем
254
    if (is_array($pay_link['DATA'])) {
255
      foreach ($pay_link['DATA'] as $key => $value) {
256
        $template->assign_block_vars('pay_link_data', array(
257
          'FIELD' => $key,
258
          'VALUE' => $value,
259
        ));
260
      }
261
    }
262
263
    if (is_array($pay_link) && in_array($pay_link['PAY_LINK_METHOD'], array('POST', 'GET', 'LINK', 'STEP'))) {
264
      // TODO Переделать это под assign_vars_recursive и возвращать пустые строки если нет платежного метода - для унификации формы в темплейте
265
      $template->assign_vars(array(
266
        'PAY_LINK_METHOD' => $pay_link['PAY_LINK_METHOD'],
267
        'PAY_LINK_URL'    => $pay_link['PAY_LINK_URL'],
268
      ));
269
    } else {
270
      throw new exception(SN::$lang['pay_msg_request_paylink_unsupported'], ERR_ERROR);
271
    }
272
  } catch (exception $e) {
273
    $template->assign_block_vars('result', $response = array(
274
      'STATUS'  => $e->getCode(),
275
      'MESSAGE' => $e->getMessage(),
276
    ));
277
    $debug->warning('Результат операции: код ' . $e->getCode() . ' сообщение "' . $e->getMessage() . '"', 'Ошибка платежа', LOG_INFO_PAYMENT);
278
  }
279
}
280
281
// Прегенерированные пакеты
282
foreach ($unit_available_amount_list as $unit_amount => $discount) {
283
  $temp = sn_module_payment::currency_convert($unit_amount, 'MM_', $player_currency);
284
  $template->assign_block_vars('mm_amount', array(
285
    'VALUE'            => $unit_amount,
286
    // 'PRICE' => $temp,
287
    'PRICE_TEXT'       => HelperString::numberFormat($temp, 2),
288
    'CURRENCY'         => $player_currency,
289
    'DISCOUNT'         => $discount,
290
    'DISCOUNT_PERCENT' => $discount * 100,
291
    'DISCOUNTED'       => $unit_amount * (1 + $discount),
292
    'TEXT'             => HelperString::numberFloorAndFormat($unit_amount),
293
    'TEXT_DISCOUNTED'  => HelperString::numberFloorAndFormat($unit_amount * (1 + $discount)),
294
  ));
295
}
296
297
$currency = $payment_module_request ? sn_module_payment::$payment_methods[$payment_type_selected][$payment_method_selected]['currency'] : '';
298
$bonus_percent = round(sn_module_payment::bonus_calculate($request['metamatter'], true, true) * 100);
299
$income_metamatter_text = prettyNumberStyledDefault(sn_module_payment::bonus_calculate($request['metamatter']));
300
301
$template->assign_vars(array(
302
  'PAGE_HEADER' => SN::$lang['sys_metamatter'],
303
304
  'URL_PURCHASE' => SN::$config->url_purchase_metamatter,
305
306
  'PAYMENT_TYPE'        => $payment_type_selected,
307
  'PAYMENT_METHOD'      => $payment_method_selected,
308
  'PAYMENT_METHOD_NAME' => SN::$lang['pay_methods'][$payment_method_selected],
309
310
  'PAYMENT_MODULE'             => $payment_module_request,
311
  'PAYMENT_MODULE_NAME'        => SN::$lang["module_{$payment_module_request}_name"],
312
  'PAYMENT_MODULE_DESCRIPTION' => SN::$lang["module_{$payment_module_request}_description"],
313
314
  'PLAYER_CURRENCY'              => $player_currency,
315
  'PLAYER_CURRENCY_PRICE_PER_MM' => sn_module_payment::currency_convert(1, $player_currency, 'MM_', 10),
316
317
  'UNIT_AMOUNT'                 => (float)$request['metamatter'],
318
  'UNIT_AMOUNT_TEXT'            => HelperString::numberFloorAndFormat($request['metamatter']),
319
  'UNIT_AMOUNT_BONUS_PERCENT'   => $bonus_percent,
320
  'UNIT_AMOUNT_TEXT_DISCOUNTED' => $income_metamatter_text,
321
  'UNIT_AMOUNT_TEXT_COST_BASE'  => HelperString::numberFormat(sn_module_payment::currency_convert($request['metamatter'], 'MM_', $player_currency), 2),
322
323
  'PAYMENT_CURRENCY_EXCHANGE_DEFAULT' => prettyNumberStyledDefault(get_mm_cost()),
324
  'PAYMENT_CURRENCY_DEFAULT_TEXT'     => SN::$lang['pay_currency_list'][SN::$config->payment_currency_default],
325
326
  'METAMATTER' => mrc_get_level($user, '', RES_METAMATTER),
327
328
  'METAMATTER_COST_TEXT'       => sprintf(SN::$lang['pay_mm_buy_conversion_cost'],
329
    prettyNumberStyledDefault($request['metamatter']),
330
    number_format($mmWish = sn_module_payment::currency_convert($request['metamatter'], 'MM_', $currency), 2, ',', '.'),
331
    $currency,
332
    prettyNumberGetClass($mmWish, true)),
333
  'METAMATTER_COST_BONUS_TEXT' => $bonus_percent
334
    ? sprintf(SN::$lang['pay_mm_buy_real_income'], prettyNumberStyledDefault($bonus_percent), $income_metamatter_text)
335
    : '',
336
337
  'DARK_MATTER_DESCRIPTION' => SN::$lang['info'][RES_DARK_MATTER]['description'],
338
339
  'PAYMENT_AVAILABLE' => SN::$gc->modules->countModulesInGroup('payment') && !defined('SN_GOOGLE'),
340
341
));
342
343
display($template, SN::$lang['sys_metamatter']);
344