Completed
Branch master (ab4e85)
by SuperNova.WS
06:22
created
includes/classes/sn_module_payment.php 2 patches
Doc Comments   +7 added lines, -1 removed lines patch added patch discarded remove patch
@@ -702,7 +702,7 @@  discard block
 block discarded – undo
702 702
    * Рассчёт бонуса ММ
703 703
    *
704 704
    * @param            $dark_matter
705
-   * @param bool|true  $direct
705
+   * @param boolean  $direct
706 706
    * @param bool|false $return_bonus
707 707
    *
708 708
    * @return float|int
@@ -738,6 +738,12 @@  discard block
 block discarded – undo
738 738
 
739 739
   // Дополнительная ре-трансляция адреса, если в каком-то случае платежная система ожидает нелогичный ответ
740 740
   // Пример: иксолла при неправильно заданном пользователе в ордере ожидает НЕПРАВИЛЬНЫЙ_ОРДЕР, а не НЕПРАВИЛЬНЫЙ_ПОЛЬЗОВАТЕЛЬ
741
+
742
+  /**
743
+   * @param integer $error_code
744
+   *
745
+   * @return integer|null
746
+   */
741 747
   function retranslate_error($error_code, $options = array()) {
742 748
     return isset($options['retranslate_error'][$error_code]) ? $options['retranslate_error'][$error_code] : $error_code;
743 749
   }
Please login to merge, or discard this patch.
Spacing   +55 added lines, -55 removed lines patch added patch discarded remove patch
@@ -450,7 +450,7 @@  discard block
 block discarded – undo
450 450
   public function compile_request($request) {
451 451
     global $config, $lang, $user;
452 452
 
453
-    if(!(classSupernova::$auth->account instanceof Account)) {
453
+    if (!(classSupernova::$auth->account instanceof Account)) {
454 454
       // TODO - throw new Exception($lang['pay_msg_mm_request_amount_invalid'], SN_PAYMENT_REQUEST_ERROR_UNIT_AMOUNT);
455 455
     }
456 456
     $this->account = classSupernova::$auth->account;
@@ -471,15 +471,15 @@  discard block
 block discarded – undo
471 471
     $this->payment_currency = $config->payment_currency_default;
472 472
     $this->payment_amount = self::currency_convert($this->payment_dark_matter_paid, 'MM_', $this->payment_currency);
473 473
 
474
-    if(empty($this->payment_external_currency) && !empty($this->config['currency'])) {
474
+    if (empty($this->payment_external_currency) && !empty($this->config['currency'])) {
475 475
       $this->payment_external_currency = $this->config['currency'];
476 476
     }
477
-    if(empty($this->payment_external_currency)) {
477
+    if (empty($this->payment_external_currency)) {
478 478
       throw new Exception($lang['pay_error_internal_no_external_currency_set'], SN_PAYMENT_ERROR_INTERNAL_NO_EXTERNAL_CURRENCY_SET);
479 479
     }
480 480
 
481 481
     $this->payment_external_amount = self::currency_convert($this->payment_dark_matter_paid, 'MM_', $this->payment_external_currency);
482
-    if($this->payment_external_amount < 0.01) {
482
+    if ($this->payment_external_amount < 0.01) {
483 483
       throw new Exception($lang['pay_msg_mm_request_amount_invalid'], SN_PAYMENT_REQUEST_ERROR_UNIT_AMOUNT);
484 484
     }
485 485
 
@@ -488,7 +488,7 @@  discard block
 block discarded – undo
488 488
     $this->generate_description();
489 489
 
490 490
     $this->db_insert();
491
-    if(!$this->is_exists) {
491
+    if (!$this->is_exists) {
492 492
       throw new Exception($lang['pay_msg_request_error_db_payment_create'], SN_PAYMENT_REQUEST_DB_ERROR_PAYMENT_CREATE);
493 493
     }
494 494
   }
@@ -503,24 +503,24 @@  discard block
 block discarded – undo
503 503
   protected function payment_request_process($options = array()) {
504 504
     global $lang, $config;
505 505
 
506
-    if(!$this->manifest['active']) {
506
+    if (!$this->manifest['active']) {
507 507
       throw new Exception($lang['pay_msg_module_disabled'], SN_MODULE_DISABLED);
508 508
     }
509 509
 
510 510
     // Если есть payment_id - загружаем под него данные
511
-    if(!empty($this->payment_params['payment_id'])) {
511
+    if (!empty($this->payment_params['payment_id'])) {
512 512
       $this->request_payment_id = sys_get_param_id($this->payment_params['payment_id']);
513
-      if(!$this->request_payment_id) {
513
+      if (!$this->request_payment_id) {
514 514
         throw new Exception($lang['pay_msg_request_payment_id_invalid'], SN_PAYMENT_REQUEST_INTERNAL_ID_WRONG);
515 515
       }
516 516
 
517
-      if(!$this->db_get_by_id($this->request_payment_id)) {
517
+      if (!$this->db_get_by_id($this->request_payment_id)) {
518 518
         throw new Exception($lang['pay_msg_request_payment_id_invalid'], SN_PAYMENT_REQUEST_INTERNAL_ID_WRONG);
519 519
       }
520 520
 
521 521
       // Проверяем - был ли этот платеж обработан?
522 522
       // TODO - Статусы бывают разные. Нужен спецфлаг payment_processed
523
-      if($this->payment_status != PAYMENT_STATUS_NONE) {
523
+      if ($this->payment_status != PAYMENT_STATUS_NONE) {
524 524
         sn_db_transaction_rollback();
525 525
         sys_redirect(SN_ROOT_VIRTUAL . 'metamatter.php?payment_id=' . $this->payment_id);
526 526
         die();
@@ -530,89 +530,89 @@  discard block
 block discarded – undo
530 530
     // Пытаемся получить из запроса ИД аккаунта
531 531
     $request_account_id = !empty($this->payment_params['account_id']) ? sys_get_param_id($this->payment_params['account_id']) : 0;
532 532
     // Если в запросе нет ИД аккаунта - пытаемся использовать payment_account_id
533
-    if(empty($request_account_id) && !empty($this->payment_account_id)) {
533
+    if (empty($request_account_id) && !empty($this->payment_account_id)) {
534 534
       $request_account_id = $this->payment_account_id;
535 535
     }
536 536
     // Если теперь у нас нету ИД аккаунта ни в запросе, ни в записи таблицы - можно паниковать
537
-    if(empty($request_account_id)) {
537
+    if (empty($request_account_id)) {
538 538
       // TODO - аккаунт
539 539
       throw new Exception($lang['pay_msg_request_user_invalid'], $this->retranslate_error(SN_PAYMENT_REQUEST_USER_NOT_FOUND, $options));
540 540
     }
541 541
     // Если нет записи в таблице - тогда берем payment_account_id из запроса
542
-    if(empty($this->payment_account_id)) {
542
+    if (empty($this->payment_account_id)) {
543 543
       $this->payment_account_id = $request_account_id;
544 544
     }
545 545
     // Если у нас отличаются ИД аккаунта в запросе и ИД аккаунта в записи - тоже можно паниковать
546
-    if($this->payment_account_id != $request_account_id) {
546
+    if ($this->payment_account_id != $request_account_id) {
547 547
       // TODO - Поменять сообщение об ошибке
548 548
       throw new Exception($lang['pay_msg_request_user_invalid'], $this->retranslate_error(SN_PAYMENT_REQUEST_USER_NOT_FOUND, $options));
549 549
     }
550 550
     // Проверяем существование аккаунта с данным ИД
551
-    if(!$this->account->db_get_by_id($this->payment_account_id)) {
551
+    if (!$this->account->db_get_by_id($this->payment_account_id)) {
552 552
       throw new Exception($lang['pay_msg_request_user_invalid'] . ' ID ' . $this->payment_account_id, $this->retranslate_error(SN_PAYMENT_REQUEST_USER_NOT_FOUND, $options));
553 553
     }
554 554
 
555 555
     // TODO Проверка на сервер_ид - как бы и не нужна, наверное?
556
-    if(!empty($this->payment_params['server_id'])) {
556
+    if (!empty($this->payment_params['server_id'])) {
557 557
       $this->request_server_id = sys_get_param_str($this->payment_params['server_id']);
558
-      if(SN_ROOT_VIRTUAL != $this->request_server_id) {
558
+      if (SN_ROOT_VIRTUAL != $this->request_server_id) {
559 559
         throw new Exception($lang['pay_msg_request_server_wrong'] . " {$this->request_server_id} вместо " . SN_ROOT_VIRTUAL, SN_PAYMENT_REQUEST_SERVER_WRONG);
560 560
       }
561 561
     }
562 562
 
563 563
     // Сверка количества оплаченной ММ с учётом бонусов
564
-    if(!empty($this->payment_params['payment_dark_matter_gained'])) {
564
+    if (!empty($this->payment_params['payment_dark_matter_gained'])) {
565 565
       $request_mm_amount = sys_get_param_id($this->payment_params['payment_dark_matter_gained']);
566
-      if($request_mm_amount != $this->payment_dark_matter_gained && $this->is_loaded) {
566
+      if ($request_mm_amount != $this->payment_dark_matter_gained && $this->is_loaded) {
567 567
         throw new Exception($lang['pay_msg_mm_request_amount_invalid'] . " пришло {$request_mm_amount} ММ вместо {$this->payment_dark_matter_gained} ММ", SN_PAYMENT_REQUEST_MM_AMOUNT_INVALID);
568 568
       }
569 569
       empty($this->payment_dark_matter_gained) ? $this->payment_dark_matter_gained = $request_mm_amount : false;
570 570
     }
571
-    if(empty($this->payment_dark_matter_paid)) {
571
+    if (empty($this->payment_dark_matter_paid)) {
572 572
       // TODO - обратный расчёт из gained
573 573
     }
574 574
 
575 575
     // Проверка наличия внешнего ИД платежа
576
-    if(!empty($this->payment_params['payment_external_id'])) {
576
+    if (!empty($this->payment_params['payment_external_id'])) {
577 577
       $request_payment_external_id = sys_get_param_id($this->payment_params['payment_external_id']);
578
-      if(empty($request_payment_external_id)) {
578
+      if (empty($request_payment_external_id)) {
579 579
         throw new exception($lang['pay_msg_request_payment_id_invalid'], SN_PAYMENT_REQUEST_EXTERNAL_ID_WRONG);
580
-      } elseif(!empty($this->payment_external_id) && $this->payment_external_id != $request_payment_external_id) {
580
+      } elseif (!empty($this->payment_external_id) && $this->payment_external_id != $request_payment_external_id) {
581 581
         // TODO - Может быть поменять сообщение
582 582
         throw new exception($lang['pay_msg_request_payment_id_invalid'], SN_PAYMENT_REQUEST_EXTERNAL_ID_WRONG);
583 583
       }
584 584
       $this->payment_external_id = $request_payment_external_id;
585 585
     }
586 586
     // Сверка суммы, запрошенной СН к оплате
587
-    if(!empty($this->payment_params['payment_external_money'])) {
587
+    if (!empty($this->payment_params['payment_external_money'])) {
588 588
       $request_money_out = sys_get_param_float($this->payment_params['payment_external_money']);
589
-      if($request_money_out != $this->payment_external_amount && $this->is_loaded) {
589
+      if ($request_money_out != $this->payment_external_amount && $this->is_loaded) {
590 590
         throw new Exception($lang['pay_msg_request_payment_amount_invalid'] . " пришло {$request_money_out} денег вместо {$this->payment_external_amount} денег", SN_PAYMENT_REQUEST_CURRENCY_AMOUNT_INVALID);
591 591
       }
592 592
       empty($this->payment_external_amount) ? $this->payment_external_amount = $request_money_out : false;
593 593
     }
594 594
     // Заполняем поле валюты платёжной системы
595
-    if(!empty($this->payment_params['payment_external_currency'])) {
595
+    if (!empty($this->payment_params['payment_external_currency'])) {
596 596
       $this->payment_external_currency = sys_get_param_str($this->payment_params['payment_external_currency']);
597
-      if(empty($this->payment_external_currency)) {
597
+      if (empty($this->payment_external_currency)) {
598 598
         // TODO - поменять сообщение
599 599
         throw new Exception($lang['pay_msg_request_payment_amount_invalid'] . " {$this->payment_external_currency}", SN_PAYMENT_REQUEST_CURRENCY_AMOUNT_INVALID);
600 600
       }
601 601
     }
602
-    if(empty($this->payment_external_currency)) {
602
+    if (empty($this->payment_external_currency)) {
603 603
       $this->payment_external_currency = $this->config['currency'];
604 604
     }
605 605
 
606 606
     // Заполнение внутренней суммы и валюты из внешних данных
607
-    if(empty($this->payment_currency)) {
607
+    if (empty($this->payment_currency)) {
608 608
       $this->payment_currency = $config->payment_currency_default;
609 609
     }
610
-    if(empty($this->payment_amount) && !empty($this->payment_external_currency)) {
610
+    if (empty($this->payment_amount) && !empty($this->payment_external_currency)) {
611 611
       $this->payment_amount = self::currency_convert($this->payment_external_amount, $this->payment_external_currency, $this->payment_currency);
612 612
     }
613 613
 
614 614
     // TODO - Тестовый режим
615
-    if(!empty($this->payment_params['test'])) {
615
+    if (!empty($this->payment_params['test'])) {
616 616
       $this->payment_test = $this->config['test'] || sys_get_param_int($this->payment_params['test']);
617 617
     }
618 618
 
@@ -641,12 +641,12 @@  discard block
 block discarded – undo
641 641
     sn_db_transaction_start();
642 642
     try {
643 643
       $response = $this->payment_request_process();
644
-    } catch(Exception $e) {
644
+    } catch (Exception $e) {
645 645
       $response['result'] = $e->getCode();
646 646
       $response['message'] = $e->getMessage();
647 647
     }
648 648
 
649
-    if($response['result'] == SN_PAYMENT_REQUEST_OK) {
649
+    if ($response['result'] == SN_PAYMENT_REQUEST_OK) {
650 650
       sn_db_transaction_commit();
651 651
       $debug->warning('Результат операции: код ' . $response['result'] . ' сообщение "' . $response['message'] . '"', 'Успешный платёж', LOG_INFO_PAYMENT);
652 652
     } else {
@@ -655,7 +655,7 @@  discard block
 block discarded – undo
655 655
     }
656 656
 
657 657
     // Переводим код результата из СН в код платежной системы
658
-    if(is_array($this->result_translations) && !empty($this->result_translations)) {
658
+    if (is_array($this->result_translations) && !empty($this->result_translations)) {
659 659
       $response['result'] = isset($this->result_translations[$response['result']]) ? $this->result_translations[$response['result']] : $this->result_translations[SN_PAYMENT_REQUEST_UNDEFINED_ERROR];
660 660
     }
661 661
 
@@ -680,7 +680,7 @@  discard block
 block discarded – undo
680 680
     $currency_from = strtolower($currency_from);
681 681
     $currency_to = strtolower($currency_to);
682 682
 
683
-    if($currency_from != $currency_to) {
683
+    if ($currency_from != $currency_to) {
684 684
 //      $config_currency_from_name = 'payment_currency_exchange_' . $currency_from;
685 685
 //      $config_currency_to_name = 'payment_currency_exchange_' . $currency_to;
686 686
 
@@ -710,10 +710,10 @@  discard block
 block discarded – undo
710 710
   public static function bonus_calculate($dark_matter, $direct = true, $return_bonus = false) {
711 711
     $bonus = 0;
712 712
     $dark_matter_new = $dark_matter;
713
-    if(!empty(self::$bonus_table) && $dark_matter >= self::$bonus_table[0]) {
714
-      if($direct) {
715
-        foreach(self::$bonus_table as $dm_for_bonus => $multiplier) {
716
-          if($dm_for_bonus <= $dark_matter) {
713
+    if (!empty(self::$bonus_table) && $dark_matter >= self::$bonus_table[0]) {
714
+      if ($direct) {
715
+        foreach (self::$bonus_table as $dm_for_bonus => $multiplier) {
716
+          if ($dm_for_bonus <= $dark_matter) {
717 717
             $dark_matter_new = $dark_matter * (1 + $multiplier);
718 718
             $bonus = $multiplier;
719 719
           } else {
@@ -721,9 +721,9 @@  discard block
 block discarded – undo
721 721
           }
722 722
         }
723 723
       } else {
724
-        foreach(self::$bonus_table as $dm_for_bonus => $multiplier) {
724
+        foreach (self::$bonus_table as $dm_for_bonus => $multiplier) {
725 725
           $temp = $dm_for_bonus * (1 + $multiplier);
726
-          if($dark_matter >= $temp) {
726
+          if ($dark_matter >= $temp) {
727 727
             $dark_matter_new = round($dark_matter / (1 + $multiplier));
728 728
             $bonus = $multiplier;
729 729
           } else {
@@ -779,13 +779,13 @@  discard block
 block discarded – undo
779 779
     );
780 780
 
781 781
     $replace = false;
782
-    if($this->payment_id) {
782
+    if ($this->payment_id) {
783 783
       $payment['payment_id'] = $this->payment_id;
784 784
       $replace = true;
785 785
     }
786 786
 
787 787
     $query = array();
788
-    foreach($payment as $key => $value) {
788
+    foreach ($payment as $key => $value) {
789 789
       $value = is_string($value) ? '"' . db_escape($value) . '"' : $value;
790 790
       $query[] = "`{$key}` = {$value}";
791 791
     }
@@ -797,12 +797,12 @@  discard block
 block discarded – undo
797 797
 
798 798
 
799 799
   function payment_adjust_mm_new() {
800
-    if(!$this->payment_test) {
800
+    if (!$this->payment_test) {
801 801
       // Not a test payment. Adding DM to account
802 802
       $this->account = new Account($this->db);
803 803
       $this->account->db_get_by_id($this->payment_account_id);
804 804
       $result = $this->account->metamatter_change(RPG_PURCHASE, $this->payment_dark_matter_gained, $this->payment_comment);
805
-      if(!$result) {
805
+      if (!$result) {
806 806
         throw new Exception('Ошибка начисления ММ', SN_METAMATTER_ERROR_ADJUST);
807 807
       }
808 808
     }
@@ -812,25 +812,25 @@  discard block
 block discarded – undo
812 812
     die('{НЕ РАБОТАЕТ! СООБЩИТЕ АДМИНИСТРАЦИИ!}');
813 813
     global $lang;
814 814
 
815
-    if(!isset($payment['payment_status'])) {
815
+    if (!isset($payment['payment_status'])) {
816 816
       throw new exception($lang['pay_msg_request_payment_not_found'], SN_PAYMENT_REQUEST_ORDER_NOT_FOUND);
817 817
     }
818 818
 
819
-    if($payment['payment_status'] == PAYMENT_STATUS_COMPLETE) {
820
-      $safe_comment = db_escape($payment['payment_comment'] = $lang['pay_msg_request_payment_cancelled'] .' ' . $payment['payment_comment']);
819
+    if ($payment['payment_status'] == PAYMENT_STATUS_COMPLETE) {
820
+      $safe_comment = db_escape($payment['payment_comment'] = $lang['pay_msg_request_payment_cancelled'] . ' ' . $payment['payment_comment']);
821 821
 
822
-      if(!$payment['payment_test']) {
822
+      if (!$payment['payment_test']) {
823 823
         $result = $this->account->metamatter_change(RPG_PURCHASE_CANCEL, -$payment['payment_dark_matter_gained'], $payment['payment_comment']);
824
-        if(!$result) {
824
+        if (!$result) {
825 825
           throw new exception('Ошибка начисления ММ', SN_METAMATTER_ERROR_ADJUST);
826 826
         }
827 827
       }
828 828
       $payment['payment_status'] = PAYMENT_STATUS_CANCELED;
829 829
       doquery("UPDATE {{payment}} SET payment_status = {$payment['payment_status']}, payment_comment = '{$safe_comment}' WHERE payment_id = {$payment['payment_id']};");
830 830
       throw new exception($lang['pay_msg_request_payment_cancel_complete'], SN_PAYMENT_REQUEST_OK);
831
-    } elseif($payment['payment_status'] == PAYMENT_STATUS_CANCELED) {
831
+    } elseif ($payment['payment_status'] == PAYMENT_STATUS_CANCELED) {
832 832
       throw new exception($lang['pay_msg_request_payment_cancelled_already'], SN_PAYMENT_REQUEST_OK);
833
-    } elseif($payment['payment_status'] == PAYMENT_STATUS_NONE) {
833
+    } elseif ($payment['payment_status'] == PAYMENT_STATUS_NONE) {
834 834
       throw new exception($lang['pay_msg_request_payment_cancel_not_complete'], SN_PAYMENT_REQUEST_PAYMENT_NOT_COMPLETE);
835 835
     }
836 836
   }
@@ -844,8 +844,8 @@  discard block
 block discarded – undo
844 844
 
845 845
   protected function db_complete_payment() {
846 846
     // TODO - поле payment_processed
847
-    if($this->payment_status == PAYMENT_STATUS_NONE) {
848
-      if(!defined('PAYMENT_EXPIRE_TIME') || PAYMENT_EXPIRE_TIME == 0 || empty($this->payment_date) || strtotime($this->payment_date) + PAYMENT_EXPIRE_TIME <= SN_TIME_NOW) {
847
+    if ($this->payment_status == PAYMENT_STATUS_NONE) {
848
+      if (!defined('PAYMENT_EXPIRE_TIME') || PAYMENT_EXPIRE_TIME == 0 || empty($this->payment_date) || strtotime($this->payment_date) + PAYMENT_EXPIRE_TIME <= SN_TIME_NOW) {
849 849
         $this->payment_adjust_mm_new();
850 850
         $this->payment_status = PAYMENT_STATUS_COMPLETE;
851 851
       } else {
@@ -892,7 +892,7 @@  discard block
 block discarded – undo
892 892
   protected function db_assign_payment($payment = null) {
893 893
     $this->payment_reset();
894 894
 
895
-    if(is_array($payment) && isset($payment['payment_id'])) {
895
+    if (is_array($payment) && isset($payment['payment_id'])) {
896 896
       $this->payment_id = $payment['payment_id'];
897 897
       $this->payment_status = $payment['payment_status'];
898 898
       $this->payment_date = $payment['payment_date'];
Please login to merge, or discard this patch.
includes/classes/supernova.php 3 patches
Doc Comments   +5 added lines, -2 removed lines patch added patch discarded remove patch
@@ -323,7 +323,7 @@  discard block
 block discarded – undo
323 323
    *   <p>null - транзакция НЕ должна быть запущена</p>
324 324
    *   <p>true - транзакция должна быть запущена - для совместимости с $for_update</p>
325 325
    *   <p>false - всё равно - для совместимости с $for_update</p>
326
-   * @return bool Текущий статус транзакции
326
+   * @return null|boolean Текущий статус транзакции
327 327
    */
328 328
   public static function db_transaction_check($status = null) {
329 329
     $error_msg = false;
@@ -399,7 +399,7 @@  discard block
 block discarded – undo
399 399
   /**
400 400
    * Блокирует указанные таблицу/список таблиц
401 401
    *
402
-   * @param string|array $tables Таблица/список таблиц для блокировки. Названия таблиц - без префиксов
402
+   * @param string $tables Таблица/список таблиц для блокировки. Названия таблиц - без префиксов
403 403
    * <p>string - название таблицы для блокировки</p>
404 404
    * <p>array - массив, где ключ - имя таблицы, а значение - условия блокировки элементов</p>
405 405
    */
@@ -574,6 +574,9 @@  discard block
 block discarded – undo
574 574
     return $result;
575 575
   }
576 576
 
577
+  /**
578
+   * @param integer $location_type
579
+   */
577 580
   public static function db_ins_field_set($location_type, $field_set, $serialize = false) {
578 581
     // TODO multiinsert
579 582
     !sn_db_field_set_is_safe($field_set) ? $field_set = sn_db_field_set_make_safe($field_set, $serialize) : false;
Please login to merge, or discard this patch.
Spacing   +106 added lines, -108 removed lines patch added patch discarded remove patch
@@ -191,7 +191,7 @@  discard block
 block discarded – undo
191 191
 
192 192
 
193 193
   public static function log_file($message, $spaces = 0) {
194
-    if(self::$debug_handler) {
194
+    if (self::$debug_handler) {
195 195
       self::$debug_handler->log_file($message, $spaces);
196 196
     }
197 197
   }
@@ -202,14 +202,14 @@  discard block
 block discarded – undo
202 202
   // Перепаковывает массив на заданную глубину, убирая поля с null
203 203
   public static function array_repack(&$array, $level = 0) {
204 204
     // TODO $lock_table не нужна тут
205
-    if(!is_array($array)) return;
205
+    if (!is_array($array)) return;
206 206
 
207
-    foreach($array as $key => &$value) {
208
-      if($value === null) {
207
+    foreach ($array as $key => &$value) {
208
+      if ($value === null) {
209 209
         unset($array[$key]);
210
-      } elseif($level > 0 && is_array($value)) {
210
+      } elseif ($level > 0 && is_array($value)) {
211 211
         static::array_repack($value, $level - 1);
212
-        if(empty($value)) unset($array[$key]);
212
+        if (empty($value)) unset($array[$key]);
213 213
       }
214 214
     }
215 215
   }
@@ -218,7 +218,7 @@  discard block
 block discarded – undo
218 218
   // TODO Вынести в отдельный объект
219 219
   public static function cache_repack($location_type, $record_id = 0) {
220 220
     // Если есть $user_id - проверяем, а надо ли перепаковывать?
221
-    if($record_id && isset(static::$data[$location_type][$record_id]) && static::$data[$location_type][$record_id] !== null) return;
221
+    if ($record_id && isset(static::$data[$location_type][$record_id]) && static::$data[$location_type][$record_id] !== null) return;
222 222
 
223 223
     static::array_repack(static::$data[$location_type]);
224 224
     static::array_repack(static::$locator[$location_type], 3); // TODO У каждого типа локации - своя глубина!!!! Но можно и глубже ???
@@ -226,9 +226,9 @@  discard block
 block discarded – undo
226 226
   }
227 227
   public static function cache_clear($location_type, $hard = true) {
228 228
     //print("<br />CACHE CLEAR {$cache_id} " . ($hard ? 'HARD' : 'SOFT') . "<br />");
229
-    if($hard && !empty(static::$data[$location_type])) {
229
+    if ($hard && !empty(static::$data[$location_type])) {
230 230
       // Здесь нельзя делать unset - надо записывать NULL, что бы это отразилось на зависимых записях
231
-      array_walk(static::$data[$location_type], function(&$item){$item = null;});
231
+      array_walk(static::$data[$location_type], function(&$item) {$item = null; });
232 232
     }
233 233
     static::$locator[$location_type] = array();
234 234
     static::$queries[$location_type] = array();
@@ -236,7 +236,7 @@  discard block
 block discarded – undo
236 236
   }
237 237
   public static function cache_clear_all($hard = true) {
238 238
     //print('<br />CACHE CLEAR ALL<br />');
239
-    if($hard) {
239
+    if ($hard) {
240 240
       static::$data = array();
241 241
       static::cache_lock_unset_all();
242 242
     }
@@ -263,10 +263,10 @@  discard block
 block discarded – undo
263 263
   */
264 264
   public static function cache_set($location_type, $record_id, $record, $force_overwrite = false, $skip_lock = false) {
265 265
     // нет идентификатора - выход
266
-    if(!($record_id = $record[static::$location_info[$location_type][P_ID]])) return;
266
+    if (!($record_id = $record[static::$location_info[$location_type][P_ID]])) return;
267 267
 
268 268
     $in_transaction = static::db_transaction_check(false);
269
-    if(
269
+    if (
270 270
       $force_overwrite
271 271
       ||
272 272
       // Не заменяются заблокированные записи во время транзакции
@@ -276,14 +276,14 @@  discard block
 block discarded – undo
276 276
       !static::cache_isset($location_type, $record_id)
277 277
     ) {
278 278
       static::$data[$location_type][$record_id] = $record;
279
-      if($in_transaction && !$skip_lock) {
279
+      if ($in_transaction && !$skip_lock) {
280 280
         static::cache_lock_set($location_type, $record_id);
281 281
       }
282 282
     }
283 283
   }
284 284
   public static function cache_unset($cache_id, $safe_record_id) {
285 285
     // $record_id должен быть проверен заранее !
286
-    if(isset(static::$data[$cache_id][$safe_record_id]) && static::$data[$cache_id][$safe_record_id] !== null) {
286
+    if (isset(static::$data[$cache_id][$safe_record_id]) && static::$data[$cache_id][$safe_record_id] !== null) {
287 287
       // Выставляем запись в null
288 288
       static::$data[$cache_id][$safe_record_id] = null;
289 289
       // Очищаем кэш мягко - что бы удалить очистить связанные данные - кэш локаций и кэш запоросов и всё, что потребуется впредь
@@ -297,7 +297,7 @@  discard block
 block discarded – undo
297 297
     return static::$locks[$location_type][$record_id] = true; // Не всегда - от результата
298 298
   }
299 299
   public static function cache_lock_unset($location_type, $record_id) {
300
-    if(isset(static::$locks[$location_type][$record_id]))
300
+    if (isset(static::$locks[$location_type][$record_id]))
301 301
       unset(static::$locks[$location_type][$record_id]);
302 302
     return true; // Не всегда - от результата
303 303
   }
@@ -327,13 +327,13 @@  discard block
 block discarded – undo
327 327
    */
328 328
   public static function db_transaction_check($status = null) {
329 329
     $error_msg = false;
330
-    if($status && !static::$db_in_transaction) {
330
+    if ($status && !static::$db_in_transaction) {
331 331
       $error_msg = 'No transaction started for current operation';
332
-    } elseif($status === null && static::$db_in_transaction) {
332
+    } elseif ($status === null && static::$db_in_transaction) {
333 333
       $error_msg = 'Transaction is already started';
334 334
     }
335 335
 
336
-    if($error_msg) {
336
+    if ($error_msg) {
337 337
       // TODO - Убрать позже
338 338
       print('<h1>СООБЩИТЕ ЭТО АДМИНУ: sn_db_transaction_check() - ' . $error_msg . '</h1>');
339 339
       $backtrace = debug_backtrace();
@@ -354,7 +354,7 @@  discard block
 block discarded – undo
354 354
     static::$transaction_id++;
355 355
     doquery('START TRANSACTION');
356 356
 
357
-    if($config->db_manual_lock_enabled) {
357
+    if ($config->db_manual_lock_enabled) {
358 358
       $config->db_loadItem('var_db_manually_locked');
359 359
       $config->db_saveItem('var_db_manually_locked', SN_TIME_SQL);
360 360
     }
@@ -369,7 +369,7 @@  discard block
 block discarded – undo
369 369
   public static function db_transaction_commit() {
370 370
     static::db_transaction_check(true);
371 371
 
372
-    if(!empty(static::$delayed_changset)) {
372
+    if (!empty(static::$delayed_changset)) {
373 373
       static::db_changeset_apply(static::$delayed_changset, true);
374 374
       // pdump(static::$delayed_changset);
375 375
     }
@@ -384,7 +384,7 @@  discard block
 block discarded – undo
384 384
   }
385 385
   public static function db_transaction_rollback() {
386 386
     // static::db_transaction_check(true); // TODO - вообще-то тут тоже надо проверять есть ли транзакция
387
-    if(!empty(static::$delayed_changset)) {
387
+    if (!empty(static::$delayed_changset)) {
388 388
       static::db_changeset_revert();
389 389
     }
390 390
     static::$delayed_changset = array();
@@ -405,7 +405,7 @@  discard block
 block discarded – undo
405 405
    */
406 406
   public static function db_lock_tables($tables) {
407 407
     $tables = is_array($tables) ? $tables : array($tables => '');
408
-    foreach($tables as $table_name => $condition) {
408
+    foreach ($tables as $table_name => $condition) {
409 409
       self::$db->doquery("SELECT 1 FROM {{{$table_name}}}" . ($condition ? ' WHERE ' . $condition : ''));
410 410
     }
411 411
   }
@@ -446,17 +446,17 @@  discard block
 block discarded – undo
446 446
     //pdump($filter, 'Выбираем ' . $location_type);
447 447
     $query_cache = &static::$queries[$location_type][$filter];
448 448
 
449
-    if(!isset($query_cache) || $query_cache === null) {
449
+    if (!isset($query_cache) || $query_cache === null) {
450 450
       // pdump($filter, 'Кэш пустой, начинаем возню');
451 451
       $location_info = &static::$location_info[$location_type];
452 452
       $id_field = $location_info[P_ID];
453 453
       $query_cache = array();
454 454
 
455
-      if(static::db_transaction_check(false)) {
455
+      if (static::db_transaction_check(false)) {
456 456
         //pdump($filter, 'Транзакция - блокируем ' . $location_type);
457 457
         // Проходим по всем родителям данной записи
458 458
         // foreach($location_info[P_OWNER_INFO] as $owner_location_type => $owner_data)
459
-        foreach($location_info[P_OWNER_INFO] as $owner_data) {
459
+        foreach ($location_info[P_OWNER_INFO] as $owner_data) {
460 460
           $owner_location_type = $owner_data[P_LOCATION];
461 461
           //pdump($filter, 'Транзакция - блокируем родителя ' . $owner_location_type);
462 462
           $parent_id_list = array();
@@ -469,14 +469,14 @@  discard block
 block discarded – undo
469 469
             ($fetch ? ' LIMIT 1' : ''), false, true);
470 470
 
471 471
           //pdump($q, 'Запрос блокировки');
472
-          while($row = db_fetch($query)) {
472
+          while ($row = db_fetch($query)) {
473 473
             // Исключаем из списка родительских ИД уже заблокированные записи
474
-            if(!static::cache_lock_get($owner_location_type, $row['parent_id']))
474
+            if (!static::cache_lock_get($owner_location_type, $row['parent_id']))
475 475
               $parent_id_list[$row['parent_id']] = $row['parent_id'];
476 476
           }
477 477
           //pdump($parent_id_list, 'Выбраны родители');
478 478
           // Если все-таки какие-то записи еще не заблокированы - вынимаем текущие версии из базы
479
-          if($indexes_str = implode(',', $parent_id_list)) {
479
+          if ($indexes_str = implode(',', $parent_id_list)) {
480 480
             //pdump($indexes_str, '$indexes_str');
481 481
             $parent_id_field = static::$location_info[$owner_location_type][P_ID];
482 482
             static::db_get_record_list($owner_location_type,
@@ -491,7 +491,7 @@  discard block
 block discarded – undo
491 491
         "SELECT * FROM {{{$location_info[P_TABLE_NAME]}}}" .
492 492
         (($filter = trim($filter)) ? " WHERE {$filter}" : '')
493 493
       );
494
-      while($row = db_fetch($query)) {
494
+      while ($row = db_fetch($query)) {
495 495
         // static::db_get_record_by_id($location_type, $row[$id_field]);
496 496
         static::cache_set($location_type, $row[$id_field], $row);
497 497
         $query_cache[$row[$id_field]] = &static::$data[$location_type][$row[$id_field]];
@@ -499,14 +499,14 @@  discard block
 block discarded – undo
499 499
       }
500 500
     }
501 501
 
502
-    if($no_return) {
502
+    if ($no_return) {
503 503
       return true;
504 504
     } else {
505 505
       $result = false;
506
-      if(is_array($query_cache)) {
507
-        foreach($query_cache as $key => $value) {
506
+      if (is_array($query_cache)) {
507
+        foreach ($query_cache as $key => $value) {
508 508
           $result[$key] = $value;
509
-          if($fetch) break;
509
+          if ($fetch) break;
510 510
         }
511 511
       }
512 512
       return $fetch ? (is_array($result) ? reset($result) : false) : $result;
@@ -515,14 +515,14 @@  discard block
 block discarded – undo
515 515
 
516 516
   public static function db_upd_record_by_id($location_type, $record_id, $set) {
517 517
     //if(!($record_id = intval($record_id)) || !($set = trim($set))) return false;
518
-    if(!($record_id = idval($record_id)) || !($set = trim($set))) return false;
518
+    if (!($record_id = idval($record_id)) || !($set = trim($set))) return false;
519 519
 
520 520
     $location_info = &static::$location_info[$location_type];
521 521
     $id_field = $location_info[P_ID];
522 522
     $table_name = $location_info[P_TABLE_NAME];
523
-    if($result = static::db_query($q = "UPDATE {{{$table_name}}} SET {$set} WHERE `{$id_field}` = {$record_id}")) // TODO Как-то вернуть может быть LIMIT 1 ?
523
+    if ($result = static::db_query($q = "UPDATE {{{$table_name}}} SET {$set} WHERE `{$id_field}` = {$record_id}")) // TODO Как-то вернуть может быть LIMIT 1 ?
524 524
     {
525
-      if(static::$db->db_affected_rows()) {
525
+      if (static::$db->db_affected_rows()) {
526 526
         // Обновляем данные только если ряд был затронут
527 527
         // TODO - переделать под работу со структурированными $set
528 528
 
@@ -537,16 +537,16 @@  discard block
 block discarded – undo
537 537
     return $result;
538 538
   }
539 539
   public static function db_upd_record_list($location_type, $condition, $set) {
540
-    if(!($set = trim($set))) return false;
540
+    if (!($set = trim($set))) return false;
541 541
 
542 542
     $condition = trim($condition);
543 543
     $table_name = static::$location_info[$location_type][P_TABLE_NAME];
544 544
 
545 545
 //static::db_get_record_list($location_type, $condition, false, true);
546 546
 
547
-    if($result = static::db_query("UPDATE {{{$table_name}}} SET " . $set . ($condition ? ' WHERE ' . $condition : ''))) {
547
+    if ($result = static::db_query("UPDATE {{{$table_name}}} SET " . $set . ($condition ? ' WHERE ' . $condition : ''))) {
548 548
 
549
-      if(static::$db->db_affected_rows()) { // Обновляем данные только если ряд был затронут
549
+      if (static::$db->db_affected_rows()) { // Обновляем данные только если ряд был затронут
550 550
         // Поскольку нам неизвестно, что и как обновилось - сбрасываем кэш этого типа полностью
551 551
         // TODO - когда будет структурированный $condition и $set - перепаковывать данные
552 552
         static::cache_clear($location_type, true);
@@ -559,8 +559,8 @@  discard block
 block discarded – undo
559 559
   public static function db_ins_record($location_type, $set) {
560 560
     $set = trim($set);
561 561
     $table_name = static::$location_info[$location_type][P_TABLE_NAME];
562
-    if($result = static::db_query("INSERT INTO `{{{$table_name}}}` SET {$set}")) {
563
-      if(static::$db->db_affected_rows()) // Обновляем данные только если ряд был затронут
562
+    if ($result = static::db_query("INSERT INTO `{{{$table_name}}}` SET {$set}")) {
563
+      if (static::$db->db_affected_rows()) // Обновляем данные только если ряд был затронут
564 564
       {
565 565
         $record_id = db_insert_id();
566 566
         // Вытаскиваем запись целиком, потому что в $set могли быть "данные по умолчанию"
@@ -582,8 +582,8 @@  discard block
 block discarded – undo
582 582
     $fields = implode(',', array_keys($field_set));
583 583
 
584 584
     $table_name = static::$location_info[$location_type][P_TABLE_NAME];
585
-    if($result = static::db_query("INSERT INTO `{{{$table_name}}}` ($fields) VALUES ($values);")) {
586
-      if(static::$db->db_affected_rows()) {
585
+    if ($result = static::db_query("INSERT INTO `{{{$table_name}}}` ($fields) VALUES ($values);")) {
586
+      if (static::$db->db_affected_rows()) {
587 587
         // Обновляем данные только если ряд был затронут
588 588
         $record_id = db_insert_id();
589 589
         // Вытаскиваем запись целиком, потому что в $set могли быть "данные по умолчанию"
@@ -600,14 +600,14 @@  discard block
 block discarded – undo
600 600
   public static function db_del_record_by_id($location_type, $safe_record_id)
601 601
   {
602 602
     // if(!($safe_record_id = intval($safe_record_id))) return false;
603
-    if(!($safe_record_id = idval($safe_record_id))) return false;
603
+    if (!($safe_record_id = idval($safe_record_id))) return false;
604 604
 
605 605
     $location_info = &static::$location_info[$location_type];
606 606
     $id_field = $location_info[P_ID];
607 607
     $table_name = $location_info[P_TABLE_NAME];
608
-    if($result = static::db_query("DELETE FROM `{{{$table_name}}}` WHERE `{$id_field}` = {$safe_record_id}"))
608
+    if ($result = static::db_query("DELETE FROM `{{{$table_name}}}` WHERE `{$id_field}` = {$safe_record_id}"))
609 609
     {
610
-      if(static::$db->db_affected_rows()) // Обновляем данные только если ряд был затронут
610
+      if (static::$db->db_affected_rows()) // Обновляем данные только если ряд был затронут
611 611
       {
612 612
         static::cache_unset($location_type, $safe_record_id);
613 613
       }
@@ -617,16 +617,16 @@  discard block
 block discarded – undo
617 617
   }
618 618
   public static function db_del_record_list($location_type, $condition)
619 619
   {
620
-    if(!($condition = trim($condition))) return false;
620
+    if (!($condition = trim($condition))) return false;
621 621
 
622 622
     $location_info = &static::$location_info[$location_type];
623 623
     $table_name = $location_info[P_TABLE_NAME];
624 624
 
625 625
 //static::db_get_record_list($location_type, $condition, false, true);
626 626
 
627
-    if($result = static::db_query("DELETE FROM `{{{$table_name}}}` WHERE {$condition}"))
627
+    if ($result = static::db_query("DELETE FROM `{{{$table_name}}}` WHERE {$condition}"))
628 628
     {
629
-      if(static::$db->db_affected_rows()) // Обновляем данные только если ряд был затронут
629
+      if (static::$db->db_affected_rows()) // Обновляем данные только если ряд был затронут
630 630
       {
631 631
         // Обнуление кэша, потому что непонятно, что поменялось
632 632
         // TODO - когда будет структурированный $condition можно будет делать только cache_unset по нужным записям
@@ -673,21 +673,21 @@  discard block
 block discarded – undo
673 673
   public static function db_get_user_by_username($username_unsafe, $for_update = false, $fields = '*', $player = null, $like = false)
674 674
   {
675 675
     // TODO Проверить, кстати - а везде ли нужно выбирать юзеров или где-то все-таки ищутся Альянсы ?
676
-    if(!($username_unsafe = trim($username_unsafe))) return false;
676
+    if (!($username_unsafe = trim($username_unsafe))) return false;
677 677
 
678 678
     $user = null;
679
-    if(is_array(static::$data[LOC_USER]))
680
-    foreach(static::$data[LOC_USER] as $user_id => $user_data)
679
+    if (is_array(static::$data[LOC_USER]))
680
+    foreach (static::$data[LOC_USER] as $user_id => $user_data)
681 681
     {
682
-      if(is_array($user_data) && isset($user_data['username']))
682
+      if (is_array($user_data) && isset($user_data['username']))
683 683
       {
684 684
         // проверяем поле
685 685
         // TODO Возможно есть смысл всегда искать по strtolower - но может игрок захочет переименоваться с другим регистром? Проверить!
686
-        if((!$like && $user_data['username'] == $username_unsafe) || ($like && strtolower($user_data['username']) == strtolower($username_unsafe)))
686
+        if ((!$like && $user_data['username'] == $username_unsafe) || ($like && strtolower($user_data['username']) == strtolower($username_unsafe)))
687 687
         {
688 688
           // $user_as_ally = intval($user_data['user_as_ally']);
689 689
           $user_as_ally = idval($user_data['user_as_ally']);
690
-          if($player === null || ($player === true && !$user_as_ally) || ($player === false && $user_as_ally))
690
+          if ($player === null || ($player === true && !$user_as_ally) || ($player === false && $user_as_ally))
691 691
           {
692 692
             $user = $user_data;
693 693
             break;
@@ -696,7 +696,7 @@  discard block
 block discarded – undo
696 696
       }
697 697
     }
698 698
 
699
-    if($user === null)
699
+    if ($user === null)
700 700
     {
701 701
       // Вытаскиваем запись
702 702
       $username_safe = db_escape($like ? strtolower($username_unsafe) : $username_unsafe); // тут на самом деле strtolower() лишняя, но пусть будет
@@ -705,7 +705,7 @@  discard block
 block discarded – undo
705 705
       // self::db_get_record_list(LOC_USER, "`username` " . ($like ? 'LIKE' : '='). " '{$username_safe}'");
706 706
 
707 707
       $user = static::db_query(
708
-        "SELECT * FROM {{users}} WHERE `username` " . ($like ? 'LIKE' : '='). " '{$username_safe}'"
708
+        "SELECT * FROM {{users}} WHERE `username` " . ($like ? 'LIKE' : '=') . " '{$username_safe}'"
709 709
       , true);
710 710
       static::cache_set(LOC_USER, $user['id'], $user); // В кэш-юзер так же заполнять индексы
711 711
     }
@@ -714,15 +714,15 @@  discard block
 block discarded – undo
714 714
   }
715 715
   // UNUSED
716 716
   public static function db_get_user_by_email($email_unsafe, $use_both = false, $for_update = false, $fields = '*') {
717
-    if(!($email_unsafe = strtolower(trim($email_unsafe)))) return false;
717
+    if (!($email_unsafe = strtolower(trim($email_unsafe)))) return false;
718 718
 
719 719
     $user = null;
720 720
     // TODO переделать на индексы
721
-    if(is_array(static::$data[LOC_USER])) {
722
-      foreach(static::$data[LOC_USER] as $user_id => $user_data) {
723
-        if(is_array($user_data) && isset($user_data['email_2'])) {
721
+    if (is_array(static::$data[LOC_USER])) {
722
+      foreach (static::$data[LOC_USER] as $user_id => $user_data) {
723
+        if (is_array($user_data) && isset($user_data['email_2'])) {
724 724
           // проверяем поле
725
-          if(strtolower($user_data['email_2']) == $email_unsafe || ($use_both && strtolower($user_data['email']) == $email_unsafe)) {
725
+          if (strtolower($user_data['email_2']) == $email_unsafe || ($use_both && strtolower($user_data['email']) == $email_unsafe)) {
726 726
             $user = $user_data;
727 727
             break;
728 728
           }
@@ -730,7 +730,7 @@  discard block
 block discarded – undo
730 730
       }
731 731
     }
732 732
 
733
-    if($user === null) {
733
+    if ($user === null) {
734 734
       // Вытаскиваем запись
735 735
       $email_safe = db_escape($email_unsafe);
736 736
       $user = static::db_query(
@@ -748,7 +748,7 @@  discard block
 block discarded – undo
748 748
     $user = null;
749 749
     // TODO переделать на индексы
750 750
 
751
-    if($user === null && !empty($where_safe)) {
751
+    if ($user === null && !empty($where_safe)) {
752 752
       // Вытаскиваем запись
753 753
       $user = static::db_query("SELECT * FROM {{users}} WHERE {$where_safe}", true);
754 754
 
@@ -783,7 +783,7 @@  discard block
 block discarded – undo
783 783
   {
784 784
     // TODO запихивать в $data[LOC_LOCATION][$location_type][$location_id]
785 785
     $unit = static::db_get_record_by_id(LOC_UNIT, $unit_id, $for_update, $fields);
786
-    if(is_array($unit))
786
+    if (is_array($unit))
787 787
     {
788 788
       static::$locator[LOC_UNIT][$unit['unit_location_type']][$unit['unit_location_id']][$unit['unit_snid']] = &static::$data[LOC_UNIT][$unit_id];
789 789
     }
@@ -794,15 +794,15 @@  discard block
 block discarded – undo
794 794
   public static function db_get_unit_list_by_location($user_id = 0, $location_type, $location_id)
795 795
   {
796 796
     //if(!($location_type = intval($location_type)) || !($location_id = intval($location_id))) return false;
797
-    if(!($location_type = idval($location_type)) || !($location_id = idval($location_id))) return false;
797
+    if (!($location_type = idval($location_type)) || !($location_id = idval($location_id))) return false;
798 798
 
799 799
     $query_cache = &static::$locator[LOC_UNIT][$location_type][$location_id];
800
-    if(!isset($query_cache))
800
+    if (!isset($query_cache))
801 801
     {
802 802
       $got_data = static::db_get_record_list(LOC_UNIT, "unit_location_type = {$location_type} AND unit_location_id = {$location_id} AND " . static::db_unit_time_restrictions());
803
-      if(is_array($got_data))
803
+      if (is_array($got_data))
804 804
       {
805
-        foreach($got_data as $unit_id => $unit_data)
805
+        foreach ($got_data as $unit_id => $unit_data)
806 806
         {
807 807
           // static::$data[LOC_LOCATION][$location_type][$location_id][$unit_data['unit_snid']] = &static::$data[LOC_UNIT][$unit_id];
808 808
           $query_cache[$unit_data['unit_snid']] = &static::$data[LOC_UNIT][$unit_id];
@@ -811,8 +811,8 @@  discard block
 block discarded – undo
811 811
     }
812 812
 
813 813
     $result = false;
814
-    if(is_array($query_cache)) {
815
-      foreach($query_cache as $key => $value) {
814
+    if (is_array($query_cache)) {
815
+      foreach ($query_cache as $key => $value) {
816 816
         $result[$key] = $value;
817 817
       }
818 818
     }
@@ -850,7 +850,7 @@  discard block
 block discarded – undo
850 850
    */
851 851
   public static function db_que_list_by_type_location($user_id, $planet_id = null, $que_type = false, $for_update = false)
852 852
   {
853
-    if(!$user_id)
853
+    if (!$user_id)
854 854
     {
855 855
       pdump(debug_backtrace());
856 856
       die('No user_id for que_get_que()');
@@ -861,14 +861,14 @@  discard block
 block discarded – undo
861 861
     $query = array();
862 862
 
863 863
     // if($user_id = intval($user_id))
864
-    if($user_id = idval($user_id))
864
+    if ($user_id = idval($user_id))
865 865
       $query[] = "`que_player_id` = {$user_id}";
866 866
 
867
-    if($que_type == QUE_RESEARCH || $planet_id === null)
867
+    if ($que_type == QUE_RESEARCH || $planet_id === null)
868 868
       $query[] = "`que_planet_id` IS NULL";
869
-    elseif($planet_id)
869
+    elseif ($planet_id)
870 870
       $query[] = "(`que_planet_id` = {$planet_id}" . ($que_type ? '' : ' OR que_planet_id IS NULL') . ")";
871
-    if($que_type)
871
+    if ($que_type)
872 872
       $query[] = "`que_type` = {$que_type}";
873 873
 
874 874
     /*
@@ -953,14 +953,14 @@  discard block
 block discarded – undo
953 953
 
954 954
   public static function db_changeset_prepare_unit($unit_id, $unit_value, $user, $planet_id = null)
955 955
   {
956
-    if(!is_array($user))
956
+    if (!is_array($user))
957 957
     {
958 958
       // TODO - remove later
959 959
       print('<h1>СООБЩИТЕ ЭТО АДМИНУ: sn_db_unit_changeset_prepare() - USER is not ARRAY</h1>');
960 960
       pdump(debug_backtrace());
961 961
       die('USER is not ARRAY');
962 962
     }
963
-    if(!isset($user['id']) || !$user['id'])
963
+    if (!isset($user['id']) || !$user['id'])
964 964
     {
965 965
       // TODO - remove later
966 966
       print('<h1>СООБЩИТЕ ЭТО АДМИНУ: sn_db_unit_changeset_prepare() - USER[id] пустой</h1>');
@@ -976,7 +976,7 @@  discard block
 block discarded – undo
976 976
 
977 977
     $db_changeset = array();
978 978
     $temp = db_unit_by_location($user['id'], $unit_location, $location_id, $unit_id, true, 'unit_id');
979
-    if($temp['unit_id'])
979
+    if ($temp['unit_id'])
980 980
     {
981 981
       $db_changeset = array(
982 982
         'action' => SQL_OP_UPDATE,
@@ -1051,9 +1051,9 @@  discard block
 block discarded – undo
1051 1051
   }
1052 1052
 
1053 1053
   public function db_changeset_condition_compile(&$conditions, &$table_name = '') {
1054
-    if(!$conditions[P_LOCATION] || $conditions[P_LOCATION] == LOC_NONE) {
1054
+    if (!$conditions[P_LOCATION] || $conditions[P_LOCATION] == LOC_NONE) {
1055 1055
       $conditions[P_LOCATION] = LOC_NONE;
1056
-      switch($table_name) {
1056
+      switch ($table_name) {
1057 1057
         case 'users':
1058 1058
         case LOC_USER:
1059 1059
           $conditions[P_TABLE_NAME] = $table_name = 'users';
@@ -1075,18 +1075,18 @@  discard block
 block discarded – undo
1075 1075
     }
1076 1076
 
1077 1077
     $conditions[P_FIELDS_STR] = '';
1078
-    if($conditions['fields']) {
1078
+    if ($conditions['fields']) {
1079 1079
       $fields = array();
1080
-      foreach($conditions['fields'] as $field_name => $field_data) {
1080
+      foreach ($conditions['fields'] as $field_name => $field_data) {
1081 1081
         $condition = "`{$field_name}` = ";
1082 1082
         $value = '';
1083
-        if($field_data['delta']) {
1083
+        if ($field_data['delta']) {
1084 1084
           $value = "`{$field_name}`" . ($field_data['delta'] >= 0 ? '+' : '') . $field_data['delta'];
1085
-        } elseif($field_data['set']) {
1086
-          $value = (is_string($field_data['set']) ? "'{$field_data['set']}'": $field_data['set']);
1085
+        } elseif ($field_data['set']) {
1086
+          $value = (is_string($field_data['set']) ? "'{$field_data['set']}'" : $field_data['set']);
1087 1087
         }
1088 1088
 
1089
-        if($value) {
1089
+        if ($value) {
1090 1090
           $fields[] = $condition . $value;
1091 1091
         }
1092 1092
       }
@@ -1094,16 +1094,14 @@  discard block
 block discarded – undo
1094 1094
     }
1095 1095
 
1096 1096
     $conditions[P_WHERE_STR] = '';
1097
-    if(!empty($conditions['where'])) {
1098
-      if($conditions[P_VERSION] == 1) {
1097
+    if (!empty($conditions['where'])) {
1098
+      if ($conditions[P_VERSION] == 1) {
1099 1099
         $the_conditions = array();
1100
-        foreach($conditions['where'] as $field_id => $field_value) {
1100
+        foreach ($conditions['where'] as $field_id => $field_value) {
1101 1101
           // Простое условие - $field_id = $field_value
1102
-          if(is_string($field_id)) {
1102
+          if (is_string($field_id)) {
1103 1103
             $field_value =
1104
-              $field_value === null ? 'NULL' :
1105
-                (is_string($field_value) ? "'" . db_escape($field_value) . "'" :
1106
-                  (is_bool($field_value) ? intval($field_value) : $field_value));
1104
+              $field_value === null ? 'NULL' : (is_string($field_value) ? "'" . db_escape($field_value) . "'" : (is_bool($field_value) ? intval($field_value) : $field_value));
1107 1105
             $the_conditions[] = "`{$field_id}` = {$field_value}";
1108 1106
           } else {
1109 1107
             die('Неподдерживаемый тип условия');
@@ -1120,7 +1118,7 @@  discard block
 block discarded – undo
1120 1118
       $conditions[P_WHERE_STR] = implode(' AND ', $the_conditions);
1121 1119
     }
1122 1120
 
1123
-    switch($conditions['action']) {
1121
+    switch ($conditions['action']) {
1124 1122
       case SQL_OP_DELETE: $conditions[P_ACTION_STR] = ("DELETE FROM {{{$table_name}}}"); break;
1125 1123
       case SQL_OP_UPDATE: $conditions[P_ACTION_STR] = ("UPDATE {{{$table_name}}} SET"); break;
1126 1124
       case SQL_OP_INSERT: $conditions[P_ACTION_STR] = ("INSERT INTO {{{$table_name}}} SET"); break;
@@ -1133,9 +1131,9 @@  discard block
 block discarded – undo
1133 1131
 
1134 1132
   public static function db_changeset_apply($db_changeset, $flush_delayed = false) {
1135 1133
     $result = true;
1136
-    if(!is_array($db_changeset) || empty($db_changeset)) return $result;
1134
+    if (!is_array($db_changeset) || empty($db_changeset)) return $result;
1137 1135
 
1138
-    foreach($db_changeset as $table_name => &$table_data) {
1136
+    foreach ($db_changeset as $table_name => &$table_data) {
1139 1137
       // TODO - delayed changeset
1140 1138
       /*
1141 1139
       if(static::db_transaction_check(false) && !$flush_delayed && ($table_name == 'users' || $table_name == 'planets' || $table_name == 'unit'))
@@ -1144,15 +1142,15 @@  discard block
 block discarded – undo
1144 1142
         continue;
1145 1143
       }
1146 1144
       */
1147
-      foreach($table_data as $record_id => &$conditions) {
1145
+      foreach ($table_data as $record_id => &$conditions) {
1148 1146
         static::db_changeset_condition_compile($conditions, $table_name);
1149 1147
 
1150
-        if($conditions['action'] != SQL_OP_DELETE && !$conditions[P_FIELDS_STR]) continue;
1151
-        if($conditions['action'] == SQL_OP_DELETE && !$conditions[P_WHERE_STR]) continue; // Защита от случайного удаления всех данных в таблице
1148
+        if ($conditions['action'] != SQL_OP_DELETE && !$conditions[P_FIELDS_STR]) continue;
1149
+        if ($conditions['action'] == SQL_OP_DELETE && !$conditions[P_WHERE_STR]) continue; // Защита от случайного удаления всех данных в таблице
1152 1150
 
1153
-        if($conditions[P_LOCATION] != LOC_NONE) {
1151
+        if ($conditions[P_LOCATION] != LOC_NONE) {
1154 1152
           //die('spec ops supernova.php line 928 Добавить работу с кэшем юнитов итд');
1155
-          switch($conditions['action'])
1153
+          switch ($conditions['action'])
1156 1154
           {
1157 1155
             case SQL_OP_DELETE: $result = self::db_del_record_list($conditions[P_LOCATION], $conditions[P_WHERE_STR]) && $result; break;
1158 1156
             case SQL_OP_UPDATE: $result = self::db_upd_record_list($conditions[P_LOCATION], $conditions[P_WHERE_STR], $conditions[P_FIELDS_STR]) && $result; break;
@@ -1233,16 +1231,16 @@  discard block
 block discarded – undo
1233 1231
   }
1234 1232
 
1235 1233
 
1236
-  public static function init_0_prepare () {
1234
+  public static function init_0_prepare() {
1237 1235
     // Отключаем magic_quotes
1238 1236
     ini_get('magic_quotes_sybase') ? die('SN is incompatible with \'magic_quotes_sybase\' turned on. Disable it in php.ini or .htaccess...') : false;
1239
-    if(@get_magic_quotes_gpc()) {
1237
+    if (@get_magic_quotes_gpc()) {
1240 1238
       $gpcr = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
1241
-      array_walk_recursive($gpcr, function (&$value, $key) {
1239
+      array_walk_recursive($gpcr, function(&$value, $key) {
1242 1240
         $value = stripslashes($value);
1243 1241
       });
1244 1242
     }
1245
-    if(function_exists('set_magic_quotes_runtime')) {
1243
+    if (function_exists('set_magic_quotes_runtime')) {
1246 1244
       @set_magic_quotes_runtime(0);
1247 1245
       @ini_set('magic_quotes_runtime', 0);
1248 1246
       @ini_set('magic_quotes_sybase', 0);
@@ -1320,7 +1318,7 @@  discard block
 block discarded – undo
1320 1318
   }
1321 1319
 
1322 1320
   public static function init_debug_state() {
1323
-    if($_SERVER['SERVER_NAME'] == 'localhost' && !defined('BE_DEBUG')) {
1321
+    if ($_SERVER['SERVER_NAME'] == 'localhost' && !defined('BE_DEBUG')) {
1324 1322
       define('BE_DEBUG', true);
1325 1323
     }
1326 1324
 // define('DEBUG_SQL_ONLINE', true); // Полный дамп запросов в рил-тайме. Подойдет любое значение
@@ -1332,7 +1330,7 @@  discard block
 block discarded – undo
1332 1330
     defined('DEBUG_SQL_ERROR') && !defined('DEBUG_SQL_COMMENT') ? define('DEBUG_SQL_COMMENT', true) : false;
1333 1331
     defined('DEBUG_SQL_COMMENT_LONG') && !defined('DEBUG_SQL_COMMENT') ? define('DEBUG_SQL_COMMENT', true) : false;
1334 1332
 
1335
-    if(defined('BE_DEBUG') || static::$config->debug) {
1333
+    if (defined('BE_DEBUG') || static::$config->debug) {
1336 1334
       @define('BE_DEBUG', true);
1337 1335
       @ini_set('display_errors', 1);
1338 1336
       @error_reporting(E_ALL ^ E_NOTICE ^ E_DEPRECATED);
Please login to merge, or discard this patch.
Braces   +79 added lines, -35 removed lines patch added patch discarded remove patch
@@ -202,14 +202,18 @@  discard block
 block discarded – undo
202 202
   // Перепаковывает массив на заданную глубину, убирая поля с null
203 203
   public static function array_repack(&$array, $level = 0) {
204 204
     // TODO $lock_table не нужна тут
205
-    if(!is_array($array)) return;
205
+    if(!is_array($array)) {
206
+      return;
207
+    }
206 208
 
207 209
     foreach($array as $key => &$value) {
208 210
       if($value === null) {
209 211
         unset($array[$key]);
210 212
       } elseif($level > 0 && is_array($value)) {
211 213
         static::array_repack($value, $level - 1);
212
-        if(empty($value)) unset($array[$key]);
214
+        if(empty($value)) {
215
+          unset($array[$key]);
216
+        }
213 217
       }
214 218
     }
215 219
   }
@@ -218,7 +222,9 @@  discard block
 block discarded – undo
218 222
   // TODO Вынести в отдельный объект
219 223
   public static function cache_repack($location_type, $record_id = 0) {
220 224
     // Если есть $user_id - проверяем, а надо ли перепаковывать?
221
-    if($record_id && isset(static::$data[$location_type][$record_id]) && static::$data[$location_type][$record_id] !== null) return;
225
+    if($record_id && isset(static::$data[$location_type][$record_id]) && static::$data[$location_type][$record_id] !== null) {
226
+      return;
227
+    }
222 228
 
223 229
     static::array_repack(static::$data[$location_type]);
224 230
     static::array_repack(static::$locator[$location_type], 3); // TODO У каждого типа локации - своя глубина!!!! Но можно и глубже ???
@@ -263,7 +269,9 @@  discard block
 block discarded – undo
263 269
   */
264 270
   public static function cache_set($location_type, $record_id, $record, $force_overwrite = false, $skip_lock = false) {
265 271
     // нет идентификатора - выход
266
-    if(!($record_id = $record[static::$location_info[$location_type][P_ID]])) return;
272
+    if(!($record_id = $record[static::$location_info[$location_type][P_ID]])) {
273
+      return;
274
+    }
267 275
 
268 276
     $in_transaction = static::db_transaction_check(false);
269 277
     if(
@@ -297,8 +305,9 @@  discard block
 block discarded – undo
297 305
     return static::$locks[$location_type][$record_id] = true; // Не всегда - от результата
298 306
   }
299 307
   public static function cache_lock_unset($location_type, $record_id) {
300
-    if(isset(static::$locks[$location_type][$record_id]))
301
-      unset(static::$locks[$location_type][$record_id]);
308
+    if(isset(static::$locks[$location_type][$record_id])) {
309
+          unset(static::$locks[$location_type][$record_id]);
310
+    }
302 311
     return true; // Не всегда - от результата
303 312
   }
304 313
   public static function cache_lock_unset_all() {
@@ -471,8 +480,9 @@  discard block
 block discarded – undo
471 480
           //pdump($q, 'Запрос блокировки');
472 481
           while($row = db_fetch($query)) {
473 482
             // Исключаем из списка родительских ИД уже заблокированные записи
474
-            if(!static::cache_lock_get($owner_location_type, $row['parent_id']))
475
-              $parent_id_list[$row['parent_id']] = $row['parent_id'];
483
+            if(!static::cache_lock_get($owner_location_type, $row['parent_id'])) {
484
+                          $parent_id_list[$row['parent_id']] = $row['parent_id'];
485
+            }
476 486
           }
477 487
           //pdump($parent_id_list, 'Выбраны родители');
478 488
           // Если все-таки какие-то записи еще не заблокированы - вынимаем текущие версии из базы
@@ -506,7 +516,9 @@  discard block
 block discarded – undo
506 516
       if(is_array($query_cache)) {
507 517
         foreach($query_cache as $key => $value) {
508 518
           $result[$key] = $value;
509
-          if($fetch) break;
519
+          if($fetch) {
520
+            break;
521
+          }
510 522
         }
511 523
       }
512 524
       return $fetch ? (is_array($result) ? reset($result) : false) : $result;
@@ -515,12 +527,15 @@  discard block
 block discarded – undo
515 527
 
516 528
   public static function db_upd_record_by_id($location_type, $record_id, $set) {
517 529
     //if(!($record_id = intval($record_id)) || !($set = trim($set))) return false;
518
-    if(!($record_id = idval($record_id)) || !($set = trim($set))) return false;
530
+    if(!($record_id = idval($record_id)) || !($set = trim($set))) {
531
+      return false;
532
+    }
519 533
 
520 534
     $location_info = &static::$location_info[$location_type];
521 535
     $id_field = $location_info[P_ID];
522 536
     $table_name = $location_info[P_TABLE_NAME];
523
-    if($result = static::db_query($q = "UPDATE {{{$table_name}}} SET {$set} WHERE `{$id_field}` = {$record_id}")) // TODO Как-то вернуть может быть LIMIT 1 ?
537
+    if($result = static::db_query($q = "UPDATE {{{$table_name}}} SET {$set} WHERE `{$id_field}` = {$record_id}")) {
538
+      // TODO Как-то вернуть может быть LIMIT 1 ?
524 539
     {
525 540
       if(static::$db->db_affected_rows()) {
526 541
         // Обновляем данные только если ряд был затронут
@@ -528,6 +543,7 @@  discard block
 block discarded – undo
528 543
 
529 544
         // Тут именно так, а не cache_unset - что бы в кэшах автоматически обновилась запись. Будет нужно на будущее
530 545
         static::$data[$location_type][$record_id] = null;
546
+    }
531 547
         // Вытаскиваем обновленную запись
532 548
         static::db_get_record_by_id($location_type, $record_id);
533 549
         static::cache_clear($location_type, false); // Мягкий сброс - только $queries
@@ -537,7 +553,9 @@  discard block
 block discarded – undo
537 553
     return $result;
538 554
   }
539 555
   public static function db_upd_record_list($location_type, $condition, $set) {
540
-    if(!($set = trim($set))) return false;
556
+    if(!($set = trim($set))) {
557
+      return false;
558
+    }
541 559
 
542 560
     $condition = trim($condition);
543 561
     $table_name = static::$location_info[$location_type][P_TABLE_NAME];
@@ -560,9 +578,11 @@  discard block
 block discarded – undo
560 578
     $set = trim($set);
561 579
     $table_name = static::$location_info[$location_type][P_TABLE_NAME];
562 580
     if($result = static::db_query("INSERT INTO `{{{$table_name}}}` SET {$set}")) {
563
-      if(static::$db->db_affected_rows()) // Обновляем данные только если ряд был затронут
581
+      if(static::$db->db_affected_rows()) {
582
+        // Обновляем данные только если ряд был затронут
564 583
       {
565 584
         $record_id = db_insert_id();
585
+      }
566 586
         // Вытаскиваем запись целиком, потому что в $set могли быть "данные по умолчанию"
567 587
         $result = static::db_get_record_by_id($location_type, $record_id);
568 588
         // Очищаем второстепенные кэши - потому что вставленная запись могла повлиять на результаты запросов или локация или еще чего
@@ -600,24 +620,30 @@  discard block
 block discarded – undo
600 620
   public static function db_del_record_by_id($location_type, $safe_record_id)
601 621
   {
602 622
     // if(!($safe_record_id = intval($safe_record_id))) return false;
603
-    if(!($safe_record_id = idval($safe_record_id))) return false;
623
+    if(!($safe_record_id = idval($safe_record_id))) {
624
+      return false;
625
+    }
604 626
 
605 627
     $location_info = &static::$location_info[$location_type];
606 628
     $id_field = $location_info[P_ID];
607 629
     $table_name = $location_info[P_TABLE_NAME];
608 630
     if($result = static::db_query("DELETE FROM `{{{$table_name}}}` WHERE `{$id_field}` = {$safe_record_id}"))
609 631
     {
610
-      if(static::$db->db_affected_rows()) // Обновляем данные только если ряд был затронут
632
+      if(static::$db->db_affected_rows()) {
633
+        // Обновляем данные только если ряд был затронут
611 634
       {
612 635
         static::cache_unset($location_type, $safe_record_id);
613 636
       }
637
+      }
614 638
     }
615 639
 
616 640
     return $result;
617 641
   }
618 642
   public static function db_del_record_list($location_type, $condition)
619 643
   {
620
-    if(!($condition = trim($condition))) return false;
644
+    if(!($condition = trim($condition))) {
645
+      return false;
646
+    }
621 647
 
622 648
     $location_info = &static::$location_info[$location_type];
623 649
     $table_name = $location_info[P_TABLE_NAME];
@@ -626,12 +652,14 @@  discard block
 block discarded – undo
626 652
 
627 653
     if($result = static::db_query("DELETE FROM `{{{$table_name}}}` WHERE {$condition}"))
628 654
     {
629
-      if(static::$db->db_affected_rows()) // Обновляем данные только если ряд был затронут
655
+      if(static::$db->db_affected_rows()) {
656
+        // Обновляем данные только если ряд был затронут
630 657
       {
631 658
         // Обнуление кэша, потому что непонятно, что поменялось
632 659
         // TODO - когда будет структурированный $condition можно будет делать только cache_unset по нужным записям
633 660
         static::cache_clear($location_type);
634 661
       }
662
+      }
635 663
     }
636 664
 
637 665
     return $result;
@@ -673,11 +701,13 @@  discard block
 block discarded – undo
673 701
   public static function db_get_user_by_username($username_unsafe, $for_update = false, $fields = '*', $player = null, $like = false)
674 702
   {
675 703
     // TODO Проверить, кстати - а везде ли нужно выбирать юзеров или где-то все-таки ищутся Альянсы ?
676
-    if(!($username_unsafe = trim($username_unsafe))) return false;
704
+    if(!($username_unsafe = trim($username_unsafe))) {
705
+      return false;
706
+    }
677 707
 
678 708
     $user = null;
679
-    if(is_array(static::$data[LOC_USER]))
680
-    foreach(static::$data[LOC_USER] as $user_id => $user_data)
709
+    if(is_array(static::$data[LOC_USER])) {
710
+        foreach(static::$data[LOC_USER] as $user_id => $user_data)
681 711
     {
682 712
       if(is_array($user_data) && isset($user_data['username']))
683 713
       {
@@ -687,6 +717,7 @@  discard block
 block discarded – undo
687 717
         {
688 718
           // $user_as_ally = intval($user_data['user_as_ally']);
689 719
           $user_as_ally = idval($user_data['user_as_ally']);
720
+    }
690 721
           if($player === null || ($player === true && !$user_as_ally) || ($player === false && $user_as_ally))
691 722
           {
692 723
             $user = $user_data;
@@ -714,7 +745,9 @@  discard block
 block discarded – undo
714 745
   }
715 746
   // UNUSED
716 747
   public static function db_get_user_by_email($email_unsafe, $use_both = false, $for_update = false, $fields = '*') {
717
-    if(!($email_unsafe = strtolower(trim($email_unsafe)))) return false;
748
+    if(!($email_unsafe = strtolower(trim($email_unsafe)))) {
749
+      return false;
750
+    }
718 751
 
719 752
     $user = null;
720 753
     // TODO переделать на индексы
@@ -794,7 +827,9 @@  discard block
 block discarded – undo
794 827
   public static function db_get_unit_list_by_location($user_id = 0, $location_type, $location_id)
795 828
   {
796 829
     //if(!($location_type = intval($location_type)) || !($location_id = intval($location_id))) return false;
797
-    if(!($location_type = idval($location_type)) || !($location_id = idval($location_id))) return false;
830
+    if(!($location_type = idval($location_type)) || !($location_id = idval($location_id))) {
831
+      return false;
832
+    }
798 833
 
799 834
     $query_cache = &static::$locator[LOC_UNIT][$location_type][$location_id];
800 835
     if(!isset($query_cache))
@@ -861,15 +896,18 @@  discard block
 block discarded – undo
861 896
     $query = array();
862 897
 
863 898
     // if($user_id = intval($user_id))
864
-    if($user_id = idval($user_id))
865
-      $query[] = "`que_player_id` = {$user_id}";
899
+    if($user_id = idval($user_id)) {
900
+          $query[] = "`que_player_id` = {$user_id}";
901
+    }
866 902
 
867
-    if($que_type == QUE_RESEARCH || $planet_id === null)
868
-      $query[] = "`que_planet_id` IS NULL";
869
-    elseif($planet_id)
870
-      $query[] = "(`que_planet_id` = {$planet_id}" . ($que_type ? '' : ' OR que_planet_id IS NULL') . ")";
871
-    if($que_type)
872
-      $query[] = "`que_type` = {$que_type}";
903
+    if($que_type == QUE_RESEARCH || $planet_id === null) {
904
+          $query[] = "`que_planet_id` IS NULL";
905
+    } elseif($planet_id) {
906
+          $query[] = "(`que_planet_id` = {$planet_id}" . ($que_type ? '' : ' OR que_planet_id IS NULL') . ")";
907
+    }
908
+    if($que_type) {
909
+          $query[] = "`que_type` = {$que_type}";
910
+    }
873 911
 
874 912
     /*
875 913
     $sql = '';
@@ -990,8 +1028,7 @@  discard block
 block discarded – undo
990 1028
           ),
991 1029
         ),
992 1030
       );
993
-    }
994
-    else
1031
+    } else
995 1032
     {
996 1033
       $db_changeset = array(
997 1034
         'action' => SQL_OP_INSERT,
@@ -1133,7 +1170,9 @@  discard block
 block discarded – undo
1133 1170
 
1134 1171
   public static function db_changeset_apply($db_changeset, $flush_delayed = false) {
1135 1172
     $result = true;
1136
-    if(!is_array($db_changeset) || empty($db_changeset)) return $result;
1173
+    if(!is_array($db_changeset) || empty($db_changeset)) {
1174
+      return $result;
1175
+    }
1137 1176
 
1138 1177
     foreach($db_changeset as $table_name => &$table_data) {
1139 1178
       // TODO - delayed changeset
@@ -1147,8 +1186,13 @@  discard block
 block discarded – undo
1147 1186
       foreach($table_data as $record_id => &$conditions) {
1148 1187
         static::db_changeset_condition_compile($conditions, $table_name);
1149 1188
 
1150
-        if($conditions['action'] != SQL_OP_DELETE && !$conditions[P_FIELDS_STR]) continue;
1151
-        if($conditions['action'] == SQL_OP_DELETE && !$conditions[P_WHERE_STR]) continue; // Защита от случайного удаления всех данных в таблице
1189
+        if($conditions['action'] != SQL_OP_DELETE && !$conditions[P_FIELDS_STR]) {
1190
+          continue;
1191
+        }
1192
+        if($conditions['action'] == SQL_OP_DELETE && !$conditions[P_WHERE_STR]) {
1193
+          continue;
1194
+        }
1195
+        // Защита от случайного удаления всех данных в таблице
1152 1196
 
1153 1197
         if($conditions[P_LOCATION] != LOC_NONE) {
1154 1198
           //die('spec ops supernova.php line 928 Добавить работу с кэшем юнитов итд');
Please login to merge, or discard this patch.
includes/classes/template.php 4 patches
Doc Comments   +1 added lines patch added patch discarded remove patch
@@ -103,6 +103,7 @@
 block discarded – undo
103 103
   /**
104 104
   * Set custom template location (able to use directory outside of phpBB)
105 105
   * @access public
106
+  * @param string $template_path
106 107
   */
107 108
   function set_custom_template($template_path, $template_name, $fallback_template_path = false)
108 109
   {
Please login to merge, or discard this patch.
Indentation   +75 added lines, -75 removed lines patch added patch discarded remove patch
@@ -25,11 +25,11 @@  discard block
 block discarded – undo
25 25
 class template
26 26
 {
27 27
   /** variable that holds all the data we'll be substituting into
28
-  * the compiled templates. Takes form:
29
-  * --> $this->_tpldata[block][iteration#][child][iteration#][child2][iteration#][variablename] == value
30
-  * if it's a root-level variable, it'll be like this:
31
-  * --> $this->_tpldata[.][0][varname] == value
32
-  */
28
+   * the compiled templates. Takes form:
29
+   * --> $this->_tpldata[block][iteration#][child][iteration#][child2][iteration#][variablename] == value
30
+   * if it's a root-level variable, it'll be like this:
31
+   * --> $this->_tpldata[.][0][varname] == value
32
+   */
33 33
   var $_tpldata = array('.' => array(0 => array()));
34 34
   var $_rootref;
35 35
 //  var $_block_counter = array();
@@ -60,9 +60,9 @@  discard block
 block discarded – undo
60 60
   var $parsed = false;
61 61
 
62 62
   /**
63
-  * Set template location
64
-  * @access public
65
-  */
63
+   * Set template location
64
+   * @access public
65
+   */
66 66
   function set_template()
67 67
   {
68 68
     global $phpbb_root_path, $user;
@@ -101,9 +101,9 @@  discard block
 block discarded – undo
101 101
   }
102 102
 
103 103
   /**
104
-  * Set custom template location (able to use directory outside of phpBB)
105
-  * @access public
106
-  */
104
+   * Set custom template location (able to use directory outside of phpBB)
105
+   * @access public
106
+   */
107 107
   function set_custom_template($template_path, $template_name, $fallback_template_path = false)
108 108
   {
109 109
     global $phpbb_root_path, $user;
@@ -142,10 +142,10 @@  discard block
 block discarded – undo
142 142
   }
143 143
 
144 144
   /**
145
-  * Sets the template filenames for handles. $filename_array
146
-  * should be a hash of handle => filename pairs.
147
-  * @access public
148
-  */
145
+   * Sets the template filenames for handles. $filename_array
146
+   * should be a hash of handle => filename pairs.
147
+   * @access public
148
+   */
149 149
   function set_filenames($filename_array)
150 150
   {
151 151
     if (!is_array($filename_array))
@@ -172,9 +172,9 @@  discard block
 block discarded – undo
172 172
   }
173 173
 
174 174
   /**
175
-  * Destroy template data set
176
-  * @access public
177
-  */
175
+   * Destroy template data set
176
+   * @access public
177
+   */
178 178
   function destroy()
179 179
   {
180 180
     $this->_tpldata = array('.' => array(0 => array()));
@@ -182,9 +182,9 @@  discard block
 block discarded – undo
182 182
   }
183 183
 
184 184
   /**
185
-  * Reset/empty complete block
186
-  * @access public
187
-  */
185
+   * Reset/empty complete block
186
+   * @access public
187
+   */
188 188
   function destroy_block_vars($blockname)
189 189
   {
190 190
     if (strpos($blockname, '.') !== false)
@@ -212,9 +212,9 @@  discard block
 block discarded – undo
212 212
   }
213 213
 
214 214
   /**
215
-  * Display handle
216
-  * @access public
217
-  */
215
+   * Display handle
216
+   * @access public
217
+   */
218 218
   function display($handle, $include_once = true)
219 219
   {
220 220
     global $user, $phpbb_hook, $lang, $config;
@@ -248,9 +248,9 @@  discard block
 block discarded – undo
248 248
   }
249 249
 
250 250
   /**
251
-  * Display the handle and assign the output to a template variable or return the compiled result.
252
-  * @access public
253
-  */
251
+   * Display the handle and assign the output to a template variable or return the compiled result.
252
+   * @access public
253
+   */
254 254
   function assign_display($handle, $template_var = '', $return_content = true, $include_once = false)
255 255
   {
256 256
     ob_start();
@@ -268,9 +268,9 @@  discard block
 block discarded – undo
268 268
   }
269 269
 
270 270
   /**
271
-  * Load a compiled template if possible, if not, recompile it
272
-  * @access private
273
-  */
271
+   * Load a compiled template if possible, if not, recompile it
272
+   * @access private
273
+   */
274 274
   function _tpl_load(&$handle)
275 275
   {
276 276
     global $user, $config;
@@ -453,9 +453,9 @@  discard block
 block discarded – undo
453 453
   }
454 454
 
455 455
   /**
456
-  * Assign key variable pairs from an array
457
-  * @access public
458
-  */
456
+   * Assign key variable pairs from an array
457
+   * @access public
458
+   */
459 459
   function assign_vars($vararray)
460 460
   {
461 461
     foreach ($vararray as $key => $val)
@@ -467,9 +467,9 @@  discard block
 block discarded – undo
467 467
   }
468 468
 
469 469
   /**
470
-  * Assign a single variable to a single key
471
-  * @access public
472
-  */
470
+   * Assign a single variable to a single key
471
+   * @access public
472
+   */
473 473
   function assign_var($varname, $varval)
474 474
   {
475 475
     $this->_rootref[$varname] = $varval;
@@ -478,9 +478,9 @@  discard block
 block discarded – undo
478 478
   }
479 479
 
480 480
   /**
481
-  * Assign key variable pairs from an array to a specified block
482
-  * @access public
483
-  */
481
+   * Assign key variable pairs from an array to a specified block
482
+   * @access public
483
+   */
484 484
   function assign_block_vars($blockname, $vararray)
485 485
   {
486 486
     if (strpos($blockname, '.') !== false)
@@ -545,33 +545,33 @@  discard block
 block discarded – undo
545 545
   }
546 546
 
547 547
   /**
548
-  * Change already assigned key variable pair (one-dimensional - single loop entry)
549
-  *
550
-  * An example of how to use this function:
551
-  * {@example alter_block_array.php}
552
-  *
553
-  * @param  string  $blockname  the blockname, for example 'loop'
554
-  * @param  array $vararray the var array to insert/add or merge
555
-  * @param  mixed $key    Key to search for
556
-  *
557
-  * array: KEY => VALUE [the key/value pair to search for within the loop to determine the correct position]
558
-  *
559
-  * int: Position [the position to change or insert at directly given]
560
-  *
561
-  * If key is false the position is set to 0
562
-  * If key is true the position is set to the last entry
563
-  *
564
-  * @param  string  $mode   Mode to execute (valid modes are 'insert' and 'change')
565
-  *
566
-  * If insert, the vararray is inserted at the given position (position counting from zero).
567
-  * If change, the current block gets merged with the vararray (resulting in new key/value pairs be added and existing keys be replaced by the new value).
568
-  *
569
-  * Since counting begins by zero, inserting at the last position will result in this array: array(vararray, last positioned array)
570
-  * and inserting at position 1 will result in this array: array(first positioned array, vararray, following vars)
571
-  *
572
-  * @return bool false on error, true on success
573
-  * @access public
574
-  */
548
+   * Change already assigned key variable pair (one-dimensional - single loop entry)
549
+   *
550
+   * An example of how to use this function:
551
+   * {@example alter_block_array.php}
552
+   *
553
+   * @param  string  $blockname  the blockname, for example 'loop'
554
+   * @param  array $vararray the var array to insert/add or merge
555
+   * @param  mixed $key    Key to search for
556
+   *
557
+   * array: KEY => VALUE [the key/value pair to search for within the loop to determine the correct position]
558
+   *
559
+   * int: Position [the position to change or insert at directly given]
560
+   *
561
+   * If key is false the position is set to 0
562
+   * If key is true the position is set to the last entry
563
+   *
564
+   * @param  string  $mode   Mode to execute (valid modes are 'insert' and 'change')
565
+   *
566
+   * If insert, the vararray is inserted at the given position (position counting from zero).
567
+   * If change, the current block gets merged with the vararray (resulting in new key/value pairs be added and existing keys be replaced by the new value).
568
+   *
569
+   * Since counting begins by zero, inserting at the last position will result in this array: array(vararray, last positioned array)
570
+   * and inserting at position 1 will result in this array: array(first positioned array, vararray, following vars)
571
+   *
572
+   * @return bool false on error, true on success
573
+   * @access public
574
+   */
575 575
   function alter_block_array($blockname, $vararray, $key = false, $mode = 'insert')
576 576
   {
577 577
     if (strpos($blockname, '.') !== false)
@@ -655,9 +655,9 @@  discard block
 block discarded – undo
655 655
   }
656 656
 
657 657
   /**
658
-  * Include a separate template
659
-  * @access private
660
-  */
658
+   * Include a separate template
659
+   * @access private
660
+   */
661 661
   function _tpl_include($filename, $include = true)
662 662
   {
663 663
     global $lang, $config;
@@ -686,9 +686,9 @@  discard block
 block discarded – undo
686 686
   }
687 687
 
688 688
   /**
689
-  * Include a php-file
690
-  * @access private
691
-  */
689
+   * Include a php-file
690
+   * @access private
691
+   */
692 692
   function _php_include($filename)
693 693
   {
694 694
     global $phpbb_root_path;
@@ -705,9 +705,9 @@  discard block
 block discarded – undo
705 705
   }
706 706
 
707 707
   /**
708
-  * Assign key variable pairs from an array with block support
709
-  * @access public
710
-  */
708
+   * Assign key variable pairs from an array with block support
709
+   * @access public
710
+   */
711 711
   function assign_recursive($values, $name = '')
712 712
   {
713 713
     if(isset($values['.']))
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -628,7 +628,7 @@  discard block
 block discarded – undo
628 628
       // Re-position template blocks
629 629
       for ($i = sizeof($this->_tpldata[$blockname]); $i > $key; $i--)
630 630
       {
631
-        $this->_tpldata[$blockname][$i] = $this->_tpldata[$blockname][$i-1];
631
+        $this->_tpldata[$blockname][$i] = $this->_tpldata[$blockname][$i - 1];
632 632
         $this->_tpldata[$blockname][$i]['S_ROW_COUNT'] = $i;
633 633
       }
634 634
 
@@ -710,13 +710,13 @@  discard block
 block discarded – undo
710 710
   */
711 711
   function assign_recursive($values, $name = '')
712 712
   {
713
-    if(isset($values['.']))
713
+    if (isset($values['.']))
714 714
     {
715 715
       $values_extra = $values['.'];
716 716
       unset($values['.']);
717 717
     }
718 718
 
719
-    if(!$name)
719
+    if (!$name)
720 720
     {
721 721
       $this->assign_vars($values);
722 722
     }
@@ -725,12 +725,12 @@  discard block
 block discarded – undo
725 725
       $this->assign_block_vars($name, $values);
726 726
     }
727 727
 
728
-    if(isset($values_extra))
728
+    if (isset($values_extra))
729 729
     {
730
-      foreach($values_extra as $sub_array_name => $sub_array)
730
+      foreach ($values_extra as $sub_array_name => $sub_array)
731 731
       {
732 732
         $new_name = $name . ($name ? '.' : '') . $sub_array_name;
733
-        foreach($sub_array as $sub_element)
733
+        foreach ($sub_array as $sub_element)
734 734
         {
735 735
           $this->assign_recursive($sub_element, $new_name);
736 736
         }
Please login to merge, or discard this patch.
Braces   +13 added lines, -26 removed lines patch added patch discarded remove patch
@@ -89,8 +89,7 @@  discard block
 block discarded – undo
89 89
       {
90 90
         $this->inherit_root = $phpbb_root_path . 'styles/' . $user->theme['template_inherit_path'] . '/template';
91 91
       }
92
-    }
93
-    else
92
+    } else
94 93
     {
95 94
       trigger_error('Template path could not be found: styles/' . $user->theme['template_path'] . '/template', E_USER_ERROR);
96 95
     }
@@ -126,8 +125,7 @@  discard block
 block discarded – undo
126 125
 
127 126
       $this->inherit_root = $fallback_template_path;
128 127
       $this->orig_tpl_inherits_id = true;
129
-    }
130
-    else
128
+    } else
131 129
     {
132 130
       $this->orig_tpl_inherits_id = false;
133 131
     }
@@ -201,8 +199,7 @@  discard block
 block discarded – undo
201 199
       }
202 200
 
203 201
       unset($str[$blocks[$blockcount]]);
204
-    }
205
-    else
202
+    } else
206 203
     {
207 204
       // Top-level block.
208 205
       unset($this->_tpldata[$blockname]);
@@ -238,8 +235,7 @@  discard block
 block discarded – undo
238 235
     if ($filename = $this->_tpl_load($handle))
239 236
     {
240 237
       ($include_once) ? include_once($filename) : include($filename);
241
-    }
242
-    else
238
+    } else
243 239
     {
244 240
       eval(' ?>' . $this->compiled_code[$handle] . '<?php ');
245 241
     }
@@ -293,8 +289,7 @@  discard block
 block discarded – undo
293 289
     if (!file_exists($filename) || @filesize($filename) === 0)
294 290
     {
295 291
       $recompile = true;
296
-    }
297
-    else if ($config->load_tplcompile)
292
+    } else if ($config->load_tplcompile)
298 293
     {
299 294
       // No way around it: we need to check inheritance here
300 295
       if ($user->theme['template_inherits_id'] && !file_exists($this->files[$handle]))
@@ -382,15 +377,13 @@  discard block
 block discarded – undo
382 377
               $this->files[$row['template_filename']] = $file;
383 378
               $this->files_inherit[$row['template_filename']] = $file;
384 379
               $this->files_template[$row['template_filename']] = $user->theme['template_inherits_id'];
385
-            }
386
-            else if (isset($user->theme['template_inherits_id']) && $user->theme['template_inherits_id'])
380
+            } else if (isset($user->theme['template_inherits_id']) && $user->theme['template_inherits_id'])
387 381
             {
388 382
               // Ok, we have a situation. There is a file in the subtemplate, but nothing in the DB. We have to fix that.
389 383
               $force_reload = true;
390 384
               $this->files_template[$row['template_filename']] = $user->theme['template_inherits_id'];
391 385
             }
392
-          }
393
-          else
386
+          } else
394 387
           {
395 388
             $this->files_template[$row['template_filename']] = $user->theme['template_id'];
396 389
           }
@@ -400,8 +393,7 @@  discard block
 block discarded – undo
400 393
             if ($row['template_filename'] == $this->filename[$handle])
401 394
             {
402 395
               $compile->_tpl_load_file($handle, true);
403
-            }
404
-            else
396
+            } else
405 397
             {
406 398
               $this->files[$row['template_filename']] = $file;
407 399
               $this->filename[$row['template_filename']] = $row['template_filename'];
@@ -416,8 +408,7 @@  discard block
 block discarded – undo
416 408
           {
417 409
             $this->compiled_code[$handle] = $compile->compile(trim($row['template_data']));
418 410
             $compile->compile_write($handle, $this->compiled_code[$handle]);
419
-          }
420
-          else
411
+          } else
421 412
           {
422 413
             // Only bother compiling if it doesn't already exist
423 414
             if (!file_exists($this->cachepath . str_replace('/', '.', $row['template_filename']) . DOT_PHP_EX))
@@ -428,8 +419,7 @@  discard block
 block discarded – undo
428 419
             }
429 420
           }
430 421
         }
431
-      }
432
-      else
422
+      } else
433 423
       {
434 424
         $file = $this->root . '/' . $row['template_filename'];
435 425
 
@@ -517,8 +507,7 @@  discard block
 block discarded – undo
517 507
       // We're adding a new iteration to this block with the given
518 508
       // variable assignments.
519 509
       $str[$blocks[$blockcount]][] = $vararray;
520
-    }
521
-    else
510
+    } else
522 511
     {
523 512
       // Top-level block.
524 513
       $s_row_count = (isset($this->_tpldata[$blockname])) ? sizeof($this->_tpldata[$blockname]) : 0;
@@ -618,8 +607,7 @@  discard block
 block discarded – undo
618 607
         $key = sizeof($this->_tpldata[$blockname]);
619 608
         unset($this->_tpldata[$blockname][($key - 1)]['S_LAST_ROW']);
620 609
         $vararray['S_LAST_ROW'] = true;
621
-      }
622
-      else if ($key === 0)
610
+      } else if ($key === 0)
623 611
       {
624 612
         unset($this->_tpldata[$blockname][0]['S_FIRST_ROW']);
625 613
         $vararray['S_FIRST_ROW'] = true;
@@ -719,8 +707,7 @@  discard block
 block discarded – undo
719 707
     if(!$name)
720 708
     {
721 709
       $this->assign_vars($values);
722
-    }
723
-    else
710
+    } else
724 711
     {
725 712
       $this->assign_block_vars($name, $values);
726 713
     }
Please login to merge, or discard this patch.
includes/classes/user_options.php 2 patches
Doc Comments   +3 added lines patch added patch discarded remove patch
@@ -151,6 +151,9 @@
 block discarded – undo
151 151
   }
152 152
 
153 153
 
154
+  /**
155
+   * @param integer $user_id
156
+   */
154 157
   public function __construct($user_id) {
155 158
     $this->user_change($user_id);
156 159
   }
Please login to merge, or discard this patch.
Spacing   +30 added lines, -30 removed lines patch added patch discarded remove patch
@@ -116,8 +116,8 @@  discard block
 block discarded – undo
116 116
 
117 117
     $update_cache = false;
118 118
 
119
-    if(!empty($this->to_write)) {
120
-      foreach($this->to_write as $key => $cork) {
119
+    if (!empty($this->to_write)) {
120
+      foreach ($this->to_write as $key => $cork) {
121 121
         $value = is_array($this->data[$key]) ? serialize($this->data[$key]) : $this->data[$key]; // Сериализация для массивов при сохранении в БД
122 122
         $this->to_write[$key] = "({$this->user_id}, '" . db_escape($key) . "', '" . db_escape($value) . "')";
123 123
       }
@@ -128,19 +128,19 @@  discard block
 block discarded – undo
128 128
       $update_cache = true;
129 129
     }
130 130
 
131
-    if(!empty($this->to_delete)) {
132
-      foreach($this->to_delete as $key => &$value) {
133
-        $value = is_string($key) ? "'". db_escape($key) . "'" : $key;
131
+    if (!empty($this->to_delete)) {
132
+      foreach ($this->to_delete as $key => &$value) {
133
+        $value = is_string($key) ? "'" . db_escape($key) . "'" : $key;
134 134
       }
135 135
 
136
-      doquery("DELETE FROM {{player_options}} WHERE `player_id` = {$this->user_id} AND `option_id` IN (". implode(',', $this->to_delete) . ") ");
136
+      doquery("DELETE FROM {{player_options}} WHERE `player_id` = {$this->user_id} AND `option_id` IN (" . implode(',', $this->to_delete) . ") ");
137 137
       // pdump("DELETE FROM {{player_options}} WHERE `player_id` = {$this->user_id} AND `option_id` IN (". implode(',', $this->to_delete) . ") ");
138 138
 
139 139
       $this->to_delete = array();
140 140
       $update_cache = true;
141 141
     }
142 142
 
143
-    if($update_cache) {
143
+    if ($update_cache) {
144 144
       global $sn_cache;
145 145
 
146 146
       $field_name = $this->cached_name();
@@ -167,7 +167,7 @@  discard block
 block discarded – undo
167 167
   protected function load() {
168 168
     global $sn_cache;
169 169
 
170
-    if($this->loaded) {
170
+    if ($this->loaded) {
171 171
       return;
172 172
     }
173 173
 
@@ -175,7 +175,7 @@  discard block
 block discarded – undo
175 175
     $this->to_write = array();
176 176
     $this->to_delete = array();
177 177
 
178
-    if(!$this->user_id) {
178
+    if (!$this->user_id) {
179 179
       $this->loaded = true;
180 180
       return;
181 181
     }
@@ -183,13 +183,13 @@  discard block
 block discarded – undo
183 183
     $field_name = $this->cached_name();
184 184
     $a_data = $sn_cache->$field_name;
185 185
 
186
-    if(!empty($a_data)) {
186
+    if (!empty($a_data)) {
187 187
       $this->data = array_replace_recursive($this->data, $a_data);
188 188
       return;
189 189
     }
190 190
 
191 191
     $query = doquery("SELECT * FROM `{{player_options}}` WHERE `player_id` = {$this->user_id} FOR UPDATE");
192
-    while($row = db_fetch($query)) {
192
+    while ($row = db_fetch($query)) {
193 193
       // $this->data[$row['option_id']] = $row['value'];
194 194
       $this->data[$row['option_id']] = is_string($row['value']) && ($temp = unserialize($row['value'])) !== false ? $temp : $row['value']; // Десериализация
195 195
     }
@@ -269,14 +269,14 @@  discard block
 block discarded – undo
269 269
     // Если в массиве индекса только один элемент - значит это просто индекс
270 270
     is_array($option_id) && count($option_id) == 1 ? $option_id = reset($option_id) : false;
271 271
 
272
-    if(!isset($this->data[is_array($option_id) ? reset($option_id) : $option_id])) {
272
+    if (!isset($this->data[is_array($option_id) ? reset($option_id) : $option_id])) {
273 273
       $this->load();
274 274
     }
275 275
 
276
-    if(is_array($option_id)) {
276
+    if (is_array($option_id)) {
277 277
       $result = $this->data;
278
-      foreach($option_id as $sub_key) {
279
-        if(!isset($result) || !isset($result[$sub_key])) {
278
+      foreach ($option_id as $sub_key) {
279
+        if (!isset($result) || !isset($result[$sub_key])) {
280 280
           $result = null;
281 281
           break;
282 282
         }
@@ -296,12 +296,12 @@  discard block
 block discarded – undo
296 296
   public function __set($option, $value = null) {
297 297
     global $sn_cache;
298 298
 
299
-    if(empty($option) || !$this->user_id) {
299
+    if (empty($option) || !$this->user_id) {
300 300
       return;
301 301
     }
302 302
 
303 303
     // Если в массиве индекса только один элемент - значит это просто индекс
304
-    if(is_array($option) && count($option) == 1) {
304
+    if (is_array($option) && count($option) == 1) {
305 305
       // Разворачиваем его в индекс
306 306
       $option = array(reset($option) => $value);
307 307
       unset($value);
@@ -310,13 +310,13 @@  discard block
 block discarded – undo
310 310
 
311 311
     $to_write = array();
312 312
     // Адресация многомерного массива через массив индексов в $option
313
-    if(is_array($option) && isset($value)) {
313
+    if (is_array($option) && isset($value)) {
314 314
       $a_data = &$this->data;
315
-      foreach($option as $option_id) {
315
+      foreach ($option as $option_id) {
316 316
         !is_array($a_data[$option_id]) ? $a_data[$option_id] = array() : false;
317 317
         $a_data = &$a_data[$option_id];
318 318
       }
319
-      if($a_data != $value) {
319
+      if ($a_data != $value) {
320 320
         $a_data = $value;
321 321
         $to_write[reset($option)] = null;
322 322
       }
@@ -324,10 +324,10 @@  discard block
 block discarded – undo
324 324
       // Пакетная запись из массива ключ -> значение
325 325
       !is_array($option) ? $option = array($option => $value) : false;
326 326
 
327
-      foreach($option as $option_id => $option_value) {
328
-        if($this->data[$option_id] !== $option_value) {
327
+      foreach ($option as $option_id => $option_value) {
328
+        if ($this->data[$option_id] !== $option_value) {
329 329
           // TODO - вынести отдельно в обработчик
330
-          if($option_id == PLAYER_OPTION_MENU_HIDE_SHOW_BUTTON &&  $option_value == PLAYER_OPTION_MENU_HIDE_SHOW_BUTTON_HIDDEN) {
330
+          if ($option_id == PLAYER_OPTION_MENU_HIDE_SHOW_BUTTON && $option_value == PLAYER_OPTION_MENU_HIDE_SHOW_BUTTON_HIDDEN) {
331 331
             sn_setcookie(SN_COOKIE . '_menu_hidden', '0', time() - PERIOD_WEEK, SN_ROOT_RELATIVE);
332 332
           }
333 333
 
@@ -337,11 +337,11 @@  discard block
 block discarded – undo
337 337
       }
338 338
     }
339 339
 
340
-    if(!empty($to_write)) {
340
+    if (!empty($to_write)) {
341 341
       $field_name = $this->cached_name();
342 342
       $sn_cache->$field_name = $this->data;
343 343
 
344
-      foreach($to_write as $option_id => &$option_value) {
344
+      foreach ($to_write as $option_id => &$option_value) {
345 345
         $option_value = is_array($this->data[$option_id]) ? serialize($this->data[$option_id]) : $this->data[$option_id]; // Сериализация для массивов при сохранении в БД
346 346
         $to_write[$option_id] = "({$this->user_id}, '" . db_escape($option_id) . "', '" . db_escape($option_value) . "')";
347 347
       }
@@ -353,26 +353,26 @@  discard block
 block discarded – undo
353 353
   protected function load() {
354 354
     global $sn_cache;
355 355
 
356
-    if($this->loaded) {
356
+    if ($this->loaded) {
357 357
       return;
358 358
     }
359 359
 
360 360
     $this->data = $this->defaults;
361 361
 
362
-    if(!$this->user_id) {
362
+    if (!$this->user_id) {
363 363
       return;
364 364
     }
365 365
 
366 366
     $field_name = $this->cached_name();
367 367
     $a_data = $sn_cache->$field_name;
368 368
 
369
-    if(!empty($a_data)) {
369
+    if (!empty($a_data)) {
370 370
       $this->data = array_replace($this->data, $a_data);
371 371
       return;
372 372
     }
373 373
 
374 374
     $query = doquery("SELECT * FROM `{{player_options}}` WHERE `player_id` = {$this->user_id} FOR UPDATE");
375
-    while($row = db_fetch($query)) {
375
+    while ($row = db_fetch($query)) {
376 376
       // $this->data[$row['option_id']] = $row['value'];
377 377
       $this->data[$row['option_id']] = is_string($row['value']) && ($temp = unserialize($row['value'])) !== false ? $temp : $row['value']; // Десериализация
378 378
     }
@@ -388,7 +388,7 @@  discard block
 block discarded – undo
388 388
     return $this->__get($offset);
389 389
   }
390 390
   public function offsetSet($offset, $value) {
391
-    if(!is_null($offset)) {
391
+    if (!is_null($offset)) {
392 392
       // $this->data[$offset] = $value;
393 393
       $this->__set($offset, $value);
394 394
     } else {
Please login to merge, or discard this patch.
includes/db.php 3 patches
Doc Comments   +8 added lines, -5 removed lines patch added patch discarded remove patch
@@ -11,6 +11,9 @@  discard block
 block discarded – undo
11 11
 
12 12
 require_once('db/db_queries.php');
13 13
 
14
+/**
15
+ * @param string $tablename
16
+ */
14 17
 function db_change_units_perform($query, $tablename, $object_id) {
15 18
   $query = implode(',', $query);
16 19
   if($query && $object_id) {
@@ -63,6 +66,9 @@  discard block
 block discarded – undo
63 66
   db_change_units_perform($query[LOC_USER], 'users', $user['id']);
64 67
   db_change_units_perform($query[LOC_PLANET], 'planets', $planet['id']);
65 68
 }
69
+/**
70
+ * @param string $table
71
+ */
66 72
 function sn_db_perform($table, $values, $type = 'insert', $options = false) {
67 73
   $mass_perform = false;
68 74
 
@@ -171,11 +177,8 @@  discard block
 block discarded – undo
171 177
 /**
172 178
  * Функция проверяет статус транзакции
173 179
  *
174
- * @param null|true|false $status Должна ли быть запущена транзакция в момент проверки
175
- *   <p>null - транзакция НЕ должна быть запущена</p>
176
- *   <p>true - транзакция должна быть запущена - для совместимости с $for_update</p>
177
- *   <p>false - всё равно - для совместимости с $for_update</p>
178
- * @return bool Текущий статус транзакции
180
+ * @param boolean $transaction_should_be_started
181
+ * @return null|boolean Текущий статус транзакции
179 182
  */
180 183
 function sn_db_transaction_check($transaction_should_be_started = null) {
181 184
   return classSupernova::db_transaction_check($transaction_should_be_started);
Please login to merge, or discard this patch.
Indentation   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -169,14 +169,14 @@
 block discarded – undo
169 169
   return classSupernova::db_changeset_apply($db_changeset);
170 170
 }
171 171
 /**
172
- * Функция проверяет статус транзакции
173
- *
174
- * @param null|true|false $status Должна ли быть запущена транзакция в момент проверки
175
- *   <p>null - транзакция НЕ должна быть запущена</p>
176
- *   <p>true - транзакция должна быть запущена - для совместимости с $for_update</p>
177
- *   <p>false - всё равно - для совместимости с $for_update</p>
178
- * @return bool Текущий статус транзакции
179
- */
172
+   * Функция проверяет статус транзакции
173
+   *
174
+   * @param null|true|false $status Должна ли быть запущена транзакция в момент проверки
175
+   *   <p>null - транзакция НЕ должна быть запущена</p>
176
+   *   <p>true - транзакция должна быть запущена - для совместимости с $for_update</p>
177
+   *   <p>false - всё равно - для совместимости с $for_update</p>
178
+   * @return bool Текущий статус транзакции
179
+   */
180 180
 function sn_db_transaction_check($transaction_should_be_started = null) {
181 181
   return classSupernova::db_transaction_check($transaction_should_be_started);
182 182
 }
Please login to merge, or discard this patch.
Spacing   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -5,7 +5,7 @@  discard block
 block discarded – undo
5 5
  * @copyright 2008-2015 Gorlum for Project "SuperNova.WS"
6 6
  */
7 7
 
8
-if(!defined('INSIDE')) {
8
+if (!defined('INSIDE')) {
9 9
   die();
10 10
 }
11 11
 
@@ -13,7 +13,7 @@  discard block
 block discarded – undo
13 13
 
14 14
 function db_change_units_perform($query, $tablename, $object_id) {
15 15
   $query = implode(',', $query);
16
-  if($query && $object_id) {
16
+  if ($query && $object_id) {
17 17
     return classSupernova::db_upd_record_by_id($tablename == 'users' ? LOC_USER : LOC_PLANET, $object_id, $query);
18 18
     // return doquery("UPDATE {{{$tablename}}} SET {$query} WHERE `id` = '{$object_id}' LIMIT 1;");
19 19
   }
@@ -30,15 +30,15 @@  discard block
 block discarded – undo
30 30
 
31 31
   $group = sn_get_groups('resources_loot');
32 32
 
33
-  foreach($unit_list as $unit_id => $unit_amount) {
34
-    if(!in_array($unit_id, $group)) {
33
+  foreach ($unit_list as $unit_id => $unit_amount) {
34
+    if (!in_array($unit_id, $group)) {
35 35
       // TODO - remove later
36 36
       print('<h1>СООБЩИТЕ ЭТО АДМИНУ: db_change_units() вызван для не-ресурсов!</h1>');
37 37
       pdump(debug_backtrace());
38 38
       die('db_change_units() вызван для не-ресурсов!');
39 39
     }
40 40
 
41
-    if(!$unit_amount) {
41
+    if (!$unit_amount) {
42 42
       continue;
43 43
     }
44 44
 
@@ -47,7 +47,7 @@  discard block
 block discarded – undo
47 47
     $unit_location = sys_get_unit_location($user, $planet, $unit_id);
48 48
 
49 49
     // Changing value in object
50
-    switch($unit_location) {
50
+    switch ($unit_location) {
51 51
       case LOC_USER:
52 52
         $user[$unit_db_name] += $unit_amount;
53 53
         break;
@@ -69,23 +69,23 @@  discard block
 block discarded – undo
69 69
   $field_set = '';
70 70
   $value_set = '';
71 71
 
72
-  switch($type) {
72
+  switch ($type) {
73 73
     case 'delete':
74 74
       $query = 'DELETE FROM';
75 75
       break;
76 76
 
77 77
     case 'insert':
78 78
       $query = 'INSERT INTO';
79
-      if(isset($options['__multi'])) {
79
+      if (isset($options['__multi'])) {
80 80
         // Here we generate mass-insert set
81 81
         break;
82 82
       }
83 83
     case 'update':
84
-      if(!$query) {
84
+      if (!$query) {
85 85
         $query = 'UPDATE';
86 86
       }
87 87
 
88
-      foreach($values as $field => &$value) {
88
+      foreach ($values as $field => &$value) {
89 89
         $value_type = gettype($value);
90 90
         if ($value_type == 'string') {
91 91
           $value = "'" . db_escape($value) . "'";
@@ -113,12 +113,12 @@  discard block
 block discarded – undo
113 113
   $field_set['__IS_SAFE'] = true;
114 114
 }
115 115
 function sn_db_field_set_make_safe($field_set, $serialize = false) {
116
-  if(!is_array($field_set)) {
116
+  if (!is_array($field_set)) {
117 117
     die('$field_set is not an array!');
118 118
   }
119 119
 
120 120
   $result = array();
121
-  foreach($field_set as $field => $value) {
121
+  foreach ($field_set as $field => $value) {
122 122
     $field = db_escape(trim($field));
123 123
     switch (true) {
124 124
       case is_int($value):
Please login to merge, or discard this patch.
includes/db/db_queries.php 2 patches
Doc Comments   +5 added lines patch added patch discarded remove patch
@@ -337,6 +337,11 @@
 block discarded – undo
337 337
  */
338 338
 // OK v4
339 339
 // TODO - вынести в отдельный класс
340
+/**
341
+ * @param string $db_id_field_name
342
+ * @param string $db_table_name
343
+ * @param string $db_value_field_name
344
+ */
340 345
 function db_get_set_unique_id_value($current_value_unsafe, $db_id_field_name, $db_table_name, $db_value_field_name) {
341 346
   $current_value_safe = db_escape($current_value_unsafe);
342 347
   $value_id = doquery("SELECT `{$db_id_field_name}` AS id_field FROM {{{$db_table_name}}} WHERE `{$db_value_field_name}` = '{$current_value_safe}' LIMIT 1 FOR UPDATE", true);
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -111,7 +111,7 @@  discard block
 block discarded – undo
111 111
 
112 112
 function db_unit_records_sum($unit_id, $user_skip_list_unit)
113 113
 {
114
-  return doquery (
114
+  return doquery(
115 115
     "SELECT unit_player_id, username, sum(unit_level) as unit_level
116 116
           FROM {{unit}} JOIN {{users}} AS u ON u.id = unit_player_id
117 117
           WHERE unit_player_id != 0 AND unit_snid = {$unit_id} {$user_skip_list_unit}
@@ -123,7 +123,7 @@  discard block
 block discarded – undo
123 123
 
124 124
 function db_unit_records_plain($unit_id, $user_skip_list_unit)
125 125
 {
126
-  return doquery (
126
+  return doquery(
127 127
     "SELECT unit_player_id, username, unit_level
128 128
           FROM {{unit}} JOIN {{users}} AS u ON u.id = unit_player_id
129 129
           WHERE unit_player_id != 0 AND unit_snid = {$unit_id} {$user_skip_list_unit}
@@ -134,7 +134,7 @@  discard block
 block discarded – undo
134 134
 
135 135
 function db_stat_list_statistic($who, $is_common_stat, $Rank, $start, $source = false) {
136 136
 // pdump($source);
137
-  if(!$source) {
137
+  if (!$source) {
138 138
     $source = array(
139 139
       'statpoints' => 'statpoints',
140 140
       'users' => 'users',
@@ -155,8 +155,8 @@  discard block
 block discarded – undo
155 155
     );
156 156
   }
157 157
 // pdump($source);
158
-  if($who == 1) {
159
-    if($is_common_stat) { // , UNIX_TIMESTAMP(CONCAT(YEAR(CURRENT_DATE), DATE_FORMAT(`user_birthday`, '-%m-%d'))) AS `nearest_birthday`
158
+  if ($who == 1) {
159
+    if ($is_common_stat) { // , UNIX_TIMESTAMP(CONCAT(YEAR(CURRENT_DATE), DATE_FORMAT(`user_birthday`, '-%m-%d'))) AS `nearest_birthday`
160 160
       $query_str =
161 161
         "SELECT
162 162
       @rownum:=@rownum+1 rownum, subject.{$source['id']} as `id`, sp.{$Rank}_rank as rank, sp.{$Rank}_old_rank as rank_old, sp.{$Rank}_points as points, subject.{$source['username']} as `name`, subject.*
@@ -170,7 +170,7 @@  discard block
 block discarded – undo
170 170
     ORDER BY
171 171
       sp.`{$Rank}_rank`, subject.{$source['id']}
172 172
     LIMIT
173
-      ". $start .",100;";
173
+      " . $start . ",100;";
174 174
     } else { // , UNIX_TIMESTAMP(CONCAT(YEAR(CURRENT_DATE), DATE_FORMAT(`user_birthday`, '-%m-%d'))) AS `nearest_birthday`
175 175
       $query_str =
176 176
         "SELECT
@@ -183,7 +183,7 @@  discard block
 block discarded – undo
183 183
     ORDER BY
184 184
       subject.{$Rank} DESC, subject.{$source['id']}
185 185
     LIMIT
186
-      ". $start .",100;";
186
+      " . $start . ",100;";
187 187
     }
188 188
   } else {
189 189
     // TODO
@@ -200,7 +200,7 @@  discard block
 block discarded – undo
200 200
   ORDER BY
201 201
     sp.`{$Rank}_rank`, subject.id
202 202
   LIMIT
203
-    ". $start .",100;";
203
+    " . $start . ",100;";
204 204
   }
205 205
 
206 206
   return doquery($query_str);
@@ -340,7 +340,7 @@  discard block
 block discarded – undo
340 340
 function db_get_set_unique_id_value($current_value_unsafe, $db_id_field_name, $db_table_name, $db_value_field_name) {
341 341
   $current_value_safe = db_escape($current_value_unsafe);
342 342
   $value_id = doquery("SELECT `{$db_id_field_name}` AS id_field FROM {{{$db_table_name}}} WHERE `{$db_value_field_name}` = '{$current_value_safe}' LIMIT 1 FOR UPDATE", true);
343
-  if(!isset($value_id['id_field']) || !$value_id['id_field']) {
343
+  if (!isset($value_id['id_field']) || !$value_id['id_field']) {
344 344
     doquery("INSERT INTO {{{$db_table_name}}} (`{$db_value_field_name}`) VALUES ('{$current_value_safe}');");
345 345
     $variable_id = db_insert_id();
346 346
   } else {
Please login to merge, or discard this patch.
includes/db/db_queries_planets.php 3 patches
Doc Comments   +15 added lines patch added patch discarded remove patch
@@ -4,11 +4,20 @@  discard block
 block discarded – undo
4 4
 {
5 5
   return classSupernova::db_get_record_by_id(LOC_PLANET, $planet_id, $for_update, $fields);
6 6
 }
7
+/**
8
+ * @param integer $galaxy
9
+ * @param integer $system
10
+ * @param integer $planet
11
+ * @param integer $planet_type
12
+ */
7 13
 function db_planet_by_gspt_safe($galaxy, $system, $planet, $planet_type, $for_update = false, $fields = '*')
8 14
 {
9 15
   return classSupernova::db_get_record_list(LOC_PLANET,
10 16
     "{{planets}}.`galaxy` = {$galaxy} AND {{planets}}.`system` = {$system} AND {{planets}}.`planet` = {$planet} AND {{planets}}.`planet_type` = {$planet_type}", true);
11 17
 }
18
+/**
19
+ * @param integer $planet_type
20
+ */
12 21
 function db_planet_by_gspt($galaxy, $system, $planet, $planet_type, $for_update = false, $fields = '*')
13 22
 {
14 23
   $galaxy = intval($galaxy);
@@ -79,6 +88,9 @@  discard block
 block discarded – undo
79 88
   return classSupernova::db_get_record_list(LOC_PLANET,
80 89
     "`id_owner` = '{$user_row['id']}' {$conditions} ORDER BY {$order_by}");
81 90
 }
91
+/**
92
+ * @param integer $planet_id
93
+ */
82 94
 function db_planet_list_by_user_or_planet($user_id, $planet_id) {
83 95
   if(!($user_id = idval($user_id)) && !($planet_id = idval($planet_id))) return false;
84 96
 
@@ -92,6 +104,9 @@  discard block
 block discarded – undo
92 104
   if(!($planet_id = idval($planet_id))) return false;
93 105
   return classSupernova::db_upd_record_by_id(LOC_PLANET, $planet_id, $set);
94 106
 }
107
+/**
108
+ * @param integer $ui_planet_type
109
+ */
95 110
 function db_planet_set_by_gspt($ui_galaxy, $ui_system, $ui_planet, $ui_planet_type = PT_ALL, $set)
96 111
 {
97 112
   if(!($set = trim($set))) return false;
Please login to merge, or discard this patch.
Spacing   +12 added lines, -13 removed lines patch added patch discarded remove patch
@@ -23,8 +23,7 @@  discard block
 block discarded – undo
23 23
   $galaxy = isset($vector[$prefix . 'galaxy']) ? intval($vector[$prefix . 'galaxy']) : 0;
24 24
   $system = isset($vector[$prefix . 'system']) ? intval($vector[$prefix . 'system']) : 0;
25 25
   $planet = isset($vector[$prefix . 'planet']) ? intval($vector[$prefix . 'planet']) : 0;
26
-  $planet_type = isset($vector[$prefix . 'planet_type']) ? intval($vector[$prefix . 'planet_type']) :
27
-    (isset($vector[$prefix . 'type']) ? intval($vector[$prefix . 'type']) : 0);
26
+  $planet_type = isset($vector[$prefix . 'planet_type']) ? intval($vector[$prefix . 'planet_type']) : (isset($vector[$prefix . 'type']) ? intval($vector[$prefix . 'type']) : 0);
28 27
   $planet_type = $planet_type == PT_DEBRIS ? PT_PLANET : $planet_type;
29 28
 
30 29
   return db_planet_by_gspt_safe($galaxy, $system, $planet, $planet_type, $for_update, $fields);
@@ -32,14 +31,14 @@  discard block
 block discarded – undo
32 31
 function db_planet_by_parent($parent_id, $for_update = false, $fields = '*')
33 32
 {
34 33
   //if(!($parent_id = intval($parent_id))) return false;
35
-  if(!($parent_id = idval($parent_id))) return false;
34
+  if (!($parent_id = idval($parent_id))) return false;
36 35
   return classSupernova::db_get_record_list(LOC_PLANET,
37 36
     "`parent_planet` = {$parent_id} AND `planet_type` = " . PT_MOON, true);
38 37
 }
39 38
 function db_planet_by_id_and_owner($planet_id, $owner_id, $for_update = false, $fields = '*')
40 39
 {
41 40
   //if(!($planet_id = intval($planet_id)) || !($owner_id = intval($owner_id))) return false;
42
-  if(!($planet_id = idval($planet_id)) || !($owner_id = idval($owner_id))) return false;
41
+  if (!($planet_id = idval($planet_id)) || !($owner_id = idval($owner_id))) return false;
43 42
   return classSupernova::db_get_record_list(LOC_PLANET,
44 43
     "`id` = {$planet_id} AND `id_owner` = {$owner_id}", true);
45 44
 }
@@ -48,7 +47,7 @@  discard block
 block discarded – undo
48 47
 function db_planet_list_moon_other($user_id, $this_moon_id)
49 48
 {
50 49
   // if(!($user_id = intval($user_id)) || !($this_moon_id = intval($this_moon_id))) return false;
51
-  if(!($user_id = idval($user_id)) || !($this_moon_id = idval($this_moon_id))) return false;
50
+  if (!($user_id = idval($user_id)) || !($this_moon_id = idval($this_moon_id))) return false;
52 51
   return classSupernova::db_get_record_list(LOC_PLANET,
53 52
     "`planet_type` = " . PT_MOON . " AND `id_owner` = {$user_id} AND `id` != {$this_moon_id}");
54 53
 }
@@ -61,7 +60,7 @@  discard block
 block discarded – undo
61 60
 }
62 61
 
63 62
 function db_planet_list_sorted($user_row, $skip_planet_id = false, $field_list = '', $conditions = '') {
64
-  if(!is_array($user_row)) return false;
63
+  if (!is_array($user_row)) return false;
65 64
   // $field_list = $field_list != '*' ? "{{planets}}.`id`, `name`, `image`, {{planets}}.`galaxy`, {{planets}}.`system`, {{planets}}.`planet`, `planet_type`{$field_list}" : $field_list;
66 65
   $conditions .= $skip_planet_id ? " AND `id` <> {$skip_planet_id} " : '';
67 66
 
@@ -80,7 +79,7 @@  discard block
 block discarded – undo
80 79
     "`id_owner` = '{$user_row['id']}' {$conditions} ORDER BY {$order_by}");
81 80
 }
82 81
 function db_planet_list_by_user_or_planet($user_id, $planet_id) {
83
-  if(!($user_id = idval($user_id)) && !($planet_id = idval($planet_id))) return false;
82
+  if (!($user_id = idval($user_id)) && !($planet_id = idval($planet_id))) return false;
84 83
 
85 84
   return classSupernova::db_get_record_list(LOC_PLANET,
86 85
     $planet_id = idval($planet_id) ? "{{planets}}.`id` = {$planet_id}" : "`id_owner` = {$user_id}", $planet_id);
@@ -89,12 +88,12 @@  discard block
 block discarded – undo
89 88
 function db_planet_set_by_id($planet_id, $set)
90 89
 {
91 90
   // if(!($planet_id = intval($planet_id))) return false;
92
-  if(!($planet_id = idval($planet_id))) return false;
91
+  if (!($planet_id = idval($planet_id))) return false;
93 92
   return classSupernova::db_upd_record_by_id(LOC_PLANET, $planet_id, $set);
94 93
 }
95 94
 function db_planet_set_by_gspt($ui_galaxy, $ui_system, $ui_planet, $ui_planet_type = PT_ALL, $set)
96 95
 {
97
-  if(!($set = trim($set))) return false;
96
+  if (!($set = trim($set))) return false;
98 97
 
99 98
   $si_galaxy = intval($ui_galaxy);
100 99
   $si_system = intval($ui_system);
@@ -106,13 +105,13 @@  discard block
 block discarded – undo
106 105
 function db_planet_set_by_parent($ui_parent_id, $ss_set)
107 106
 {
108 107
   //if(!($si_parent_id = intval($ui_parent_id)) || !($ss_set = trim($ss_set))) return false;
109
-  if(!($si_parent_id = idval($ui_parent_id)) || !($ss_set = trim($ss_set))) return false;
108
+  if (!($si_parent_id = idval($ui_parent_id)) || !($ss_set = trim($ss_set))) return false;
110 109
   return classSupernova::db_upd_record_list(LOC_PLANET, "`parent_planet` = {$si_parent_id}", $ss_set);
111 110
 }
112 111
 function db_planet_set_by_owner($ui_owner_id, $ss_set)
113 112
 {
114 113
   //if(!($si_owner_id = intval($ui_owner_id)) || !($ss_set = trim($ss_set))) return false;
115
-  if(!($si_owner_id = idval($ui_owner_id)) || !($ss_set = trim($ss_set))) return false;
114
+  if (!($si_owner_id = idval($ui_owner_id)) || !($ss_set = trim($ss_set))) return false;
116 115
   return classSupernova::db_upd_record_list(LOC_PLANET, "`id_owner` = {$si_owner_id}", $ss_set);
117 116
 }
118 117
 
@@ -120,7 +119,7 @@  discard block
 block discarded – undo
120 119
 function db_planet_delete_by_id($planet_id)
121 120
 {
122 121
   // if(!($planet_id = intval($planet_id))) return false;
123
-  if(!($planet_id = idval($planet_id))) return false;
122
+  if (!($planet_id = idval($planet_id))) return false;
124 123
   classSupernova::db_del_record_by_id(LOC_PLANET, $planet_id);
125 124
   classSupernova::db_del_record_list(LOC_UNIT, "`unit_location_type` = " . LOC_PLANET . " AND `unit_location_id` = " . $planet_id);
126 125
   // Очереди очистятся автоматически по FOREIGN KEY
@@ -129,7 +128,7 @@  discard block
 block discarded – undo
129 128
 function db_planet_list_delete_by_owner($ui_owner_id)
130 129
 {
131 130
   // if(!($si_owner_id = intval($ui_owner_id))) return false;
132
-  if(!($si_owner_id = idval($ui_owner_id))) return false;
131
+  if (!($si_owner_id = idval($ui_owner_id))) return false;
133 132
   classSupernova::db_del_record_list(LOC_PLANET, "`id_owner` = {$si_owner_id}");
134 133
   classSupernova::db_del_record_list(LOC_UNIT, "`unit_location_type` = " . LOC_PLANET . " AND `unit_player_id` = " . $si_owner_id);
135 134
   // Очереди очистятся автоматически по FOREIGN KEY
Please login to merge, or discard this patch.
Braces   +33 added lines, -11 removed lines patch added patch discarded remove patch
@@ -32,14 +32,18 @@  discard block
 block discarded – undo
32 32
 function db_planet_by_parent($parent_id, $for_update = false, $fields = '*')
33 33
 {
34 34
   //if(!($parent_id = intval($parent_id))) return false;
35
-  if(!($parent_id = idval($parent_id))) return false;
35
+  if(!($parent_id = idval($parent_id))) {
36
+    return false;
37
+  }
36 38
   return classSupernova::db_get_record_list(LOC_PLANET,
37 39
     "`parent_planet` = {$parent_id} AND `planet_type` = " . PT_MOON, true);
38 40
 }
39 41
 function db_planet_by_id_and_owner($planet_id, $owner_id, $for_update = false, $fields = '*')
40 42
 {
41 43
   //if(!($planet_id = intval($planet_id)) || !($owner_id = intval($owner_id))) return false;
42
-  if(!($planet_id = idval($planet_id)) || !($owner_id = idval($owner_id))) return false;
44
+  if(!($planet_id = idval($planet_id)) || !($owner_id = idval($owner_id))) {
45
+    return false;
46
+  }
43 47
   return classSupernova::db_get_record_list(LOC_PLANET,
44 48
     "`id` = {$planet_id} AND `id_owner` = {$owner_id}", true);
45 49
 }
@@ -48,7 +52,9 @@  discard block
 block discarded – undo
48 52
 function db_planet_list_moon_other($user_id, $this_moon_id)
49 53
 {
50 54
   // if(!($user_id = intval($user_id)) || !($this_moon_id = intval($this_moon_id))) return false;
51
-  if(!($user_id = idval($user_id)) || !($this_moon_id = idval($this_moon_id))) return false;
55
+  if(!($user_id = idval($user_id)) || !($this_moon_id = idval($this_moon_id))) {
56
+    return false;
57
+  }
52 58
   return classSupernova::db_get_record_list(LOC_PLANET,
53 59
     "`planet_type` = " . PT_MOON . " AND `id_owner` = {$user_id} AND `id` != {$this_moon_id}");
54 60
 }
@@ -61,7 +67,9 @@  discard block
 block discarded – undo
61 67
 }
62 68
 
63 69
 function db_planet_list_sorted($user_row, $skip_planet_id = false, $field_list = '', $conditions = '') {
64
-  if(!is_array($user_row)) return false;
70
+  if(!is_array($user_row)) {
71
+    return false;
72
+  }
65 73
   // $field_list = $field_list != '*' ? "{{planets}}.`id`, `name`, `image`, {{planets}}.`galaxy`, {{planets}}.`system`, {{planets}}.`planet`, `planet_type`{$field_list}" : $field_list;
66 74
   $conditions .= $skip_planet_id ? " AND `id` <> {$skip_planet_id} " : '';
67 75
 
@@ -80,7 +88,9 @@  discard block
 block discarded – undo
80 88
     "`id_owner` = '{$user_row['id']}' {$conditions} ORDER BY {$order_by}");
81 89
 }
82 90
 function db_planet_list_by_user_or_planet($user_id, $planet_id) {
83
-  if(!($user_id = idval($user_id)) && !($planet_id = idval($planet_id))) return false;
91
+  if(!($user_id = idval($user_id)) && !($planet_id = idval($planet_id))) {
92
+    return false;
93
+  }
84 94
 
85 95
   return classSupernova::db_get_record_list(LOC_PLANET,
86 96
     $planet_id = idval($planet_id) ? "{{planets}}.`id` = {$planet_id}" : "`id_owner` = {$user_id}", $planet_id);
@@ -89,12 +99,16 @@  discard block
 block discarded – undo
89 99
 function db_planet_set_by_id($planet_id, $set)
90 100
 {
91 101
   // if(!($planet_id = intval($planet_id))) return false;
92
-  if(!($planet_id = idval($planet_id))) return false;
102
+  if(!($planet_id = idval($planet_id))) {
103
+    return false;
104
+  }
93 105
   return classSupernova::db_upd_record_by_id(LOC_PLANET, $planet_id, $set);
94 106
 }
95 107
 function db_planet_set_by_gspt($ui_galaxy, $ui_system, $ui_planet, $ui_planet_type = PT_ALL, $set)
96 108
 {
97
-  if(!($set = trim($set))) return false;
109
+  if(!($set = trim($set))) {
110
+    return false;
111
+  }
98 112
 
99 113
   $si_galaxy = intval($ui_galaxy);
100 114
   $si_system = intval($ui_system);
@@ -106,13 +120,17 @@  discard block
 block discarded – undo
106 120
 function db_planet_set_by_parent($ui_parent_id, $ss_set)
107 121
 {
108 122
   //if(!($si_parent_id = intval($ui_parent_id)) || !($ss_set = trim($ss_set))) return false;
109
-  if(!($si_parent_id = idval($ui_parent_id)) || !($ss_set = trim($ss_set))) return false;
123
+  if(!($si_parent_id = idval($ui_parent_id)) || !($ss_set = trim($ss_set))) {
124
+    return false;
125
+  }
110 126
   return classSupernova::db_upd_record_list(LOC_PLANET, "`parent_planet` = {$si_parent_id}", $ss_set);
111 127
 }
112 128
 function db_planet_set_by_owner($ui_owner_id, $ss_set)
113 129
 {
114 130
   //if(!($si_owner_id = intval($ui_owner_id)) || !($ss_set = trim($ss_set))) return false;
115
-  if(!($si_owner_id = idval($ui_owner_id)) || !($ss_set = trim($ss_set))) return false;
131
+  if(!($si_owner_id = idval($ui_owner_id)) || !($ss_set = trim($ss_set))) {
132
+    return false;
133
+  }
116 134
   return classSupernova::db_upd_record_list(LOC_PLANET, "`id_owner` = {$si_owner_id}", $ss_set);
117 135
 }
118 136
 
@@ -120,7 +138,9 @@  discard block
 block discarded – undo
120 138
 function db_planet_delete_by_id($planet_id)
121 139
 {
122 140
   // if(!($planet_id = intval($planet_id))) return false;
123
-  if(!($planet_id = idval($planet_id))) return false;
141
+  if(!($planet_id = idval($planet_id))) {
142
+    return false;
143
+  }
124 144
   classSupernova::db_del_record_by_id(LOC_PLANET, $planet_id);
125 145
   classSupernova::db_del_record_list(LOC_UNIT, "`unit_location_type` = " . LOC_PLANET . " AND `unit_location_id` = " . $planet_id);
126 146
   // Очереди очистятся автоматически по FOREIGN KEY
@@ -129,7 +149,9 @@  discard block
 block discarded – undo
129 149
 function db_planet_list_delete_by_owner($ui_owner_id)
130 150
 {
131 151
   // if(!($si_owner_id = intval($ui_owner_id))) return false;
132
-  if(!($si_owner_id = idval($ui_owner_id))) return false;
152
+  if(!($si_owner_id = idval($ui_owner_id))) {
153
+    return false;
154
+  }
133 155
   classSupernova::db_del_record_list(LOC_PLANET, "`id_owner` = {$si_owner_id}");
134 156
   classSupernova::db_del_record_list(LOC_UNIT, "`unit_location_type` = " . LOC_PLANET . " AND `unit_player_id` = " . $si_owner_id);
135 157
   // Очереди очистятся автоматически по FOREIGN KEY
Please login to merge, or discard this patch.
includes/db/db_queries_unit.php 2 patches
Doc Comments   +6 added lines patch added patch discarded remove patch
@@ -64,11 +64,17 @@
 block discarded – undo
64 64
   return classSupernova::db_upd_record_by_id(LOC_UNIT, $unit_id, $set);
65 65
 }
66 66
 
67
+/**
68
+ * @param string $set
69
+ */
67 70
 function db_unit_set_insert($set)
68 71
 {
69 72
   return classSupernova::db_ins_record(LOC_UNIT, $set);
70 73
 }
71 74
 
75
+/**
76
+ * @param integer $unit_location_type
77
+ */
72 78
 function db_unit_list_delete($user_id = 0, $unit_location_type, $unit_location_id, $unit_snid = 0)
73 79
 {
74 80
   return classSupernova::db_del_record_list(LOC_UNIT,
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -26,7 +26,7 @@
 block discarded – undo
26 26
     'GROUP BY `unit_snid`'
27 27
   );
28 28
   $result = array();
29
-  while($row = db_fetch($query)) {
29
+  while ($row = db_fetch($query)) {
30 30
     $result[$row['unit_snid']] = $row;
31 31
   }
32 32
 
Please login to merge, or discard this patch.
includes/db/db_queries_users.php 2 patches
Doc Comments   +3 added lines patch added patch discarded remove patch
@@ -1,5 +1,8 @@
 block discarded – undo
1 1
 <?php
2 2
 
3
+/**
4
+ * @param boolean $player
5
+ */
3 6
 function db_user_by_id($user_id_unsafe, $for_update = false, $fields = '*', $player = null) {
4 7
   return classSupernova::db_get_user_by_id($user_id_unsafe, $for_update, $fields, $player);
5 8
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -83,7 +83,7 @@  discard block
 block discarded – undo
83 83
     "SELECT `id` AS `ID`, `username` AS `NAME`, `ally_name` AS `ALLY`, `total_points` AS `STAT_POINTS`,
84 84
       `onlinetime` AS `ACTIVITY`
85 85
     FROM {{users}}
86
-    WHERE `onlinetime` >= ". (SN_TIME_NOW - $config->game_users_online_timeout) ." ORDER BY user_as_ally, `". $TypeSort ."` ASC;");
86
+    WHERE `onlinetime` >= ". (SN_TIME_NOW - $config->game_users_online_timeout) . " ORDER BY user_as_ally, `" . $TypeSort . "` ASC;");
87 87
 }
88 88
 
89 89
 
@@ -98,7 +98,7 @@  discard block
 block discarded – undo
98 98
   return doquery("SELECT u.*, COUNT(r.id) AS referral_count, SUM(r.dark_matter) AS referral_dm FROM {{users}} as u
99 99
     LEFT JOIN {{referrals}} as r on r.id_partner = u.id
100 100
     WHERE" .
101
-    ($online ? " `onlinetime` >= ". (SN_TIME_NOW - $config->game_users_online_timeout) : ' user_as_ally IS NULL') .
101
+    ($online ? " `onlinetime` >= " . (SN_TIME_NOW - $config->game_users_online_timeout) : ' user_as_ally IS NULL') .
102 102
     " GROUP BY u.id
103 103
     ORDER BY user_as_ally, {$sort} ASC");
104 104
 }
@@ -114,7 +114,7 @@  discard block
 block discarded – undo
114 114
   !is_array($user_id_list) ? $user_id_list = array($user_id_list) : false;
115 115
 
116 116
   $user_list = array();
117
-  foreach($user_id_list as $user_id_unsafe) {
117
+  foreach ($user_id_list as $user_id_unsafe) {
118 118
     $user = db_user_by_id($user_id_unsafe);
119 119
     !empty($user) ? $user_list[$user_id_unsafe] = $user : false;
120 120
   }
Please login to merge, or discard this patch.