Passed
Branch trunk (3f392c)
by SuperNova.WS
04:59
created

metamatter.php (16 issues)

1
<?php
2
3
global $debug;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
4
5
// Придумать какой статус должен быть у глобальных ответов, что бы не перекрывать статусы платежных систем
6
// Может добавить спецстатус "Ответ системы платежа" и парсить дальше getMessage
7
// см constants.php
8
9
include_once('common.' . substr(strrchr(__FILE__, '.'), 1));
10
11
if(!sn_module::sn_module_get_active_count('payment')) {
12
  sys_redirect('dark_matter.php');
13
  die();
14
}
15
16
global $config;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
17
18
lng_include('payment');
19
lng_include('infos');
20
21
$template = gettemplate('metamatter', true);
0 ignored issues
show
true of type true is incompatible with the type null|template expected by parameter $template of gettemplate(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

21
$template = gettemplate('metamatter', /** @scrutinizer ignore-type */ true);
Loading history...
22
23
// $player_currency_default = player_load_option($user, PLAYER_OPTION_CURRENCY_DEFAULT);
0 ignored issues
show
Unused Code Comprehensibility introduced by
47% of this comment could be valid code. Did you maybe forget this after debugging?

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

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

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

Loading history...
24
$player_currency_default = classSupernova::$user_options[PLAYER_OPTION_CURRENCY_DEFAULT];
25
$player_currency = sys_get_param_str('player_currency', $player_currency_default);
26
empty(classSupernova::$lang['pay_currency_list'][$player_currency]) ? ($player_currency =  $player_currency_default ? $player_currency_default : classSupernova::$config->payment_currency_default) : false;
27
// $player_currency_default != $player_currency ? player_save_option($user, PLAYER_OPTION_CURRENCY_DEFAULT, $player_currency) : false;
0 ignored issues
show
Unused Code Comprehensibility introduced by
52% of this comment could be valid code. Did you maybe forget this after debugging?

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

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

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

Loading history...
28
$player_currency_default != $player_currency ? classSupernova::$user_options[PLAYER_OPTION_CURRENCY_DEFAULT] = $player_currency : false;
29
30
//// Конвертация ММ в ТМ
0 ignored issues
show
Unused Code Comprehensibility introduced by
56% of this comment could be valid code. Did you maybe forget this after debugging?

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

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

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

Loading history...
31
//if(sys_get_param('mm_convert_do')) {
32
//  try {
33
//    if(!($mm_convert = sys_get_param_id('mm_convert'))) {
34
//      throw new exception($lang['pay_msg_mm_convert_wrong_amount'], ERR_ERROR);
35
//    }
36
//
37
//    sn_db_transaction_start();
38
//    $user = db_user_by_id($user['id'], true);
39
//    if($mm_convert > mrc_get_level($user, null, RES_METAMATTER)) {
40
//      throw new exception($lang['pay_msg_mm_convert_not_enough'], ERR_ERROR);
41
//    }
42
//
43
//    $payment_comment = sprintf("Игрок сконвертировал %d Метаматерии в Тёмную Материю", $mm_convert);
44
//    if(!mm_points_change($user['id'], RPG_CONVERT_MM, -$mm_convert, $payment_comment)) {
45
//      throw new exception($lang['pay_msg_mm_convert_mm_error'], ERR_ERROR);
46
//    }
47
//    if(!rpg_points_change($user['id'], RPG_CONVERT_MM, $mm_convert, $payment_comment)) {
48
//      throw new exception($lang['pay_msg_mm_convert_dm_error'], ERR_ERROR);
49
//    }
50
//
51
//    $template->assign_block_vars('result', array(
52
//      'STATUS'  => ERR_NONE,
53
//      'MESSAGE' => sprintf('Конвертация %1$s единиц Метаматерии в %1$s единиц Тёмной Материи успешно произведена', pretty_number($mm_convert)),
54
//    ));
55
//
56
//    sn_db_transaction_commit();
57
//  } catch(exception $e) {
58
//    sn_db_transaction_rollback();
59
//    $template->assign_block_vars('result', $response = array(
60
//      'STATUS'  => $e->getCode(),
61
//      'MESSAGE' => $e->getMessage(),
62
//    ));
63
//  }
64
//}
65
66
// Таблица скидок
67
$prev_discount = 0;
68
if(isset(sn_module_payment::$bonus_table) && is_array(sn_module_payment::$bonus_table)) {
69
  foreach(sn_module_payment::$bonus_table as $sum => $discount) {
70
    if($discount && $discount != $prev_discount) {
71
      $template->assign_block_vars('discount', array(
72
        'SUM' => $sum,
73
        'DISCOUNT' => $discount * 100,
74
        'DISCOUNT_ONE' => 1 + $discount,
75
        'TEXT' => sprintf(classSupernova::$lang['pay_mm_bonus_each'], HelperString::numberFloorAndFormat($sum), round($discount * 100)),
76
      ));
77
      $prev_discount = $discount;
78
    }
79
  }
80
}
81
82
// Результат платежа
83
if($payment_id = sys_get_param_id('payment_id')) {
84
  $payment = doquery("SELECT * FROM {{payment}} WHERE `payment_id` = {$payment_id} LIMIT 1;", true);
85
  if($payment && $payment['payment_user_id'] == $user['id']) {
86 View Code Duplication
    if($payment['payment_status'] == PAYMENT_STATUS_COMPLETE) {
0 ignored issues
show
This code seems to be duplicated across your project.

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

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

Loading history...
87
      $template->assign_block_vars('result', array('MESSAGE' => sprintf(classSupernova::$lang['pay_msg_mm_purchase_complete'], $payment['payment_dark_matter_paid'], $payment['payment_module_name'], $payment['payment_dark_matter_gained'])));
88
    }
89 View Code Duplication
    if($payment['payment_status'] == PAYMENT_STATUS_NONE) {
0 ignored issues
show
This code seems to be duplicated across your project.

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

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

Loading history...
90
      $template->assign_block_vars('result', array(
91
        'MESSAGE' => sprintf(classSupernova::$lang['pay_msg_mm_purchase_incomplete'], $payment['payment_dark_matter_paid'], $payment['payment_module_name']),
92
        'STATUS' => 1,
93
      ));
94
    }
95
    if($payment['payment_test']) {
96
      $template->assign_block_vars('result', array(
97
        'MESSAGE' => sprintf(classSupernova::$lang['pay_msg_mm_purchase_test']),
98
        'STATUS' => -1,
99
      ));
100
    }
101
  }
102
}
103
104
$unit_available_amount_list = &sn_module_payment::$bonus_table;
105
106
$request = array(
107
  'metamatter' => sys_get_param_float('metamatter'),
108
);
109
110
if(!$request['metamatter']) {
111
  unset($_POST);
112
}
113
114
$payment_methods_available = array_combine(array_keys(sn_module_payment::$payment_methods), array_fill(0, count(sn_module_payment::$payment_methods), null));
115
array_walk($payment_methods_available, function(&$value, $index) {
116
  $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;
117
});
118
119
$payment_module_valid = false;
120
$payment_module = sys_get_param_str('payment_module');
121
foreach($sn_module_list['payment'] as $module_name => $module) {
122
  if(!is_object($module) || !$module->manifest['active']) {
123
    continue;
124
  }
125
126
  lng_include($module_name, $module->manifest['root_relative']);
127
128
  foreach(sn_module_payment::$payment_methods as $payment_type_id => $available_methods) {
129
    foreach($available_methods as $payment_method => $payment_currency) {
130
      if(isset($module->manifest['payment_method'][$payment_method])) {
131
        $payment_methods_available[$payment_type_id][$payment_method][$module_name] = $module->manifest['payment_method'][$payment_method];
132
      }
133
    }
134
  }
135
136
  $payment_module_valid = $payment_module_valid || $module_name == $payment_module;
137
}
138
139
global $template_result;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
140
// Доступные платежные методы
141
foreach($payment_methods_available as $payment_type_id => $payment_methods) {
142
  if(empty($payment_methods)) continue;
143
144
  $template_result['.']['payment'][$payment_type_id] =array(
145
    'ID' => $payment_type_id,
146
    'NAME' => classSupernova::$lang['pay_methods'][$payment_type_id],
147
  );
148
  foreach($payment_methods as $payment_method_id => $module_list) {
149
    if(empty($module_list)) {
150
      continue;
151
    }
152
    $template_result['.']['payment'][$payment_type_id]['.']['method'][$payment_method_id] = array(
153
      'ID'         => $payment_method_id,
154
      'NAME'       => classSupernova::$lang['pay_methods'][$payment_method_id],
155
      'IMAGE'      => isset(sn_module_payment::$payment_methods[$payment_type_id][$payment_method_id]['image'])
156
        ? sn_module_payment::$payment_methods[$payment_type_id][$payment_method_id]['image'] : '',
157
      'NAME_FORCE' => isset(sn_module_payment::$payment_methods[$payment_type_id][$payment_method_id]['name']),
158
      'BUTTON'     => isset(sn_module_payment::$payment_methods[$payment_type_id][$payment_method_id]['button']),
159
    );
160
    foreach($module_list as $payment_module_name => $payment_module_method_details) {
161
      $template_result['.']['payment'][$payment_type_id]['.']['method'][$payment_method_id]['.']['module'][] = array(
162
        'MODULE' => $payment_module_name,
163
      );
164
    }
165
  }
166
167
  if(empty($template_result['.']['payment'][$payment_type_id]['.'])) {
168
    unset($template_result['.']['payment'][$payment_type_id]);
169
  }
170
}
171
172
$template->assign_recursive($template_result);
173
174
$payment_type_selected = sys_get_param_int('payment_type');
175
$payment_method_selected = sys_get_param_int('payment_method');
176
177
$payment_module_valid = $payment_module_valid && (!$payment_method_selected || isset($payment_methods_available[$payment_type_selected][$payment_method_selected][$module_name]));
178
179
// If payment_module invalid - making it empty OR if there is only one payment_module - selecting it
180
if($payment_module_valid) {
0 ignored issues
show
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
181
  // $payment_module = $payment_module; // Really - do nothing
0 ignored issues
show
Unused Code Comprehensibility introduced by
38% of this comment could be valid code. Did you maybe forget this after debugging?

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

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

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

Loading history...
182
} elseif($payment_type_selected && count($payment_methods_available[$payment_type_selected][$payment_method_selected]) == 1) {
183
  reset($payment_methods_available[$payment_type_selected][$payment_method_selected]);
184
  $payment_module = key($payment_methods_available[$payment_type_selected][$payment_method_selected]);
185
} elseif(count($sn_module_list['payment']) == 1) {
186
  $payment_module = $module_name;
187
} else {
188
  $payment_module = '';
189
}
190
191
if($payment_type_selected && $payment_method_selected) {
192
  foreach($payment_methods_available[$payment_type_selected][$payment_method_selected] as $module_name => $temp) {
193
    $template->assign_block_vars('payment_module', array(
194
      'ID' => $module_name,
195
      'NAME' => classSupernova::$lang["module_{$module_name}_name"],
196
      'DESCRIPTION' => classSupernova::$lang["module_{$module_name}_description"],
197
    ));
198
  }
199
}
200
201
foreach(classSupernova::$lang['pay_currency_list'] as $key => $value) {
202
  $course = get_exchange_rate($key);
203
  if(!$course) {
204
    continue;
205
  }
206
  $template->assign_block_vars('exchange', array(
207
    'SYMBOL' => $key,
208
    'TEXT' => $value,
209
    'COURSE_DIRECT' => HelperString::numberFormat($course, 4),
210
    'COURSE_REVERSE' => HelperString::numberFormat(1 / $course, 4),
211
    'MM_PER_CURRENCY' => HelperString::numberFormat(sn_module_payment::currency_convert(1, $key, 'MM_'), 2),
212
    'LOT_PRICE' => sn_module_payment::currency_convert(get_mm_cost(), 'MM_', $key),
213
    'DEFAULT' => $key == classSupernova::$config->payment_currency_default,
214
  ));
215
}
216
217
if($request['metamatter'] && $payment_module) {
218
  try {
219
    // Any possible errors about generating paylink should be raised in module!
220
    $pay_link = $sn_module[$payment_module]->compile_request($request);
221
222
    // Поддержка дополнительной информации
223
    if(is_array($pay_link['RENDER'])) {
224
      foreach($pay_link['RENDER'] as $html_data) {
225
        $template->assign_block_vars('render', $html_data);
226 View Code Duplication
        if(isset($html_data['VALUE']) && is_array($html_data['VALUE'])) {
0 ignored issues
show
This code seems to be duplicated across your project.

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

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

Loading history...
227
          foreach($html_data['VALUE'] as $value_id => $value_value) {
228
            $template->assign_block_vars('render.value', array(
229
              'FIELD' => $value_id,
230
              'VALUE' => $value_value,
231
            ));
232
          }
233
        }
234
      }
235
    }
236
237
    // Поддержка передачи данных для многошаговых платежных систем
238 View Code Duplication
    if(is_array($pay_link['DATA'])) {
0 ignored issues
show
This code seems to be duplicated across your project.

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

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

Loading history...
239
      foreach($pay_link['DATA'] as $key => $value) {
240
        $template->assign_block_vars('pay_link_data', array(
241
          'FIELD' => $key,
242
          'VALUE' => $value,
243
        ));
244
      }
245
    }
246
247
    if(is_array($pay_link) && in_array($pay_link['PAY_LINK_METHOD'], array('POST', 'GET', 'LINK', 'STEP'))) {
248
      // TODO Переделать это под assign_vars_recursive и возвращать пустые строки если нет платежного метода - для унификации формы в темплейте
249
      $template->assign_vars(array(
250
        'PAY_LINK_METHOD' => $pay_link['PAY_LINK_METHOD'],
251
        'PAY_LINK_URL' => $pay_link['PAY_LINK_URL'],
252
      ));
253
    } else {
254
      throw new exception(classSupernova::$lang['pay_msg_request_paylink_unsupported'], ERR_ERROR);
255
    }
256
  } catch(exception $e) {
257
    $template->assign_block_vars('result', $response = array(
258
      'STATUS'  => $e->getCode(),
259
      'MESSAGE' => $e->getMessage(),
260
    ));
261
    $debug->warning('Результат операции: код ' . $e->getCode() . ' сообщение "' . $e->getMessage() . '"', 'Ошибка платежа', LOG_INFO_PAYMENT);
262
  }
263
}
264
265
// Прегенерированные пакеты
266
foreach($unit_available_amount_list as $unit_amount => $discount) {
267
  $temp = sn_module_payment::currency_convert($unit_amount, 'MM_', $player_currency);
268
  $template->assign_block_vars('mm_amount', array(
269
    'VALUE' => $unit_amount,
270
    // 'PRICE' => $temp,
0 ignored issues
show
Unused Code Comprehensibility introduced by
58% of this comment could be valid code. Did you maybe forget this after debugging?

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

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

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

Loading history...
271
    'PRICE_TEXT' => HelperString::numberFormat($temp, 2),
272
    'CURRENCY' => $player_currency,
273
    'DISCOUNT' => $discount,
274
    'DISCOUNT_PERCENT' => $discount * 100,
275
    'DISCOUNTED' => $unit_amount * (1 + $discount),
276
    'TEXT' => HelperString::numberFloorAndFormat($unit_amount),
277
    'TEXT_DISCOUNTED' => HelperString::numberFloorAndFormat($unit_amount * (1 + $discount)),
278
  ));
279
}
280
281
$currency = $payment_module ? sn_module_payment::$payment_methods[$payment_type_selected][$payment_method_selected]['currency'] : '';
282
$bonus_percent = round(sn_module_payment::bonus_calculate($request['metamatter'], true, true) * 100);
283
$income_metamatter_text = prettyNumberStyledDefault(sn_module_payment::bonus_calculate($request['metamatter']));
284
285
$template->assign_vars(array(
286
  'PAGE_HEADER' => classSupernova::$lang['sys_metamatter'],
287
288
  'URL_PURCHASE' => classSupernova::$config->url_purchase_metamatter,
0 ignored issues
show
Bug Best Practice introduced by
The property url_purchase_metamatter does not exist on classConfig. Since you implemented __get, consider adding a @property annotation.
Loading history...
289
290
  'PAYMENT_TYPE' => $payment_type_selected,
291
  'PAYMENT_METHOD' => $payment_method_selected,
292
  'PAYMENT_METHOD_NAME' => classSupernova::$lang['pay_methods'][$payment_method_selected],
293
294
  'PAYMENT_MODULE' => $payment_module,
295
  'PAYMENT_MODULE_NAME' => classSupernova::$lang["module_{$payment_module}_name"],
296
  'PAYMENT_MODULE_DESCRIPTION' => classSupernova::$lang["module_{$payment_module}_description"],
297
298
  'PLAYER_CURRENCY' => $player_currency,
299
  'PLAYER_CURRENCY_PRICE_PER_MM' => sn_module_payment::currency_convert(1, $player_currency, 'MM_', 10),
300
301
  'UNIT_AMOUNT' => (float)$request['metamatter'],
302
  'UNIT_AMOUNT_TEXT' => HelperString::numberFloorAndFormat($request['metamatter']),
303
  'UNIT_AMOUNT_BONUS_PERCENT' => $bonus_percent,
304
  'UNIT_AMOUNT_TEXT_DISCOUNTED' => $income_metamatter_text,
305
  'UNIT_AMOUNT_TEXT_COST_BASE' => HelperString::numberFormat(sn_module_payment::currency_convert($request['metamatter'], 'MM_', $player_currency), 2),
306
307
  'PAYMENT_CURRENCY_EXCHANGE_DEFAULT' => prettyNumberStyledDefault(get_mm_cost()),
308
  'PAYMENT_CURRENCY_DEFAULT_TEXT' => classSupernova::$lang['pay_currency_list'][classSupernova::$config->payment_currency_default],
309
310
  'METAMATTER' => mrc_get_level($user, '', RES_METAMATTER),
0 ignored issues
show
'' of type string is incompatible with the type array expected by parameter $planet of mrc_get_level(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

310
  'METAMATTER' => mrc_get_level($user, /** @scrutinizer ignore-type */ '', RES_METAMATTER),
Loading history...
311
312
  'METAMATTER_COST_TEXT' => sprintf(classSupernova::$lang['pay_mm_buy_conversion_cost'],
313
    prettyNumberStyledDefault($request['metamatter']),
314
    number_format($mmWish = sn_module_payment::currency_convert($request['metamatter'], 'MM_', $currency), 2, ',', '.'),
315
    $currency,
316
    prettyNumberGetClass($mmWish, true)),
317
  'METAMATTER_COST_BONUS_TEXT' => $bonus_percent
318
    ? sprintf(classSupernova::$lang['pay_mm_buy_real_income'], prettyNumberStyledDefault($bonus_percent), $income_metamatter_text)
319
    : '',
320
321
  'DARK_MATTER_DESCRIPTION' => classSupernova::$lang['info'][RES_DARK_MATTER]['description'],
322
323
  'PAYMENT_AVAILABLE' => sn_module::sn_module_get_active_count('payment') && !defined('SN_GOOGLE'),
324
325
));
326
327
display($template, classSupernova::$lang['sys_metamatter']);
328