Completed
Push — work-fleets ( 2bd11a...17dd3b )
by SuperNova.WS
06:36
created

includes/classes/Account.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
/**
4
 * Created by Gorlum 24.08.2015 6:00
5
 */
6
class Account {
7
  /**
8
   * @var int
9
   */
10
  public $account_id = 0;
11
  /**
12
   * @var string
13
   */
14
  public $account_name = '';
15
  /**
16
   * @var string
17
   */
18
  public $account_password = '';
19
  /**
20
   * @var string
21
   */
22
  public $account_salt = '';
23
  /**
24
   * @var string
25
   */
26
  public $account_email = '';
27
  /**
28
   * @var int
29
   */
30
  public $account_email_verified = 0;
31
  /**
32
   * @var string
33
   */
34
  public $account_register_time = '';
35
  /**
36
   * @var string
37
   */
38
  public $account_language = '';
39
40
  public $account_metamatter = 0;
41
  public $account_metamatter_total = 0;
42
43
  /**
44
   * @var int
45
   */
46
  public $is_exists = 0;
47
  /**
48
   * @var int
49
   */
50
  public $is_loaded = 0;
51
52
  /**
53
   * @var db_mysql
54
   */
55
  public $db;
56
57
  protected $table_check = array(
58
    'account'        => 'account',
59
    'log_metamatter' => 'log_metamatter',
60
  );
61
62
  public function reset() {
63
    $this->account_id = 0;
64
    $this->account_name = '';
65
    $this->account_password = '';
66
    $this->account_salt = '';
67
    $this->account_email = '';
68
    $this->account_email_verified = 0;
69
    $this->account_register_time = '';
70
    $this->account_language = '';
71
72
    $this->is_exists = 0;
73
    $this->is_loaded = 0;
74
  }
75
76
  public function __construct($db = null) {
77
    $this->reset();
78
    $this->db = is_object($db) ? $db : classSupernova::$db;
79
80
    foreach($this->table_check as $table_name) {
81
      if(empty($this->db->table_list[$table_name])) {
82
        die('Если вы видите это сообщение первый раз после обновления релиза - просто перегрузите страницу.<br />
83
              В противном случае - сообщите Администрации сервера об ошибке.<br/>
84
              Не хватает таблицы для работы системы авторизации: ' . $table_name);
85
      }
86
    }
87
  }
88
89
  // OK 4.5
90
  public function password_check($password_unsafe) {
91
    return $this->password_encode($password_unsafe, $this->account_salt) == $this->account_password;
92
  }
93
94
  /**
95
   * Меняет пароль у аккаунта в БД
96
   *
97
   * @param      $old_password_unsafe
98
   * @param      $new_password_unsafe
99
   * @param null $salt_unsafe
100
   *
101
   * @return bool
102
   */
103
  // OK v4.6
104
  public function password_change($old_password_unsafe, $new_password_unsafe, $salt_unsafe = null) {
105
    if(!$this->password_check($old_password_unsafe)) {
106
      return false;
107
    }
108
109
    $salt_unsafe === null ? $salt_unsafe = $this->password_salt_generate() : false;
110
    $result = $this->db_set_password($new_password_unsafe, $salt_unsafe);
111
112
    return $result;
113
  }
114
115
116
  /**
117
   * Заполняет поля объекта значениями результата запроса
118
   *
119
   * @param array $row
120
   *
121
   * @return bool
122
   */
123
  // OK v4.5
124
  public function assign_from_db_row($row) {
125
    $this->reset();
126
    if(empty($row) || !is_array($row)) {
127
      return false;
128
    }
129
    $this->account_id = $row['account_id'];
130
    $this->account_name = $row['account_name'];
131
    $this->account_password = $row['account_password'];
132
    $this->account_salt = $row['account_salt'];
133
    $this->account_email = $row['account_email'];
134
    $this->account_email_verified = $row['account_email_verified'];
135
    $this->account_register_time = $row['account_register_time'];
136
    $this->account_language = $row['account_language'];
137
138
    $this->account_metamatter = $row['account_metamatter'];
139
    $this->account_metamatter_total = $row['account_metamatter_total'];
140
141
    $this->is_exists = 1;
142
    $this->is_loaded = 1;
143
144
    return true;
145
  }
146
147
  /**
148
   * Возвращает аккаунт по его ID
149
   *
150
   * @param $account_id_unsafe
151
   *
152
   * @return bool
153
   */
154
  // OK v4.5
155
  public function db_get_by_id($account_id_unsafe) {
156
    $this->reset();
157
158
    $account_id_safe = round(floatval($account_id_unsafe));
159
160
    $account_row = $this->db->doSelectFetch("SELECT * FROM {{account}} WHERE `account_id` = {$account_id_safe}");
161
162
    return $this->assign_from_db_row($account_row);
163
  }
164
  /**
165
   * Возвращает аккаунт по имени
166
   *
167
   * @param string $account_name_safe
168
   *
169
   * @return bool
170
   */
171
  // OK v4.5
172
  public function db_get_by_name($account_name_unsafe) {
173
    $this->reset();
174
175
    $account_name_safe = $this->db->db_escape($account_name_unsafe);
176
177
    $account_row = $this->db->doSelectFetch("SELECT * FROM {{account}} WHERE LOWER(`account_name`) = LOWER('{$account_name_safe}') FOR UPDATE");
178
179
    return $this->assign_from_db_row($account_row);
180
  }
181
  /**
182
   * Возвращает аккаунт по емейлу
183
   *
184
   * @param string $email_unsafe
185
   *
186
   * @return bool
187
   */
188
  // OK v4.5
189
  public function db_get_by_email($email_unsafe) {
190
    $this->reset();
191
192
    $email_safe = $this->db->db_escape($email_unsafe);
193
194
    $account_row = $this->db->doSelectFetch("SELECT * FROM {{account}} WHERE LOWER(`account_email`) = LOWER('{$email_safe}') FOR UPDATE;");
195
196
    return $this->assign_from_db_row($account_row);
197
  }
198
  /**
199
   * Возвращает аккаунт по имени или аккаунту - проверка уникальных значений
200
   *
201
   * @param string $account_name_unsafe
202
   * @param string $email_unsafe
203
   *
204
   * @return bool
205
   *
206
   */
207
  // OK v4.5
208 View Code Duplication
  public function db_get_by_name_or_email($account_name_unsafe, $email_unsafe) {
0 ignored issues
show
This method seems to be duplicated in your project.

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

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

Loading history...
209
    $this->reset();
210
211
    $account_name_safe = $this->db->db_escape($account_name_unsafe);
212
    $email_safe = $this->db->db_escape($email_unsafe);
213
214
    $account = $this->db->doSelectFetch(
215
      "SELECT * 
216
      FROM {{account}} 
217
      WHERE 
218
        LOWER(`account_name`) = LOWER('{$account_name_safe}') 
219
        OR 
220
        LOWER(`account_name`) = LOWER('{$email_safe}') 
221
        OR 
222
        LOWER(`account_email`) = LOWER('{$email_safe}') 
223
      FOR UPDATE"
224
    );
225
226
    return $this->assign_from_db_row($account);
227
  }
228
  /**
229
   * Создает аккаунт
230
   *
231
   * @throws Exception
232
   */
233
  // OK v4.5
234
  public function db_create($account_name_unsafe, $password_raw, $email_unsafe, $language_unsafe = null, $salt_unsafe = null) {
235
    $this->reset();
236
237
    $account_name_safe = $this->db->db_escape($account_name_unsafe);
238
    $email_safe = $this->db->db_escape($email_unsafe);
239
    $language_safe = $this->db->db_escape($language_unsafe === null ? DEFAULT_LANG : $language_unsafe);
240
241
    $salt_unsafe === null ? $salt_unsafe = $this->password_salt_generate() : false;
242
    $password_salted_safe = $this->db->db_escape($this->password_encode($password_raw, $salt_unsafe));
243
    $salt_safe = $this->db->db_escape($salt_unsafe);
244
245
    $result = $this->db->doInsert(
246
      "INSERT INTO {{account}} SET
247
        `account_name` = '{$account_name_safe}',
248
        `account_password` = '{$password_salted_safe}',
249
        `account_salt` = '{$salt_safe}',
250
        `account_email` = LOWER('{$email_safe}'),
251
        `account_language` = '{$language_safe}'"
252
    );
253
    if(!$result) {
254
      throw new Exception(REGISTER_ERROR_ACCOUNT_CREATE, ERR_ERROR);
255
    }
256
257
    if(!($account_id = $this->db->db_insert_id())) {
258
      throw new Exception(REGISTER_ERROR_ACCOUNT_CREATE, ERR_ERROR);
259
    }
260
261
    return $this->db_get_by_id($account_id);
262
  }
263
264
  /**
265
   * Физически меняет пароль аккаунта в БД
266
   *
267
   * @param string $password_unsafe
268
   * @param string $salt_unsafe
269
   *
270
   * @return bool
271
   */
272
  // OK v4.5
273
  public function db_set_password($password_unsafe, $salt_unsafe) {
274
    $password_encoded_unsafe = $this->password_encode($password_unsafe, $salt_unsafe);
275
    $password_encoded_safe = $this->db->db_escape($password_encoded_unsafe);
276
277
    $account_id_safe = $this->db->db_escape($this->account_id);
278
    $salt_safe = $this->db->db_escape($salt_unsafe);
279
280
    $result = $this->db->doUpdate(
281
      "UPDATE {{account}} SET
282
        `account_password` = '{$password_encoded_safe}',
283
        `account_salt` = '{$salt_safe}'
284
      WHERE `account_id` = '{$account_id_safe}'"
285
    ) ? true : false;
286
287
    if($result) {
288
      $result = $this->db_get_by_id($this->account_id);
289
    }
290
291
    return $result;
292
  }
293
294
295
296
  /**
297
   * Просаливает пароль
298
   *
299
   * @param $password
300
   * @param $salt
301
   *
302
   * @return string
303
   */
304
  // OK v4.5
305
  protected function password_encode($password, $salt) {
306
    return core_auth::password_encode($password, $salt);
307
  }
308
  /**
309
   * Генерирует соль
310
   *
311
   * @return string
312
   */
313
  // OK v4.5
314
  protected function password_salt_generate() {
315
    return core_auth::password_salt_generate();
316
  }
317
318
  /**
319
   * Вставляет запись об изменении количества ММ в лог ММ
320
   *
321
   * @param $comment
322
   * @param $change_type
323
   * @param $metamatter
324
   *
325
   * @return int|string
326
   */
327
  // OK 4.8
328
  protected function db_mm_log_insert($comment, $change_type, $metamatter, $user_id_unsafe) {
329
    $provider_id_safe = intval(core_auth::$main_provider->provider_id);
330
    //$account_id_safe = $this->db->db_escape($this->account_id);
331
    $account_id_safe = intval($this->account_id);
332
    $account_name_safe = $this->db->db_escape($this->account_name);
333
334
    // $user_id_safe = $this->db->db_escape(core_auth::$user['id']);
335
    // $user_id_safe = intval(core_auth::$user['id']);
336
    $user_id_safe = intval($user_id_unsafe);
337
    $username_safe = !empty(core_auth::$user['username']) ? $this->db->db_escape(core_auth::$user['username']) : '';
338
339
    $metamatter = round(floatval($metamatter));
340
341
    $comment_safe = $this->db->db_escape($comment);
342
343
    $server_name_safe = $this->db->db_escape(SN_ROOT_VIRTUAL);
344
    $page_url_safe = $this->db->db_escape($_SERVER['SCRIPT_NAME']);
345
346
    $this->db->doInsert("INSERT INTO {{log_metamatter}} SET
347
        `provider_id` = {$provider_id_safe},
348
        `account_id` = {$account_id_safe},
349
        `account_name` = '{$account_name_safe}',
350
        `user_id` = {$user_id_safe},
351
        `username` = '{$username_safe}',
352
        `reason` = {$change_type},
353
        `amount` = {$metamatter},
354
        `comment` = '{$comment_safe}',
355
        `server_name` = '{$server_name_safe}',
356
        `page` = '{$page_url_safe}'
357
      ;");
358
    $result = $this->db->db_insert_id();
359
360
    return $result;
361
  }
362
363
  /**
364
   * @param int    $change_type
365
   * @param int    $metamatter
366
   * @param string $comment
367
   * @param bool   $already_changed
368
   *
369
   * @return array|bool|int|mysqli_result|null|string
370
   */
371
  public function metamatter_change($change_type, $metamatter, $comment = '', $already_changed = false) {
372
    global $mm_change_legit;
373
374
    if(!$this->is_exists || !($metamatter = round(floatval($metamatter)))) {
375
      classSupernova::$debug->error('Ошибка при попытке манипуляции с ММ');
376
377
      return false;
378
    }
379
380
    $account_id_safe = $this->db->db_escape($this->account_id);
381
382
    $mm_change_legit = true;
383
    // $sn_data_metamatter_db_name = pname_resource_name(RES_METAMATTER);
384
    if($already_changed) {
385
      $metamatter_total_delta = 0;
386
      $result = -1;
387
    } else {
388
      $metamatter_total_delta = $metamatter > 0 ? $metamatter : 0;
389
390
      $classConfig = classSupernova::$config;
391
      $result = $this->db->doUpdate(
392
        "UPDATE {{account}}
393
        SET
394
          `account_metamatter` = `account_metamatter` + '{$metamatter}'" .
395
        ($metamatter_total_delta ? ", `account_immortal` = IF(`account_metamatter_total` + '{$metamatter_total_delta}' >= {$classConfig->player_metamatter_immortal}, NOW(), `account_immortal`), `account_metamatter_total` = `account_metamatter_total` + '{$metamatter_total_delta}'" : '') .
396
        " WHERE `account_id` = {$account_id_safe}"
397
      );
398
      if(!$result) {
399
        classSupernova::$debug->error("Error adjusting Metamatter for player ID {$this->account_id} (Player Not Found?) with {$metamatter}. Reason: {$comment}", 'Metamatter Change', 402);
400
      }
401
      $result = classSupernova::$db->db_affected_rows();
402
    }
403
404
    if(empty(core_auth::$user['id'])) {
405
      $user_list = PlayerToAccountTranslate::db_translate_get_users_from_account_list(core_auth::$main_provider->provider_id, $this->account_id);
406
      reset($user_list);
407
      $user_id_unsafe = key($user_list);
408
    } else {
409
      $user_id_unsafe = core_auth::$user['id'];
410
    }
411
    $user_id_safe = $this->db->db_escape($user_id_unsafe);
412
413
    if(!$result) {
414
      classSupernova::$debug->error("Error adjusting Metamatter for player ID {$this->account_id} (Player Not Found?) with {$metamatter}. Reason: {$comment}", 'Metamatter Change', 402);
415
    }
416
417
    if(!$already_changed) {
418
      $this->account_metamatter += $metamatter;
419
      $this->account_metamatter_total += $metamatter_total_delta;
420
    }
421
422
    if(is_array($comment)) {
423
      $comment = call_user_func_array('sprintf', $comment);
424
    }
425
426
    $result = $this->db_mm_log_insert($comment, $change_type, $metamatter, $user_id_unsafe);
427
428
    if($metamatter > 0 && !empty($user_id_safe)) {
429
      $old_referral = db_referral_get_by_id($user_id_safe);
430 View Code Duplication
      if($old_referral['id']) {
431
        $dark_matter_from_metamatter = $metamatter * AFFILIATE_MM_TO_REFERRAL_DM;
432
        db_referral_update_dm($user_id_safe, $dark_matter_from_metamatter);
433
        $new_referral = db_referral_get_by_id($user_id_safe);
434
435
        $partner_bonus = floor($new_referral['dark_matter'] / classSupernova::$config->rpg_bonus_divisor) - ($old_referral['dark_matter'] >= classSupernova::$config->rpg_bonus_minimum ? floor($old_referral['dark_matter'] / classSupernova::$config->rpg_bonus_divisor) : 0);
436
        if($partner_bonus > 0 && $new_referral['dark_matter'] >= classSupernova::$config->rpg_bonus_minimum) {
437
          rpg_points_change($new_referral['id_partner'], RPG_REFERRAL_BOUGHT_MM, $partner_bonus, "Incoming MM From Referral ID {$user_id_safe}");
438
        }
439
      }
440
    }
441
442
    $mm_change_legit = false;
443
444
    return $result;
445
  }
446
447
448
  // ------ UNUSED -----------------------------------------------------------------------------------------------------
449
450
}
451