Часть 8 из 12
Строки: 14001-16000 из 22262
================================================================================

                    //$list_invite_games = Model::factory("user_game")->getList(array("user_id_1" => $data ['id'] ), array( "id" ));
                    //$invite_games_count = count($list_invite_games);
                    
                    //if($invite_games_count <= 0){
                    //     $data ['game_in']  = Model::factory ( 'var' )->loadByKey ( 'start_game_in' )->value;
                    //}  else {
                    //     $data ['game_in']  = $invite_games_count;
                    //}
                    //$data ['game_in_max']  = Model::factory ( 'var' )->loadByKey ( 'start_game_in_max' )->value;
                    //$data ['point']        = 0;
                    //$data ['star']         = 0;
                    
                    $ouser = $this->create($data);
                    $this->save();
                    $user = $this->get();
                    
                    //дополнительные действия при первой инициализации прользователя     
                    //------------------------------------------------------------------------------------------           
                    //Model::factory('statistics_game_total', $data ['id'])->createRecord( );
                    
                    Model::factory("user_booster", $data ['id'])->giveBoosterToNewUser();
                    
                    //$result = $user;         
                    
                    $result = true;
                    //------------------------------------------------------------------------------------------
                }
                
                return $this;
            } else {
                return true;
            }
        } catch (Exception $e){

             LOG_CRASH::add($e->getCode(), $e->getMessage(), "userModel", "saveProfile", $data ['id']);
             throw new Exception ($e->getMessage(), $e->getCode());
        }
    }
    //--------------------------------------------------------------------------------------------------------------------------------------------------------------
    
    /**
     * Проверяет достаточно ли валюты
     * @param $needMoney1 Валюта1
     * @param $needMoney2 Валюта2
     * @param $reason_id Тип операции (соответствует одному из значений перечесления возможных операций с валютами)
     * @return boolean
     */    
    public function checkMoney( $needMoney1 = 0, $needMoney2 = 0){
        try{
             if($this->money1 - $needMoney1 < 0 || $this->money2 - $needMoney2 < 0){
                 return false;
             } else {
                 return true;
             }
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "userModel", "checkMoney", $this->id);
            throw new Exception ($e->getMessage(), $e->getCode());
        }
    }  
    
    /**
     * Проверяет достаточно ли энергии
     * @param $needMoney1 Валюта1
     * @param $needMoney2 Валюта2
     * @param $reason_id Тип операции (соответствует одному из значений перечесления возможных операций с валютами)
     * @return boolean
     */    
    public function checkEnergy( $needEnergy = 0){
        try{
              $this->checkEnergyRecoveryStatus();
			  //////if($this->energy_type == 1 || $this->energy_type == 2){
              //////    return true; 
              //////}	

			  if($this->energy - $needEnergy < 0){
                   return false;
              } else {
                   return true;
              }
        } catch (Exception $e){

             LOG_CRASH::add($e->getCode(), $e->getMessage(), "userModel", "checkEnergy", $this->id);
             throw new Exception ($e->getMessage(), $e->getCode());
        }
    } 
    
    
    //УСТАРЕВШАЯ ФУНКЦ?Я НУЖНАЮЩАЯСЯ В ПРОВЕРКЕ!!!
    //УСТАРЕВШАЯ ФУНКЦ?Я НУЖНАЮЩАЯСЯ В ПРОВЕРКЕ!!!
    //УСТАРЕВШАЯ ФУНКЦ?Я НУЖНАЮЩАЯСЯ В ПРОВЕРКЕ!!!
    //УСТАРЕВШАЯ ФУНКЦ?Я НУЖНАЮЩАЯСЯ В ПРОВЕРКЕ!!!
    //УСТАРЕВШАЯ ФУНКЦ?Я НУЖНАЮЩАЯСЯ В ПРОВЕРКЕ!!!
	public function checkStage( $needStage ){
        try{
              if($this->stage >= $needStage){
                  return true;
              }
              return false;
              
        } catch (Exception $e){

             LOG_CRASH::add($e->getCode(), $e->getMessage(), "userModel", "checkStage", $this->id);
             throw new Exception ($e->getMessage(), $e->getCode());
        }
    } 
    //УСТАРЕВШАЯ ФУНКЦ?Я НУЖНАЮЩАЯСЯ В ПРОВЕРКЕ!!!
    //УСТАРЕВШАЯ ФУНКЦ?Я НУЖНАЮЩАЯСЯ В ПРОВЕРКЕ!!!
    //УСТАРЕВШАЯ ФУНКЦ?Я НУЖНАЮЩАЯСЯ В ПРОВЕРКЕ!!!
    //УСТАРЕВШАЯ ФУНКЦ?Я НУЖНАЮЩАЯСЯ В ПРОВЕРКЕ!!!
	//УСТАРЕВШАЯ ФУНКЦ?Я НУЖНАЮЩАЯСЯ В ПРОВЕРКЕ!!!
    public function buyStage( $cost_type, &$user_stage = 0, $friends_array = array() ){
        try{
           // $type = "0" // start
           // $type = "1" // money1
           // $type = "2" // friends
           
            
            $user_stage = $this->stage;
            $next_stage = $this->stage + 1;
            if(!Model::factory("stage_stat", $next_stage )->exist()){
                errors::exc(errors::errorIncorrectDBValue,"not exist next stage in stat table");
            }
            $aNextStage  = Model::factory("stage_stat", $next_stage )->get();
            $cost_star   = $aNextStage['cost_star'];
            $cost_money1 = $aNextStage['cost_money1'];
            $cost_friend = $aNextStage['cost_friend'];
            
            $user_stars = Model::factory("mission")->calculateStars( $this->id );
            
            //проверка на то все ли миссии в этапе уже пройдены
            if(! Model::factory("mission")->checkCompliteStage( $this->id,  $this->stage )){
                return false;
            }
            
            
            if($cost_type == 0){
               if($user_stars  >= $cost_star){
                  
                   $user_stage  = $this->stage + 1;
                   $this->stage = $user_stage;
                   $this->save();
                  
                   return true;
               } else {
                   return false;
               }
            } else if($cost_type == 1){
                if(!$this->checkMoney( $cost_money1 )){
                    return false;
                } else {
                    
                    $user_stage  = $this->stage + 1;
                    $this->stage = $user_stage;
                    $this->save();
                    
                    $this->changeMoney( - $cost_money1 );
                    return true;
                }
             } else if($cost_type == 2){
                 $friends_count = 0;
                
                 //-----------------------------------------------------
                 //не проверяем действительно ли эти игроки друзья текущего игрока
                 //но проверяем существуют ли они вообще в базе игры 
                 foreach($friends_array as $check_uid){
                     if($this->id != $check_uid){
                         if(Model::factory("user", $check_uid)->exist()){
                             $friends_count++;
                         }
                     }
                 }
                 
                 if($friends_count >= $cost_friend){
                    $user_stage  = $this->stage + 1;
                    $this->stage = $user_stage;
                    $this->save();
                    return true;  
                 } else {
                   return false;
                 }
             }
             else {
                return false;
            }
        } catch (Exception $e){

             LOG_CRASH::add($e->getCode(), $e->getMessage(), "userModel", "checkStage", $this->id);
             throw new Exception ($e->getMessage(), $e->getCode());
        }
    }
    //УСТАРЕВШАЯ ФУНКЦ?Я НУЖНАЮЩАЯСЯ В ПРОВЕРКЕ!!!
    //УСТАРЕВШАЯ ФУНКЦ?Я НУЖНАЮЩАЯСЯ В ПРОВЕРКЕ!!!
    //УСТАРЕВШАЯ ФУНКЦ?Я НУЖНАЮЩАЯСЯ В ПРОВЕРКЕ!!!
    //УСТАРЕВШАЯ ФУНКЦ?Я НУЖНАЮЩАЯСЯ В ПРОВЕРКЕ!!!
    //УСТАРЕВШАЯ ФУНКЦ?Я НУЖНАЮЩАЯСЯ В ПРОВЕРКЕ!!!
    
    /**
     * Начисляет/снимает валюту игрока
     * @param $money1 Валюта1
     * @param $money2 Валюта2
     * @param $reason_id Тип операции (соответствует одному из значений перечесления возможных операций с валютами)
     * @return boolean
     */    
    public function changeMoney($money1 = 0, $money2 = 0, $reason_id = 0) {
        try{
            if($this->money1 + $money1 < 0 || $this->money2 + $money2 < 0){
                return false;
            }
            
            if ($money1 != 0) {
                $this->money1 += $money1;
            }
            if ($money2 != 0) {
                $this->money2 += $money2;
            }
            if($money1 !=0 || $money2 !=0) {
            
               $today = date("Y.m.d H:i:s", SConfig::$time);
               $aLogGold  = array( 'user_id'   => $this->id,
                                   'date'      => SConfig::$time, 
                                   'money1'    => $money1,
                                   'money2'    => $money2,
                                   'reason_id' => $reason_id
                                 );
            
                Model::factory( 'log_money' )->create( $aLogGold );
				
                return true;
                
            } else {
                
                return false; 
                  
            }
            return false;
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "userModel", "changeMoney", $this->id);
            throw new Exception ($e->getMessage(), $e->getCode());
        }
    }
    //--------------------------------------------------------------------------------------------------------------------------------------------------------------
    
      /**
     * Начисляет/снимает энергию игрока
     * @param $energy Кол-во энергии
     * @param $reason_id Тип операции (соответствует одному из значений перечесления возможных операций с энергией)
     * @return boolean
     */    
    public function changeEnergy($energy = 0, $reason_id = 0, &$user_energy = 0) {
        try{
            
            $this->checkEnergyRecoveryStatus();
            
            if($this->energy + $energy < 0){
                return false;
            }
            
            if($this->energy >= $this->energy_max &&
               $this->energy + $energy < $this->energy_max){
              $this->energy_recovery_start_date = SConfig::$time;
            }
            
            if ($energy != 0) {
                $this->energy += $energy;
                $user_energy  = $this->energy;
                return true;
            }
            else {
                return false; 
            }
            return false;
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "userModel", "changeEnergy", $this->id);
            throw new Exception ($e->getMessage(), $e->getCode());
        }
    }
  //--------------------------------------------------------------------------------------------------------------------------------------------------------------
    
    public function changeExp($i_exp, $reason_id = 0, $reason_attr = array()) 
    {
        // $this->exp += $i_exp;
        $aUser        = Model::factory('user', $this->id)->get();     
        $iLevelStart  = $aUser['level'];
        $iLevel       = $iLevelStart;
        $fExpProcent  = $aUser['exp'];
        
        $aLevelInfo   = Model::factory('level', $iLevel)->get();
        $iExpOnLevel  = $aLevelInfo['exp'];
        
        $iExpPoint = floor( $fExpProcent * $iExpOnLevel + 0.5 );
       
        
        //$iExpPoint = round( $fExpProcent * $iExpOnLevel );
        
        $iExpPointNew = $iExpPoint + $i_exp;
        
        $iTNBonus = 0;     
        while($iExpPointNew >= $iExpOnLevel)
        {
            $iExpPointNew = $iExpPointNew - $iExpOnLevel;   
            $iLevel++;
            //------------------------------------------------------------------------
            //------------------------------------------------------------------------
            //------------------------------------------------------------------------
            //действия при увеличении уровня
              
            //Отправка запроса в ВК на увеличение уровня (ознокомительынй)----------------------
            if(0){
                if( $fild_name = SConfig::$social[ SOCIAL_ID ][ "name" ] == "vkontakte"){
                    $res = social::$authAPI->setUserLevel($this->id, $iLevel);
                }
            }
            //Отправка запроса в ВК на увеличение уровня (ознокомительынй)----------------------
          
            //восстановление очков энергии 

            //------------------------------------------------------------------------
            $aLevelInfo   = Model::factory('level', $iLevel)->get();
            $iExpOnLevel  = $aLevelInfo['exp'];
        }
        
        if($iLevel != $iLevelStart)
        {
            $aUser['level'] =  $iLevel;  
        }
        
        
        $fExpProcentNew = $iExpPointNew / $iExpOnLevel;
    
        $aUser['exp'] = $fExpProcentNew;  
        
        $aUser =  $this->create($aUser);
                
        $result = 1;
      
        if(0){
            $aLogExp  = array( 'user_id' => $this->id,
                               'date'    => SConfig::$time, 
                               'amount'  => $i_exp,
                               'type_id' => $reason_id,
                               'attr'    => serialize ( $reason_attr )
                             );
            
            Model::factory( 'log_exp' )->create( $aLogExp );
        }
        
        return true;
     }
    
    //--------------------------------------------------------------------------------------------------------------------------------------------------------------
    
   /**
     * Увеличение верхней границы значения восполняемой энергии восполняемой энергии
     * 
     * @param $count кол-во очков на которых увеличится верхняя граница значения восполняемой энергии
     * @return boolean
     */  
   public function addEnergyMax(  $count = 0) {
       try{
            $this->energy_max = $this->energy_max + $count;
            $this->save();
            return true;

        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "userModel", "addEnergyMax", $this->id);
            throw new Exception ($e->getMessage(), $e->getCode());
        }
    } 
    /**
     * Предоставление энергии 
     * 
     * @param $type  тип предоставляемой энергии
     * @param $count кол-во предоставляемой энергии
     * @return boolean
     */    
    public function addEnergy( $type = 0, $count = 0) {
        try{
			$type = 0; //переменная зарезервированна на случай добавления бесконечно энергии и в данный момент игнорируется
		
			$this->checkEnergyRecoveryStatus();
			
            /////if( $this->energy_type == 2 ){         // бесконечная энергия
			/////	return false;
			/////} else if( $this->energy_type == 1 ){   // энергия бесконечная на день             
			/////	if($type == 0 || $type == 1){
			/////		return false;
			/////	} else if($type == 2){
			/////		// покупаем
			/////	}
			/////} else if( $this->energy_type == 0 ){
			/////		// покупаем
			/////}
            if(0 == $type){
                $this->energy = $this->energy + $count;
            }
			/////else if(1 == $type){
            /////    if($this->energy < $this->energy_max){
            /////        $this->energy= $this->energy_max;
            /////    }



            /////$this->energy_unlimited_end_date = SConfig::$time + 86400;
            /////$this->energy_type               = 1;
            /////} else if(2 == $type){
            /////    if($this->energy < $this->energy_max){
            /////        $this->energy= $this->energy_max;
            /////    }
            /////    $this->energy_type               = 2;
            /////}
                    
            $this->save();
            return true;

        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "userModel", "addEnergy", $this->id);
            throw new Exception ($e->getMessage(), $e->getCode());
        }
    }
     /**
     * Покупка энергии за одну из игровых валют 
     * 
     * @param $price_id позиция покупки(берется из shop_energy_stat)
     * @return boolean
     */    
    public function buyEnergy($price_id = 0) {
        try{
            
            if(!Model::factory("shop_energy_stat",$price_id)->exist()){
                 return errors::errorIncorrectInput;
            }
        
            $aPrice = Model::factory("shop_energy_stat",$price_id)->get();
            
            if($aPrice['buy_way'] == 1){            //0 - ресурсы игры / 1 - валюта соц.сети
                errors::exc(errors::errorIncorrectInput,"wrong buy way, need use only social money" );
            }
            
            //$this->checkEnergyRecoveryStatus();
           
            /////if( $this->energy_type == 2 ){         // бесконечная энергия
            /////    return false;
            /////} else if( $this->energy_type == 1 ){   // энергия бесконечная на день             
            /////    if($aPrice["type_using"] == 0 || $aPrice["type_using"] == 1){
            /////        return false;
            /////    } else if($aPrice["type_using"] == 2){
            /////        // покупаем
            /////    }
            /////} else if( $this->energy_type == 0 ){
            /////    // покупаем
            /////}
            $reason_id = 4;
            
            if($aPrice['buy_way'] == 1){            //0 - ресурсы игры / 1 - валюта соц.сети
                errors::exc(errors::errorIncorrectInput,"wrong buy way, need use only social money" );
            }
            
            if($this->money1 >= $aPrice['cost_money1'] && $this->money2 >= $aPrice['cost_money2']){
                $this->changeMoney( - $aPrice['cost_money1'], - $aPrice['cost_money2'], $reason_id);
                       
				if($this->addEnergy( $aPrice['type_using'], $aPrice['count'])){
                   $this->save();
                   return true; 
                } else {
                    return false; 
                }
                                        /////	} else if(1 == $aPrice["type_using"]){
                                        /////		if($this->energy < $this->energy_max){
                                        /////		    $this->energy= $this->energy_max;
                                        /////		}
                                        /////     $this->energy_unlimited_end_date = SConfig::$time + 86400;
                                        /////     $this->energy_type               = 1;
                                        /////	} else if(2 == $aPrice["type_using"]){
                                        /////       if($this->energy < $this->energy_max){
                                        /////       $this->energy= $this->energy_max;
                                        /////   }
                                        /////     $this->energy_type               = 2;
                                        /////   }
                       //return $this->checkEnergyRecoveryStatus();;
            }
                                                                               /////if($this->energy_type == 0){
                                        /////    if(!Model::factory("shop_energy_stat",$price_id)->exist()){
                                        /////        return errors::errorIncorrectInput;
                                        /////    }
                                            
                                        /////} else if($this->energy_type == 1){  // режим бесконечной энергии на день
                                        /////    if($this->energy_unlimited_end_date >= SConfig::$time){
                                        /////        $this->energy_type = 0; //включаем обычный режим
                                        /////    }
                                        /////    if($this->energy < $this->energy_max){
                                        /////        $this->energy = $this->energy_max;
                                        /////    }
                                        /////    $this->save();
                                        /////} else if($this->energy_type == 2){
                                        /////    return false;  
                                            //return array("result" => 0);
                                        /////}
           
            return false;  
            //return array("result" => 0);
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "userModel", "buyEnergy", $this->id);
            throw new Exception ($e->getMessage(), $e->getCode());
        }
    }
    //--------------------------------------------------------------------------------------------------------------------------------------------------------------
    
    //--------------------------------------------------------------------------------------------------------------------------------------------------------------
    
    /**
     * Покупка энергии_максимальной за одну из валют
     * @param $price_id позиция покупки(берется из energy_price_max_stat)- сколько добавится единиц максимальной энергии
     * @return boolean
     */   
    public function buyEnergyMax($price_id = 0) {
        try{
            if(!Model::factory("shop_energy_max_stat",$price_id)->exist()){
                errors::exc(errors::errorIncorrectInput,"energy max price stat id not exist" );
            }
            
            $aPrice = Model::factory("shop_energy_max_stat",$price_id)->get();
            
            $reason_id = 5;
            
            if($aPrice['buy_way'] == 1){            //0 - ресурсы игры / 1 - валюта соц.сети
                errors::exc(errors::errorIncorrectInput,"wrong buy way, need use only social money" );
            }
            
            if($this->money1 >= $aPrice['cost_money1'] && $this->money2 >= $aPrice['cost_money2']){
                $this->changeMoney( - $aPrice['cost_money1'], - $aPrice['cost_money2'], $reason_id);
                if($this->addEnergyMax(  $aPrice['count'])){
                   $this->save();
                   return true; 
                } else {
                    return false;
                }
                return true;                                                                   
            }
            return false;
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "userModel", "buyEnergyMax", $this->id);
            throw new Exception ($e->getMessage(), $e->getCode());
        }
    }
    
    
    //--------------------------------------------------------------------------------------------------------------------------------------------------------------
        
    /**
     * Покупка Валюты1 за Валюту2
     * @param $price_id позиция покупки(берется из shop_money1_stat)
     * @return boolean
     */  
     public function buyMoney1($price_id = 0){
        try{
            if(!Model::factory("shop_money1_stat",$price_id)->exist()){
                errors::exc(errors::errorIncorrectInput,"shop_money1_stat id not exist" );
            }
            
            //проверка на buy_way!
            
            $aPrice = Model::factory("shop_money1_stat",$price_id)->get();
            
           
            if($aPrice['buy_way'] == 1){            //0 - ресурсы игры / 1 - валюта соц.сети
                errors::exc(errors::errorIncorrectInput,"wrong buy way, need use only social money" );
            }
            
            $reason_id = 16;
            if( $this->money2 >= $aPrice['cost_money2']){
                $this->changeMoney( + $aPrice['count'], - $aPrice['cost_money2'], $reason_id);
            } else {
                   errors::exc(errors::errorLogic,"not enough money" ); 
            }
        } catch(Exception $e) {
            
           LOG_CRASH::add($e->getCode(), $e->getMessage(), "userModel", "buyMoney1", $this->id);
           throw new Exception ($e->getMessage(), $e->getCode());
        }
     }
     
         /**
     * Покупка Валюты2 за Валюту1
     * @param $price_id позиция покупки(берется из shop_money2_stat)
     * @return boolean
     */  
     public function buyMoney2($price_id = 0){
        try{
            if(!Model::factory("shop_money2_stat",$price_id)->exist()){
                errors::exc(errors::errorIncorrectInput,"shop_money2_stat id not exist" );
            }
            
            //проверка на buy_way!
            
            $aPrice = Model::factory("shop_money2_stat",$price_id)->get();
            
           
            if($aPrice['buy_way'] == 1){            //0 - ресурсы игры / 1 - валюта соц.сети
                errors::exc(errors::errorIncorrectInput,"wrong buy way, need use only social money" );
            }
            
            $reason_id = 15;
            if( $this->money1 >= $aPrice['cost_money1']){
                $this->changeMoney( - $aPrice['cost_money1'], + $aPrice['count'], $reason_id);
                return true;
            } else {
                errors::exc(errors::errorLogic,"not enough money" ); 
            } 
        } catch(Exception $e) {
            
           LOG_CRASH::add($e->getCode(), $e->getMessage(), "userModel", "buyMoney2", $this->id);
           throw new Exception ($e->getMessage(), $e->getCode());
        }
     }
     
    //--------------------------------------------------------------------------------------------------------------------------------------------------------------
        
    /**
     * Добовление очки, и если очков скапливается больше чем vars.points_in_star, списывает очки и добавляет звезды
     * @param int   $points очки
     * param  int  &$user_point очки которые есть в наличаи у пользователя в данный момент, значение возвращается по ссылке
     * param  int  &$user_star звезды которые есть в наличаи у пользователя в данный момент, значение возвращается по ссылке
     * @return boolean
     */   
    public function addPoints($count = 0, &$user_point = 0, &$user_star = 0) {
        try{
            $user_point = 0;
            $user_star = 0;
            $points_in_star = Model::factory ( 'var' )->loadByKey ( 'points_in_star' )->value;
            $new_point_count = $this->point + $count;
            while($new_point_count >= $points_in_star){
                   $this->star = $this->star + 1; 
                   $new_point_count = $new_point_count - $points_in_star;
            }
            
            $this->point = $new_point_count;
            
            //возвращаемые по ссылке значения
            $user_point  = $this->point; 
            $user_star   = $this->star;
            
            return true;
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "userModel", "changeGameIn", $this->id);
            throw new Exception ($e->getMessage(), $e->getCode());
        }
    }
    //--------------------------------------------------------------------------------------------------------------------------------------------------------------
    /**
    * Докупка максимального колличества исходящих дуэлей за одну из валют
    * @param $price_id позиция покупки(берется из game_out_max_stat)- сколько добавится единиц максимальной энергии
    * @return mix array('result' => 1, 'energy' => $this->energy, 'energy_max' => $this->energy_max, 'time_to_next_recovery' => $time_to_next_recovery);
    */
    public function checkEnergyRecoveryStatus(){
       try{ 
           if(!isset($this->energy)){
                errors::exc(errors::errorIncorrectInput, "energy deta not exist");
           }
           $iEnergyNow               = $this->energy;
           $iEnergyMax               = $this->energy_max;
           $timeNow                  = SConfig::$time;
           $timeRecoveryStart        = $this->energy_recovery_start_date;
           $time_to_next_recovery    = -1;
           $time_afret_last_recovery = 0; 
           /////$time_to_unlimited_end    = -1;
           /////if($this->energy_type == 0){  // обычный режим
           
           $iConstEnergyRecoveryCount = Model::factory ( 'var' )->loadByKey ( 'energy_recovery_count' )->value;
           $iConstEnergyRecoveryTime  = Model::factory ( 'var' )->loadByKey ( 'energy_recovery_time_period' )->value;
          
           $iEnergyRecoveredCount = 0;
            
           $time_afret_last_recovery  =  $timeNow - $timeRecoveryStart;

           if($iEnergyNow < $iEnergyMax){
              
               $recovery_count =  floor($time_afret_last_recovery / $iConstEnergyRecoveryTime);
               $iEnergyRecoveredCount =   $recovery_count * $iConstEnergyRecoveryCount ;
               
               if( $recovery_count != 0){
                   if($iEnergyNow + $iEnergyRecoveredCount <  $iEnergyMax){
                       $this->energy                     =  $iEnergyNow + $iEnergyRecoveredCount;
                       $timeRecoveryStart                =  $timeRecoveryStart + $recovery_count * $iConstEnergyRecoveryTime;
                       $this->energy_recovery_start_date =  $timeRecoveryStart;
                   } else {
                       $this->energy                     =  $iEnergyMax;
                       $this->energy_recovery_start_date =  $timeNow;
                   }
               }
               
               $time_to_next_recovery = $timeRecoveryStart + $iConstEnergyRecoveryTime - $timeNow;
               if($time_to_next_recovery < 0){
                  $time_to_next_recovery = -1; 
               }
            }
            /////} else if($this->energy_type == 1){  // режим бесконечной энергии на день
            /////    if($this->energy_unlimited_end_date >= SConfig::$time + 864000){
            /////        $this->energy_type       = 0; //включаем обычный режим
            /////        $time_to_unlimited_end   = -1;
            /////    }
            /////    if($this->energy < $this->energy_max){
            /////        $this->energy            = $this->energy_max;
            /////    }
            /////    $time_to_unlimited_end   = $this->energy_unlimited_end_date - SConfig::$time;
           
            /////} else if($this->energy_type == 2){
            /////     if($this->energy < $this->energy_max){
            /////         $this->energy = $this->energy_max;
            /////         $this->energy_recovery_start_date = 0;
            /////         $this->energy_unlimited_end_date  = 0;
            /////         $time_to_unlimited_end            =  -1;
            /////     }
            /////}
           $this->save();
           return array('energy'                => $this->energy, 
                        'energy_max'            => $this->energy_max, 
                        'time_to_next_recovery' => $time_to_next_recovery);

           /////return array('energy'                      => $this->energy,
           /////             'energy_max'                  => $this->energy_max, 
           /////             'time_to_next_recovery'       => $time_to_next_recovery, 
           /////             'energy_type'                 => $this->energy_type, 
           /////             'time_to_unlimited_end'       => $time_to_unlimited_end);                        
           
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "userModel", "checkEnergyRecoveryStatus", $this->id);
            throw new Exception ($e->getMessage(), $e->getCode());
        }
    } 
 
    
    //--------------------------------------------------------------------------------------------------------------------------------------------------------------
    //--------------------------------------------------------------------------------------------------------------------------------------------------------------
    //--------------------------------------------------------------------------------------------------------------------------------------------------------------
    //--------------------------------------------------------------------------------------------------------------------------------------------------------------
    //--------------------------------------------------------------------------------------------------------------------------------------------------------------
    //--------------------------------------------------------------------------------------------------------------------------------------------------------------
    //--------------------------------------------------------------------------------------------------------------------------------------------------------------
    //--------------------------------------------------------------------------------------------------------------------------------------------------------------
    //--------------------------------------------------------------------------------------------------------------------------------------------------------------
    //--------------------------------------------------------------------------------------------------------------------------------------------------------------
    //--------------------------------------------------------------------------------------------------------------------------------------------------------------
    
      

    
    
    //заготовки(ДОДЕЛАТЬ)
    public function  convertSocialMoney($user_id, $gold_id, $to_type) {
        try{
            if($gold_id < 0)
            {
                return array('result' => -1, 'text' => 'not enough glod');
            }
           
            $aUser     = Model::factory('user', $user_id)->getProfile( true );
            
            //$user_gold     = $user['gold'];
            //$user_money    = $user['money1'];
            //$user_money_tn = $user['money2'];
            $reference = array(); 
           
            if( $to_type == 0)
            {
               if( Model::factory("gold_to_money", $gold_id)->exist() )
               {   
                   $reference =  Model::factory("gold_to_money", $gold_id)->get();
                   
            
                   $gold_out  = $reference['gold']; 
                   $money_in = $reference['money']; 
                   
                   if($aUser['gold'] < $gold_out)
                   {
                        return array('result' => '-2', 'text' => 'not enough gold' );  
                   }
                   else
                   {          
                        Model::factory('user', $user_id)->changeGold ( - $gold_out, 0, 7, array ( 'gold_out' => $gold_out, 'money_in' => $money_in ) ); 
                        Model::factory('user', $user_id)->changeMoney ( $money_in, 8, array ( 'money_in' => $money_in, 'gold_out' => $gold_out ) );
                        return array('result' => 1, 'gold_id' => $gold_id, 'totype' => $to_type); 
                   }
               }
               else
               {
                   return array('result' => -2, 'text' => 'no legal input date');            
               }
            } 
            else if( $to_type == 1)
            {
               if( Model::factory("gold_to_money_tn", $gold_id)->exist() )
               {   
                   $reference =  Model::factory("gold_to_money_tn", $gold_id)->get();
               
                   $gold_out    = $reference['gold']; 
                   $money_tn_in = $reference['money_tn']; 
                   
                   if($aUser['gold'] < $gold_out)
                   {
                        return array('result' => '-2', 'text' => 'not enough gold' );  
                   }
                   else
                   {      
                        Model::factory('user', $user_id)->changeGold ( - $gold_out, 0, 9, array ( 'gold_out' => $gold_out, 'money_in' => $money_tn_in ) ); 
                        Model::factory('user', $user_id)->changeMoneyTN ( $money_tn_in, 10, array ( 'money_tn_in' => $money_tn_in, 'gold_out' => $gold_out ) );
                        return array('result' => 1, 'gold_id' => $gold_id, 'totype' => $to_type); 
                   }
               }
               else
               {
                   return array('result' => -2, 'text' => 'no legal input date');            
               }
                
            }
            else
            {
                return array('result' => -3, 'text' => 'no legal input date (to_type)');
            }
            
            return array('result' => 0, "text" => "in develop");  
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "userModel", "convertGold", $user_id);
            throw new Exception ($e->getMessage(), $e->getCode());
        }  
    } 
    
    public function checkBalance( $user_id){
        try{ 
             $listUserGold = Model::factory('user',$user_id)->getList(array('id' => $user_id), array('gold'));
             if(count($listUserGold) == 0){
                 return array('result' => -1, "text" => 'uids error');
             } else {
                 $iUserGold = $listUserGold[0]['gold'];
                 return array('result' => 1, "gold" => $iUserGold);  
             }
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "userModel", "checkBalance", $user_id);
            throw new Exception ($e->getMessage(), $e->getCode());
        }  
    }  
    
    //$user_inviter_id - пославший приглашение
    public function acceptInvitation($user_inviter_id){
        try{ 
            
            $user_id = $this->id; 
            
            // в friend поле user_id содержит того кто послал приглашение (тот кто получит в итоге награду) = $user_inviter_id 
            $list_friend = Model::factory("friend")->getList(array("user_id" => $user_inviter_id)); // $user_id заменил на $user_inviter_id
            foreach( $list_friend as $friend){
                if($friend["friend_id"] == $this->id){  //$user_inviter_id заменил на $user_id
                    
                    //invite_status = 1 - друг уже принял приглашение
                    //invite_status = 2 - друг принял приглашение и игрок забрал вознаграждение  
                    if($friend["invite_status"] == 1 || $friend["invite_status"] == 2){
                        return array("result" => 0);
                    } 
                }
                
            }
            
            
            $arr_friend = array("user_id"                => $user_inviter_id,
                                "friend_id"              => $this->id,
                                "invite_status"          => 1
                               );
            Model::factory("friend")->create($arr_friend);
            return array("result" => 1);
            
            
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "userModel", "acceptInvitation", $user_id);
            throw new Exception ($e->getMessage(), $e->getCode());
        }  
        
    }                                                   
    
    public function checkInvitation( &$friend_bonus_list = array(), &$friend_bonus_money1 = 0, &$friend_bonus_money2 = 0, &$friend_bonus_energy = 0 ){
        try{ 
            
            $user_id = $this->id; 
            
            $list_friend = Model::factory("friend")->getList(array("user_id" => $user_id));
            $bonus_money1       = Model::factory ( 'var' )->loadByKey ( 'friend_invite_bonus_money1' )->value;
            $bonus_money2       = Model::factory ( 'var' )->loadByKey ( 'friend_invite_bonus_money2' )->value;
            $bonus_energy       = Model::factory ( 'var' )->loadByKey ( 'friend_invite_bonus_energy' )->value;

            foreach( $list_friend as $friend){
                if($friend["invite_status"] == 1){
                    
                    //----------------------------------------
                    //начисление бонуса:
                    
                     $this->changeMoney( + $bonus_money1, 0, 1);
                     $this->changeMoney( 0, + $bonus_money2, 1);
                     $this->changeEnergy( + $bonus_energy ); 
                    
                     $friend_bonus_money1 =+ $bonus_money1;
                     $friend_bonus_money2 =+ $bonus_money2;
                     $friend_bonus_energy =+ $bonus_energy;
                     //----------------------------------------
                    
                    $friend["invite_status"] = 2;
                    Model::factory("friend")->create($friend);
                    
                    $friend_bonus_list[] = $friend["friend_id"];
                }
                
            }

            return 1;
  
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "userModel", "acceptInvitation", $user_id);
            throw new Exception ($e->getMessage(), $e->getCode());
        }  
        
    }  
}


================================================================================
ФАЙЛ: app/models/company_statModel.php
================================================================================

<?php
/**
 * 
 */
class company_statModel extends Model {
    
    protected $_tableName = 'company_stat';
    
}


================================================================================
ФАЙЛ: app/models/statistics/statistics_missionModel.php
================================================================================

<?php
/**
 * Класс модели обработки статистики миссий
 */
class statistics_missionModel extends Model {
    
    protected $_tableName = 'statistics_mission';
   
     
     /**
     * Пишет статистику о начале, завершении и выйгрыше в миссии
     * @param  (bigint) $user_id            номер пользователя в соц. сети
     * @param  (int)    $mission_stat_id    тип миссии, id из табл. mission_stat 
     * @param  (int)    $initial_action     тип активности инициирующий запись лога: 
     * 0 - начало миссии, 1 - успешное завершение миссии, 2 - проигрыш миссии,    
     * 
     * @return bool
     */ 
     public function updateCounts( $user_id, $mission_stat_id, $initial_action = 0, $point = 0, $star = 0) {
        try{  
            
            //-------------------------------------------------------------------------------------------------------------------
            $statistics_mission_on = 1;
            $statistics_mission_on = Model::factory("var")->getValue( 'statistics_mission_on' );
            if(1 == is_null($statistics_mission_on)){
                 $statistics_mission_on = 0;
            }
            //-------------------------------------------------------------------------------------------------------------------
            if(0 == $statistics_mission_on){
                return 0;
            }  
            
            if(!Model::factory("user", $user_id)->exist()){
                return 0;
            }
            
            if(!Model::factory("mission_stat", $mission_stat_id)->exist()){
                return 0;
            }
            
            $aStatsMission   = array();
            $add_user_unique = 0;
            
            $list_stats_mission = array();
            $list_stats_mission = Model::factory("statistics_mission")->getList(array("user_id" => $user_id, "mission_stat_id" => $mission_stat_id));
            if( is_array( $list_stats_mission ) && 0 == count( $list_stats_mission )){
               
                $aStatsMission = array( "user_id" => $user_id, "mission_stat_id" => $mission_stat_id,  "start_count" => 0, "end_count" => 0, "win_count" => 0, "date_activity" => SConfig::$time );  
                $add_user_unique = $add_user_unique + 1; //Новый уникальный пользователь начал играть в текущую миссию
            
            } else {
            
                $aStatsMission = $list_stats_mission[0]; 
                $add_user_unique = 0;
            } 
            
            switch( $initial_action ){
                case 0: {   //запуск миссии
                   $aStatsMission["start_count"]++; 
                   
                   Model::factory("statistics_mission_count", $mission_stat_id)->updateCounts(  1, 0, 0, $add_user_unique);
                   
                } break;
                case 1: {   //успешное завершение
                    
                   if(0 == $aStatsMission["start_count"]){
                       return 0;
                   } 
                
                   $aStatsMission["end_count"]++;
                   $aStatsMission["win_count"]++;
                
                   Model::factory("statistics_mission_count", $mission_stat_id)->updateCounts(  0, 1, 1, $add_user_unique, $point, $star );
                
                } break;
                case 2: {   //проигрыш
                
                   if(0 == $aStatsMission["start_count"]){
                       return 0;
                   } 
                   
                   $aStatsMission["end_count"]++;
                   
                   Model::factory("statistics_mission_count", $mission_stat_id)->updateCounts(  0, 1, 0, $add_user_unique, $point, $star );
                   
                } break;
                default:{
                    return 0;  
                }
            }       
       
            $aStatsMission["date_activity"] = SConfig::$time;
       
            Model::factory("statistics_mission")->create($aStatsMission);
            
            return 1;
    
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "statistics_missionModel", "addGameResult");
            throw new Exception ($e->getMessage(), $e->getCode());
        }  
    }
}

================================================================================
ФАЙЛ: app/models/statistics/statistics_gameModel.php
================================================================================

<?php
/**
 * 
 * Класс модели обработки статистики о завершенных играх
 */
class statistics_gameModel extends Model {
    
    protected $_tableName = 'statistics_game';
    
}

================================================================================
ФАЙЛ: app/models/statistics/statistics_games_rivalModel.php
================================================================================

<?php
/**
 * 
 * Класс модели обработки статистики между конктретными игроками
 */
class statistics_games_rivalModel extends Model {
    
    protected $_tableName = 'statistics_games_rival';
    
    /**
     * Дополняет один масив, элементами из другого массива, при этом удаляя ненужные для вывода поля
     * 
     * Дополняет один масив, элементами из другого массива, при этом удаляя ненужные для вывода поля
     * 
     * @param  (array)  $list_games     входной массив с данными о играх пользователя
     * @param  (&array) $list_games_all (передается по ссылке) массив который нужно доплнить данными о играх пользователя из массива $list_games
     * @return bool
     */ 
     
    private function convertToOutFormat($list_games, &$list_games_all){
         try{
             if(true == is_array($list_games) && 0 != count($list_games)){
                 foreach($list_games as $game_rival){
                     unset($game_rival["id"]);
                     unset($game_rival["time_last_game_end"]);
                     $list_games_all[] = $game_rival;
                 }
             }
             return 1;
         } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "statistics_games_rivalModel", "convertToOutFormat");
            throw new Exception ($e->getMessage(), $e->getCode());
        }
     }
     
     /**
     * Пишет статистику о том сколько раз сыграл и выйграл один игрок у другого 
     * Статистика не дублируется для обоих игроков
     * @param  (bigint) user_winner_id номер из соц. сети выйгравшего в дуэли игрока 
     * @param  (bigint) user_loser_id номер из соц. сети проигравшего в дуэли игрока 
     * @return bool
     */ 
     public function add( $user_winner_id, $user_loser_id) {
        try{  
            
            if(!Model::factory("user", $user_winner_id)->exist()){
                errors::exc(errors::errorIncorrectInput,"user_id not exist" );
            }
            if(!Model::factory("user", $user_loser_id)->exist()){
                errors::exc(errors::errorIncorrectInput,"user_id not exist" );
            }
            
            $flagNew = false;
            $winner_position = 0;
            
            $list = array();
            $list = Model::factory("statistics_games_rival")->getList(array("user_id_0" => $user_winner_id, "user_id_1" => $user_loser_id));
            if( is_array( $list ) && 0 == count( $list )){
                $list = Model::factory("statistics_games_rival")->getList(array("user_id_0" => $user_loser_id, "user_id_1" => $user_winner_id));
                if(is_array( $list ) && 0 == count( $list )){
                    $flagNew = true;
                } else {
                    $winner_position = 1;
                }
            } 
            
            $arr_statistic = array();
            
            if(true == $flagNew){
                //создаем нову запись в логах
                $arr_statistic = array( "user_id_0" => $user_winner_id, "user_id_1" => $user_loser_id,  "all" => 1, "win" => 1, "time_last_game_end" => SConfig::$time );  
            } else {
                //запись уже существует
                $arr_statistic = $list[0];
                $arr_statistic['all']                = $arr_statistic['all'] + 1;
                $arr_statistic["time_last_game_end"] = SConfig::$time; 
          
                if(0 == $winner_position ){
                    $arr_statistic['win'] = $arr_statistic['win'] + 1;  
                } 
            }
            
            Model::factory("statistics_games_rival")->create($arr_statistic);
            
            return 1;
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "statistics_games_rivalModel", "addGameResult");
            throw new Exception ($e->getMessage(), $e->getCode());
        }  
    }
    
     
     /**
     * Возвращает статистические данные по всем соперникам игрока
     * @param  (bigint) $user_id          :  номер пользователя в соц.сети, чьи записи проверяются
     * @return Object Объект с множеством свойств имя/значение:
     *  -  (array) rivals_data    : Массив с статисическими данными о сколько раз сыграл пользователей с оппанентами и сполько совершил побед. Массив объектов, каждый объект которого содержит следующие свойства:
     *  -  - (int) user_id_0         : номер игрока в соц.сети (игрока или соперника);
     *  -  - (int) user_id_1         : номер игрока в соц.сети (игрока или соперника);
     *  -  - (int) all               : всего игр сыграно с тиекущими пользователями;
     *  -  - (int) win               : побед игрока user_id_0 над игроком user_id_1;
     */
     public function getAllRivalsData( $user_id ){
        try{
            if(!Model::factory("user", $user_id)->exist()){
                errors::exc(errors::errorIncorrectInput,"user_id not exist" );
            }
            
            $list_games_0 = Model::factory("statistics_games_rival")->getList(array("user_id_0" => $user_id));               
            $list_games_1 = Model::factory("statistics_games_rival")->getList(array("user_id_1" => $user_id));               
            
            $list_games_all = array();
            
            $this->convertToOutFormat($list_games_0, $list_games_all);
            $this->convertToOutFormat($list_games_1, $list_games_all);
          
            return $list_games_all; 
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "statistics_games_rivalModel", "getAllRivalsData");
            throw new Exception ($e->getMessage(), $e->getCode());
        }                    
     } 

     
    //-------------------------------------------------------------------------- 
    //-------------------------------------------------------------------------- 
    //-------------------------------------------------------------------------- 
     /**
     * Возвращает статистические данные по одному сопернику
     * @param  bigint  user_id    :  номер пользователя в соц.сети, чьи записи проверяются
     * @return Object Объект с множеством свойств имя/значение:
     *  -  (array) rivals_data    : Массив с статисическими данными о сколько раз сыграл пользователей с оппанентами и сполько совершил побед. Массив объектов, каждый объект которого содержит следующие свойства:
     *  -  - (int) user_id_0         : номер игрока в соц.сети (игрока или соперника);
     *  -  - (int) user_id_1         : номер игрока в соц.сети (игрока или соперника);
     *  -  - (int) all               : всего игр сыграно с тиекущими пользователями;
     *  -  - (int) win               : побед игрока user_id_0 над игроком user_id_1;
     */
     public function getOneRivalData( $user_id,  $user_rival_id){
        try{
            if(!Model::factory("user", $user_id)->exist()){
                errors::exc(errors::errorIncorrectInput,"user_id not exist" );
            }
            
            $list_games_0 = array();
            $list_games_1 = array();
            
            $list_games_0 = Model::factory("statistics_games_rival")->getList(array("user_id_0" => $user_id, "user_id_1" => $user_rival_id ));               
            if(true == is_array($list_games_0) && 0 == count($list_games_0)){
                $list_games_1 = Model::factory("statistics_games_rival")->getList(array("user_id_0" => $user_rival_id, "user_id_1" => $user_id));               
            }
            
            $list_games_all = array();
          
            $this->convertToOutFormat($list_games_0, $list_games_all);
            $this->convertToOutFormat($list_games_1, $list_games_all);
           
            return $list_games_all;
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "statistics_games_rivalModel", "getDataAllRivals");
            throw new Exception ($e->getMessage(), $e->getCode());
        }                    
     }
     
     
     
     
     
     
     /**
     * Возвращает статистические данные о проигрышах и выйгрышах массива игроков
     * @param  bigint $user_id       номер пользователя в соц.сети, чьи записи проверяются
     * @param  array  $user_rival_id номер пользователя в соц.сети, соперник
     * @return Object Объект с множеством свойств имя/значение:
     *  -  user_rival_id номер в соц.сети соперника. 
     *  -  all всего игр сыграно с тиекущем пользователем
     *  -  win побед текущего пользователя над соперником
     */
     public function getArrayRivalsData( $user_id,  $array_rivals){
        try{                                 
            if(!Model::factory("user", $user_id)->exist()){
                errors::exc(errors::errorIncorrectInput,"user_id not exist" );
            }
            $list_games     = array();
            $list_games_all = array();
            if(is_array($array_rivals) && count($array_rivals) > 0){
                foreach($array_rivals as $user_rival_id){
                    if(Model::factory("user", $user_rival_id)->exist()){
                         $list_games = $this->getOneRivalData( $user_id,  $user_rival_id);
                         $this->convertToOutFormat($list_games, $list_games_all);
                    }
                }
            }
            return $list_games_all;
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "statistics_games_rivalModel", "getArrayRivalsData");
            throw new Exception ($e->getMessage(), $e->getCode());
        }
     }
 
}

================================================================================
ФАЙЛ: app/models/statistics/statistics_game_detailModel.php
================================================================================

<?php
/**
 * 
 * Класс модели обработки детальной статистики по посденим играм 
 */
class statistics_games_detailModel extends Model {
    
    //protected $_tableName = 'statistics_games_detail';
    
    /**
     * Создает новые записи в статистических таблицах, вносится подробная информация о игре(дуэли, раундах и заданиях)
     * Данные не дублируются для обоих играков
     * 
     * Данные копируются полностью, таблица game,task и 
     * 
     * @param  (bigint) $user_id      :  id текущего пользователя в соц. сети
     * @param  (array)  $aGame        :  массив описания игры с последними несохраненными в базу изменениями (сохранение не имеет смысла т.к. рабочие данные после внесения в статистику удаляются из БД)
     * @param  (array)  $aRoundSet    :  массив описания раундов с последними несохраненными в базу изменениями (сохранение не имеет смысла т.к. рабочие данные после внесения в статистику удаляются из БД)
     * @param  (array)  $aTaskSet     :  массив описания заданий с последними несохраненными в базу изменениями (сохранение не имеет смысла т.к. рабочие данные после внесения в статистику удаляются из БД)
     * @return bool
     */ 
    public function add( $user_id, $aGame, $aRoundSet, $aTaskSet ){
        try{
            
            $this->checkAndClear( $aGame["user_id_0"] );
            $this->checkAndClear( $aGame["user_id_1"] );
            
            //------------------------------------------------------------
           
            $statictics_game_id = 0;
            $statictics_game = array(
            "id"                => $aGame["id"],
            "user_id_0"         => $aGame["user_id_0"],
            "user_id_1"         => $aGame["user_id_1"],
            "rounds_count"      => $aGame["rounds_count"],
            "user_cancel"       => $aGame["user_cancel"],
            "round_cancel"      => $aGame["round_cancel"],
            "user_winner_game"  => $aGame["user_winner_game"],
            "time_game_end"     => SConfig::$time  );
            
            Model::factory("statistics_game")->create( $statictics_game );
 
            //------------------------------------------------------------
            
            foreach($aRoundSet as $round){
              
               $statictics_round = array(
               "id"                   => $round["id"],
               "game_id"              => $round["user_game_id"],
               "user_result_0"        => $round["user_result_0"],
               "user_result_1"        => $round["user_result_1"]);
            
               Model::factory("statistics_round")->create( $statictics_round );
            }
           
            //------------------------------------------------------------
           
            foreach($aTaskSet as $task){
              
               $statictics_task = array(
               "id"                   => $task["id"],
               "round_id"             => $task["user_round_id"],
               "task_stat_id"         => $task["task_stat_id"],           
               "result_user"          => $task["result_user"],
               "active_user"          => $task["active_user"],
               "try_count"            => $task["try_count"],
               "bit_mask"             => $task["bit_mask"],
               "fail_chars"           => "".$task["fail_signs"],
               "history"              => "".$task["history"]);
            
                Model::factory("statistics_task")->create( $statictics_task );
            }
                  
            return 1;
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "statistics_games_detailModel", "add", $user_id);
            throw new Exception ($e->getMessage(), $e->getCode());
        }  
    }
    
    /**
     * Возвращается полная статистическая информация о завершенных играх .
     * 
     * @param  bigint $user_id номер пользователя в соц.сети, чьи записи проверяются
     * @return array
     */ 
    public function getData( $user_id ) {
        try{
            //удаление старых записей, если необходимо-------------------------------------------------------------------------------------------------
          
            $game_set  = array(); 
            $round_set = array();  
            $task_set  = array();  
                           
            
            $list0 = Model::factory("statistics_game")->getList(array("user_id_0" => $user_id), array("id", "time_game_end"));
            $list1 = Model::factory("statistics_game")->getList(array("user_id_1" => $user_id), array("id", "time_game_end")); 
            
            $storage_time       = Model::factory ( 'var' )->loadByKey ( 'statistics_games_storage_time' )->value;
                   
            foreach( $list0 as $game ){
                if( SConfig::$time - $game["time_game_end"] > $storage_time){
                    $this->deleteAllGameData( $user_id, $game["id"] );
                } else {
                    $this->getAllGameSetStatistic($user_id, $game["id"], $game_set, $round_set, $task_set);          
                }
            }
            foreach( $list1 as $game ){
                if( SConfig::$time - $game["time_game_end"] > $storage_time){
                    $this->deleteAllGameData( $user_id, $game["id"] );
                } else {
                    $this->getAllGameSetStatistic($user_id, $game["id"], $game_set, $round_set, $task_set);          
                }
            }
           
            return array( "result" => 1, "game_set" => $game_set, "round_set" => $round_set, "task_set" => $task_set );
            
            //-----------------------------------------------------------------------------------------------------------------------------
            
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "statistics_game_detailModel", "getData", $user_id);
            throw new Exception ($e->getMessage(), $e->getCode());
        }  
    }
    
    /**
    * Возвращается полная статистическая информация о завершенных играх .
    * 
    * @param  bigint $user_id номер пользователя в соц.сети, чьи записи проверяются
    * @return array
    */ 
    public function getAllGameSetStatistic($user_id, $game_id, &$game_set, &$round_set, &$task_set){
        try{
             $game = Model::factory("statistics_game", $game_id)->get();

             $list_round_set = Model::factory("statistics_round")->getList(array("game_id" => $game_id));
           
             foreach($list_round_set as $round){
                  $list_task_set = Model::factory("statistics_task")->getList(array("round_id" => $round["id"]));
                  foreach($list_task_set as $task){
                      
                        $task_stat             = Model::factory("task_stat",$task["task_stat_id"])->get();
                        //$str_question  = Model::factory("word")->convert_to_in( $task_stat["question"] );
                        //$str_word_mask = Model::factory("word")->get_word_mask( $str_question, $task[ 'bit_mask' ]);
                        //$task["mask"]  = Model::factory("word")->convert_to_out($str_word_mask);
                        $task["question"] =  $task_stat["question"];
                       
                        $task_set[] = $task;
                  }
                  $round_set[] = $round; 
             }
             $game_set[] = $game;
      
        return 1;
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "statistics_game_detailModel", "getAllGameSetStatistic", $user_id);
            throw new Exception ($e->getMessage(), $e->getCode());
        }         
    }          
    
    /**
    * Проверка: просматриваются старые записи игрока содержащие статистическую информацию о сыгранных играх и в случае если данные хранятся 
    * В случае если данные хранятся слишком долго, старые записи удаляются (просуществовавшие var.statistics_games_storage_time секунд и больше)
    * @param  bigint $user_id номер пользователя в соц.сети, чьи записи проверяются
    * @return bool
    */ 
    private function checkAndClear( $user_id ) {
        try{
                    
            $list0 = Model::factory("statistics_game")->getList(array("user_id_0" => $user_id), array("id", "time_game_end"));
            $list1 = Model::factory("statistics_game")->getList(array("user_id_1" => $user_id), array("id", "time_game_end"));
           
            $storage_time       = Model::factory ( 'var' )->loadByKey ( 'statistics_games_storage_time' )->value;
                   
            foreach( $list0 as $game ){
                if( SConfig::$time - $game["time_game_end"] > $storage_time){
                    $this->deleteAllGameData( $user_id, $game["id"] );
                }
            }
            foreach( $list1 as $game ){
                if( SConfig::$time - $game["time_game_end"] > $storage_time){
                    $this->deleteAllGameData( $user_id, $game["id"] );
                }
            }

            return 1;
        
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "statistics_game_detailModel", "checkAndClear", $user_id);
            throw new Exception ($e->getMessage(), $e->getCode());
        }  
    }
    
    
     /**
     * Удаляет все данные о завершенной игре из статистики 
     * 
     * Удаляются данные о игре(дуэли), раундах, и заданиях
     * 
     * @param  (bigint) user_id    :   номер пользователя в соц.сети, чьи записи проверяются
     * @param  (int)    game_id    :   id игры(дуэли) в статистике
     * @return bool
     */ 
    private function deleteAllGameData( $user_id, $game_id ) {
        try{
             $list_round_set = Model::factory("statistics_round")->getList(array("game_id" => $game_id), array("id"));
            
             foreach($list_round_set as $round){
                  $list_task_set = Model::factory("statistics_task")->getList(array("round_id" => $round["id"]));
                  foreach($list_task_set as $task){
                        Model::factory("statistics_task")->delete(array("id" => $task["id"]));
                  }
                  Model::factory("statistics_round")->delete(array("id" => $round["id"]));
             }
             Model::factory("statistics_game")->delete(array("id" => $game_id));
             
             return 1;
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "statistics_game_detailModel", "deleteAllGameData", $user_id);
            throw new Exception ($e->getMessage(), $e->getCode());
        }
    }
    
   
}

================================================================================
ФАЙЛ: app/models/statistics/statistics_mission_countModel.php
================================================================================

<?php
/**
 * Класс модели обработки статистики миссий
 */
class statistics_mission_countModel extends Model {
    
    protected $_tableName = 'statistics_mission_count';
   
     
     /**
     * Пишет статистику о начале, завершении и выйгрыше в миссии
     * @param  (bigint) $user_id            номер пользователя в соц. сети
     * @param  (int)    $mission_stat_id    тип миссии, id из табл. mission_stat 
     * @param  (int)    $initial_action     тип активности инициирующий запись лога: 
     * 0 - начало миссии, 1 - успешное завершение миссии, 2 - проигрыш миссии,    
     * 
     * @return bool
     */ 
     public function updateCounts(  $start = 0, $end = 0, $win = 0, $user_unique = 0, $point = 0, $star = 0 ) {
        try{  
            
            
            if(!$this->exist()){
               
               $point_min = 0;
               $point_max = 0;
               $point_mid = 0;
               $star_1 = 0;
               $star_2 = 0;
               $star_3 = 0;
               
               if(0 != $point){
               
                   $point_min = $point;
                   $point_max = $point;
                   $point_mid = $point;
                   
                   switch( $star ){
                       case 1: {
                            $star_1 = 1;
                       } break;
                       case 2: {
                            $star_2 = 1;
                       } break;
                       case 3: {
                            $star_3 = 1;
                       } break;
                   }
               } 
               $this->create(array("id" => $this->id, "date_activity" => SConfig::$time, "start" => $start, "end" => $end, "win" => $win, "user_unique" => $user_unique, "point_min" => $point_min, "point_max" => $point_max, "point_mid" => $point_mid, "star_1" => $star_1, "star_2" => $star_2, "star_3" => $star_3));             
            
            } else {
            
                if($start > 0){
                    $this->start = $this->start + $start;
                }
                if($end > 0){
                    $this->end = $this->end + $end;
                }
                if($win > 0){
                    $this->win = $this->win + $win;
                }
                
                if($user_unique > 0){
                    $this->user_unique = $this->user_unique + $user_unique;
                }
                
                if(0 != $end){
                    if($point != 0 && $point < $this->point_min){
                        $this->point_min = $point;
                    }
                    
                    if($point != 0 && $point > $this->point_max){
                        $this->point_max = $point;
                    }
                    
                    if($point != 0){
                        if($this->point_mid == 0){
                           $this->point_mid = $point;  
                        } else {
                            $this->point_mid = ($this->point_mid + $point) / 2;
                        }
                    }
                    
                    switch( $star ){
                        case 1: {
                            $this->star_1++;
                        } break;
                        case 2: {
                            $this->star_2++;
                        } break;
                        case 3: {
                            $this->star_3++;
                        } break;
                    }
                }
                
                $this->date_activity = SConfig::$time;
                
                /*
                if(0 == $this->id){
                   //при save могу буть проблемы если $this->id = 0 
                   // из-за этого save в Model был изменен 
                   // $this->save();
                   return 1; 
                }
                */
               
                $this->save();
            }
            return 1;
    
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "statistics_mission_countModel", "updateCounts");
            throw new Exception ($e->getMessage(), $e->getCode());
        }  
    }
}

================================================================================
ФАЙЛ: app/models/statistics/statistics_game_totalModel.php
================================================================================

<?php
/**
 * 
 * Класс модели обработки общей статистики 
 */
class statistics_game_totalModel extends Model {
    
    protected $_tableName = 'statistics_game_total';
    
    
    /**
     * Создает новую запись в статистической таблице, инициализируя значения по-умолчанию
     * (id пользователя передается в аргументах обращении к фабрике)
     * @return mix Созданный объект
     */ 
    public function createRecord() {
        try{
            $aRecord = array('id'                   => $this->id,
                             'all'                  => 0,
                             'win'                  => 0,
                             'date_first_input'     => SConfig::$time,
                             'date_last_game_end'   => 0,
                             'friends_invate_count' => 0
                             );
            $oRecord = $this->create($aRecord);
            return $oRecord;
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "statistics_game_totalModel", "createRecord");
            throw new Exception ($e->getMessage(), $e->getCode());
        }  
    }
        
    /**
     * Пишет в статистическую таблицу изменения общих данных о активности ирока 
     * (id пользователя передается в аргументах обращении к фабрике)
     * @param $game_result_status   (0 - lose, 1 - win)
     * @return int
     */  
    public function addGameResult( $game_result_status = 0) {
        try{
           
            $all_game_increment = 1;
            $win_game_increment = 0;
            if($game_result_status == 1){
                $win_game_increment = 1;
            }
            
            if(!$this->exist()){
                $this->createRecord();
            }
            
            $this->all+=                $all_game_increment;
            $this->win+=                $win_game_increment;
            $this->date_last_game_end = SConfig::$time;
            $this->save();
            
            /*
            //------------------------------------------------------------------------- 
            $aRecord = array('id'                 => $this->id, //$this->id
                             'all'                => $this->all + $all_game_increment,
                             'win'                => $this->win + $win_game_increment,
                             'date_last_game_end' => SConfig::$time);                            
       
            $this->create( $aRecord );
            //-------------------------------------------------------------------------
            */  // the same
            
             return 1;
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "statistics_game_totalModel", "addGameResult");
            throw new Exception ($e->getMessage(), $e->getCode());
        }  
    }
    
    
    /**
     * Пишет в статистическую таблицу изменение количества приглашенных друзей 
     * (id пользователя передается в аргументах обращении к фабрике)
     * @param $friends_invate_count = 0 число приглашеных друзей
     * @return int
     */  
    public function addFriendsInviteCount( $new_friends_count = 1) {
        try{
            
            if(!$this->exist()){
                $this->createRecord();
            }
            
            $this->friends_invate_count+=   $new_friends_count;
            $this->save();
            
             return 1;
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "statistics_game_totalModel", "addFriendsInviteCount");
            throw new Exception ($e->getMessage(), $e->getCode());
        }  
    }
    
    /**
     * Возвращает статистические данные по числу игр
     * @param  bigint $user_id номер пользователя в соц.сети, чьи записи проверяются
     * @return array
     */
    public function getData( $user_id ){
        
        if(!Model::factory("user", $user_id)->exist()){
            errors::exc(errors::errorIncorrectInput,"user_id not exist" );
        }
        $aResult = array();
        $listResult = Model::factory("statistics_game_total")->getList(array("id" => $user_id), array("all", "win", "date_last_game_end"));               
        $aResult = $listResult[0];
        return $aResult;                    
    }
    
    
}

================================================================================
ФАЙЛ: app/models/statistics/statistics_roundModel.php
================================================================================

<?php
/**
 * 
 * Класс модели обработки статистики о раундах завершенных игр
 */
class statistics_roundModel extends Model {
    
    protected $_tableName = 'statistics_round';
    
}

================================================================================
ФАЙЛ: app/models/statistics/statistics_taskModel.php
================================================================================

<?php
/**
 * 
 * Класс модели обработки статистики о всех задания в раундах завершенных игр
 */
class statistics_taskModel extends Model {
    
    protected $_tableName = 'statistics_task';
    
}

================================================================================
ФАЙЛ: app/models/statistics/statisticsModel.php
================================================================================

<?php
/**
 * 
 * Класс модели обработки общей статистики 
 */
class statisticsModel extends Model {
    
    //protected $_tableName = 'statistics_game_total';
    /**
     * Пишет всю статистику о игре в момент ее окончания
      * @return bool
     */ 
    public function addGameResult( $user_id, $aGame, $aRoundSet, $aTaskSet ) {
        try{
            
            $user_id_0 = $aGame["user_id_0"];
            $user_id_1 = $aGame["user_id_1"];
            //--------------------------------------------------------------------------
            
            $iNumWinner =  $aGame["user_winner_game"];
           
            if($iNumWinner == 0){
                 //общая статистика---------------------------------------------------- 
                 Model::factory("statistics_game_total", $user_id_0)->addGameResult(1);
                 Model::factory("statistics_game_total", $user_id_1)->addGameResult(0);
            
                 //статистика для двух конкретных игроков------------------------------
                 Model::factory("statistics_games_rival")->add( $user_id_0, $user_id_1);
            } else {
                 //общая статистика---------------------------------------------------- 
                 Model::factory("statistics_game_total", $user_id_1)->addGameResult(1);   
                 Model::factory("statistics_game_total", $user_id_0)->addGameResult(0); 
                 
                 //статистика для двух конкретных игроков------------------------------
                 Model::factory("statistics_games_rival")->add( $user_id_1, $user_id_0);  
            }
            
            //--------------------------------------------------------------------------
            //--------------------------------------------------------------------------
            //подробная статистика о раундах 
            //--------------------------------------------------------------------------
            
            Model::factory("statistics_games_detail")->add( $user_id, $aGame, $aRoundSet, $aTaskSet );

            //--------------------------------------------------------------------------
            //--------------------------------------------------------------------------
            //--------------------------------------------------------------------------
            
            return 1;
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "statisticsModel", "addGameResult", $user_id);
            throw new Exception ($e->getMessage(), $e->getCode());
        }  
    }
    
    
}

================================================================================
ФАЙЛ: app/models/statistics/statistics_playlist_playModel.php
================================================================================

<?php
/**
 * 
 * Класс модели обработки статистики о использовании пользователями плейлистов
 */
class statistics_playlist_playModel extends Model {
    
    protected $_tableName = 'statistics_playlist_play';
    
    /**
     * Пишет статистику о том какой плейлист использует игрок
     * (id пользователя передается в аргументах обращении к фабрике)
     * @param  int    $user_id     номер пользователя в соц. сети
     * @param  int    $playlist_id номер плейлиста из статисчекой таблицы
     * @return int
     * 
     */ 
     public function add($user_id, $playlist_id) {
        try{
            
            if(!Model::factory("user", $user_id)->exist()){
                errors::exc(errors::errorIncorrectInput,"user_id not exist" );
            }
            
            if(!Model::factory("playlist_stat", $playlist_id)->exist()){
                errors::exc(errors::errorIncorrectInput,"playlist not exist" );
            }
            
            //------------------------------------------------------------------------------------------------- 
            $arr_statistic = array();
            $list = $this->getList(array("user_id" => $user_id, "playlist_stat_id" => $playlist_id));
            if(FALSE == is_null($list) && TRUE == is_array($list) && 0 != count($list)) {
               $arr_statistic = $list[0];
               $arr_statistic["use_count"] += 1;
            } else {
               $arr_statistic = array("user_id" => $user_id, "playlist_stat_id" => $playlist_id, "use_count" => 1 ); 
            }
            
            $this->create( $arr_statistic );
            $this->save();
            
            return 1;
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "statistics_playlist_playModel", "add");
            throw new Exception ($e->getMessage(), $e->getCode());
        }  
    }
    
 
 
    /**
     * Возвращает статистические данные по одному игроку
     * <b>ВАЖНО</b>:статистика по плейлистам пишется только после завершения дуэли,
     * 
     * <br><b>Пример запроса к серверу:</b>
     * <br> 
     * <code>
     * http://www.sweetbear.info/wp/htdocs/index.php?m=|||uid||100200300|||s_key||-1|||m||0||0||statistics.get_playlist_usage_date|||m||0||1||{}
     * </code>
     * 
     * <br><b>Пример ответа от сервера:</b>
     * <br> 
     * <code>
     * [["statistics.get_playlist_usage_date",{"result":1,"playlist_usage":{"id":"100200300","0":"0","1":"2","2":"0","3":"0","4":"0","5":"0","6":"0","7":"0","8":"0","9":"0","10":"0","11":"0","12":"0","13":"0","14":"0","15":"0","16":"0","17":"0","18":"0","19":"0","20":"0"}}]]
     * </code> 
     * 
     * @param  (bigint)    $user_id      : номер пользователя в соц.сети, чьи записи проверяются
     * 
     * @return Object Объект с множеством свойств имя/значение:
     *  -  (int) result             : "1" - успех / "-x" - ошибка 
     *  -  (array) playlist_usage      : Массив со статистическими данными. Массив объектов, каждый объект которого содержит следующие свойства:
     *  -  -  (int) playlist_stat_id      : номер плейлиста использованного игроком(соответствует id из табл.playlist_stat);
     *  -  -  (int) use_count             : количество использований плейлиста ;
     */
     public function getData( $user_id ){
        try{
            if(!Model::factory("user", $user_id)->exist()){
                errors::exc(errors::errorIncorrectInput,"user_id not exist" );
            }
            $list_statistic      = array();
            $list_statistic = Model::factory("statistics_playlist_play")->getList(array("user_id" => $user_id)); 
            if(FALSE == is_null($list_statistic) && TRUE == is_array($list_statistic) && 0 != $list_statistic){
               foreach($list_statistic as &$arr){
                  unset($arr["id"]); 
                  unset($arr["user_id"]);
               } 
            }              
            return $list_statistic;
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "statistics_playlist_playModel", "getData");
            throw new Exception ($e->getMessage(), $e->getCode());
        }                    
     } 
     
     //--------------------------------------------------------------------------------------------------------------------
     //--------------------------------------------------------------------------------------------------------------------
     //--------------------------------------------------------------------------------------------------------------------
     //--------------------------------------------------------------------------------------------------------------------
     //--------------------------------------------------------------------------------------------------------------------
     /**
     * Пишет статистику о том какой плейлист использует игрок
     * фукнция не использвуется, т.к. заменена на add
     * @param  bigint $user_winner номер из соц. сети выйгравшего в дуэли игрока 
     * @param  int    $playlist_id номер плейлиста из статисчекой таблицы
     * @return int
     * 
     * @ignore 
     */ 
     private function addDuplication( $user_id, $playlist_id) {
        try{
            
            if(!Model::factory("user", $user_id)->exist()){
                //errors::exc(errors::errorIncorrectInput,"user_id not exist" );
            }
            
            if(!Model::factory("playlist_stat", $playlist_id)->exist()){
                //errors::exc(errors::errorIncorrectInput,"playlist not exist" );
            }
            
            //$listUserPlaylistData = Model::factory("statistics_playlist_play")->getList(array("id" => $user_id));
            //$listUserPlaylistData = Model::factory("statistics_playlist_play")->getList(array("id" => $user_id), array("id", "21" ));
            
            $aUserPlaylistData = Model::factory("statistics_playlist_play", $user_id)->get();

            if(is_array($aUserPlaylistData) && count($aUserPlaylistData) > 0){
                if(is_null($aUserPlaylistData[ $playlist_id] )){
                    return 0;
                }
                //$aUserPlaylistData  = $listUserPlaylistData[0];
                $aUserPlaylistData["$playlist_id"] = $aUserPlaylistData["$playlist_id"] + 1; 
                $this->$playlist_id += 10; 
            } else {
                 
                 //------------------------------------------------------------------------------------------------- 
                 //проверка зашита в коде, в случае увеличения числа плейлистов следует внетси измнения тут и в базе
