Часть 5 из 12
Строки: 8001-10000 из 22262
================================================================================

                    $result [$key] = $value->get ();
            } else {
                $result [$key] = isset ( $this->_dataUpdate [$key] ) ? $this->_dataUpdate [$key] : $value;
            }
        }
        return $this->_prepareOutput ( $result );
    }
    
    public function getCacheListTag() {
        if (($tag = CacheAccess::get ( $this->_tableName . '_list' )) === false) {
            $tag = SConfig::$time;
            CacheAccess::set ( $this->_tableName . '_list', $tag, 86400 + mt_rand ( 0, 86400 ) );
        }
        return $tag;
    }
   
	public function resetCacheTableDel() {
        
        //CacheAccess::delete( $this->_tableName . '_list');   
        CacheAccess::delete( $this->_tableName);   
    }   
    
    public function resetCacheListDel() {
        
        //CacheAccess::delete( $this->_tableName . '_list');   
		CacheAccess::delete( $this->_tableName . '_list');   
    }   
    public function resetCacheListTag() {
        CacheAccess::set ( $this->_tableName . '_list', SConfig::$time + 1, 86400 + mt_rand ( 0, 86400 ) );
    }
    
    public function getPageList($page = 1, $where = '', $perPage = 20) {
        $count = DBAccess::query ( 'SELECT count(*) FROM ' . $this->_tableName . ' WHERE 1 ' . $where . ' ', array (), PDO::FETCH_COLUMN, false );
        $sql = 'SELECT * FROM ' . $this->_tableName . ' WHERE 1 ' . $where . ' ';
        $list = DBAccess::query ( $sql . ' LIMIT ' . (($page - 1) * $perPage) . ', ' . $perPage, array (), PDO::FETCH_ASSOC );
        return array ($list, $count );
    }
     
    /**
     * @param array $where
     * @param array $fields
     * @param string $order
     * @param userModel $user
     * @param int $limit
     * @return mixed
     */
    public function getList($where = array(), $fields = NULL, $order = '', $user = NULL, $limit = "") {
        $cacheKey = serialize ( $where ) . serialize ( $fields ) . $order;
        if($limit != ""){
            $cacheKey = $cacheKey." LIMIT ".$limit;
        }
        if ($user)
            $cacheKey .= '_' . $user->id;
        $cacheKey = $this->_tableName . '_list_' . md5 ( $cacheKey );
        $result = CacheAccess::get ( $cacheKey );
        if ($result === false || $this->getCacheListTag () > $result ['tag']) {
            $result = DBAccess::select ( $this->_tableName, $where, $fields, $order, $limit );
            CacheAccess::set ( $cacheKey, array ('tag' => SConfig::$time, 'data' => $result ), 43200 + mt_rand ( 0, 43200 ) );
        } else {
            $result = $result ['data'];
        }
        if (is_null ( $fields )) {
            if (is_null ( $user ) && isset ( $result [0] ['user_id'] ))
                $user = Model::factory ( 'user', $result [0] ['user_id'] );
            $result = $this->_prepareListOutput ( $result, $user );
        }
        return $result;
    }
        
    public function getListWithoutCache($where = array(), $fields = NULL, $order = '', $user = NULL, $limit) {
        $result = DBAccess::select ( $this->_tableName, $where, $fields, $order, $limit );
        if (is_null ( $fields )) {
            if (is_null ( $user ) && isset ( $result [0] ['user_id'] ))
                $user = Model::factory ( 'user', $result [0] ['user_id'] );
            $result = $this->_prepareListOutput ( $result, $user );
        }
        return $result;
    }
    
    
      
    public function delete($where = NULL) {
        if ($this->exist ()) {
            try {
                $result = ( boolean ) DBAccess::delete ( $this->_tableName, array ($this->_idName => $this->_data [$this->_idName] ) );
            } catch ( Exception $e ) {
                return false;
            }
            if ($result) {
                CacheAccess::delete ( $this->_tableName . '_' . $this->_data [$this->_idName] );
                $this->_data = $this->_dataUpdate = array ();
            }
        } elseif (! is_null ( $where )) {
            $result = DBAccess::delete ( $this->_tableName, $where );
        }
        if ($result) {
            $this->resetCacheListTag ();
        }
        return $result;
    } 
    
    public function __get($name) {
        if (isset ( $this->_belongs_to [$name] ) && ! isset ( $this->_data [$name] )) {
            $this->_data [$name] = Model::factory ( $this->_belongs_to [$name] ['model'], $this->{$this->_belongs_to [$name] ['foreign_key']} );
        }
        if (isset ( $this->_dataUpdate [$name] )) {
            return $this->_dataUpdate [$name];
        } elseif (isset ( $this->_data [$name] )) {
            return $this->_data [$name];
        } else {
            errors::exc ( errors::errorUnknown, $name . ' is not property' );
        }
    }
    
    public function __isset($name) {
        return isset ( $this->_data [$name] ) || isset ( $this->_belongs_to [$name] );
    }
    
    public function __set($name, $value) {
        if (isset ( $this->_data [$name] )) {
            $this->_dataUpdate [$name] = $value;
        } else {
            errors::exc ( errors::errorUnknown, $name . ' is not property' );
        }
    }
    
    public function upload($field) {
        if (! isset ( $this->$field ))
            return false;
        if (! isset ( $_FILES [$field] ) || ! is_uploaded_file ( $_FILES [$field] ['tmp_name'] ))
            return true;
        $file_parts = pathinfo ( $_FILES [$field] ['name'] );
        $old_name = $this->$field;
        $new_name = $this->_tableName . '/' . md5 ( 'aqw4fx' . $this->_idName . 'pqncga8923n' . SConfig::$time . mt_rand ( 0, 10000 ) ) . '.' . $file_parts ['extension'];
        mkdir ( SConfig::$root_dir . 'htdocs/files/' . $this->_tableName, 0777, true );
        if (move_uploaded_file ( $_FILES [$field] ['tmp_name'], SConfig::$root_dir . 'htdocs/files/' . $new_name )) {
            chmod ( SConfig::$root_dir . 'htdocs/files/' . $new_name, 0666 );
            $this->delete_upload ( $field );
            $this->file = $new_name;
            return true;
        } else {
            return false;
        }
    }
    
    public function delete_upload($field) {
        if (! isset ( $this->$field ))
            return false;
        if (file_exists ( SConfig::$root_dir . 'htdocs/files/' . $this->$field )) {
            unlink ( SConfig::$root_dir . 'htdocs/files/' . $this->$field );
            $this->$field = '';
        }
        return true;
    }
    
    public function create($data) {
        $id = DBAccess::insert ( $this->_tableName, $data, array ($this->_idName ) );
        $id = is_numeric ( $id ) ? $id : (isset ( $data [$this->_idName] ) ? $data [$this->_idName] : false);
        if ($id) {
            $this->loadFromDb ( $id );
            $this->resetCacheListTag();
        }
        return $this;
    }
    
    public function getReference($key, $value) {
        $cacheKey = $this->_tableName . '_reference_' . $key . '_' . $value;
        $result = CacheAccess::get ( $cacheKey );
        if ($result === false || $this->getCacheListTag () > $result ['tag']) {
            $list = DBAccess::select ( $this->_tableName, array (), array ($key, $value ), $key . ' ASC' );
            $result = array ();
            foreach ( $list as $l ) {
                $result [$l [$key]] = $l [$value];
            }
            CacheAccess::set ( $cacheKey, array ('tag' => SConfig::$time, 'data' => $result ), 43200 + mt_rand ( 0, 43200 ) );
        } else {
            $result = $result ['data'];
        }
        return $result;
    }
    
    public function getCount() {
        $cacheKey = $this->_tableName . '_count';
        $result = CacheAccess::get ( $cacheKey );
        if ($result === false || $this->getCacheListTag () > $result ['tag']) {
            $result = DBAccess::query ( 'SELECT COUNT(*) as count_records FROM ' . $this->_tableName, array (), PDO::FETCH_COLUMN, false );
            CacheAccess::set ( $cacheKey, array ('tag' => SConfig::$time, 'data' => $result ), 43200 + mt_rand ( 0, 43200 ) );
        } else {
            $result = $result ['data'];
        }
        return $result;
    }  

}

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

<?php
/**
 * 
 * Класс модели пользователя
 */
class user_ordersModel extends Model {
    
    protected $_tableName = 'user_orders';

    /**
    * Предоставляет недавно отработанные запросов на покупку, о которых еще не был проинформирован клиент
    * После вызова функции, запросы, которые до этого момента не были помечены как просмотренные 
    * т.е. в табл. user_orders.client_inform_flag == 0 возвращаются и сразу же помечаются как 
    * просмотренные user_orders.client_inform_flag = 1  
    * @param $user_id id игрока в соц сети
    * @return array $aOrders
    */ 
    public function get_and_change_uninform_orders($user_id){
        try{
            
            $list_order = Model::factory("user_orders")->getList(array("user_id" => $user_id, "client_inform_flag" => 0));
            $aOrder = array();
            foreach($list_order as $order){  
               $aOrder[] = array("item_id" => $order["item_id"]);
               $order["client_inform_flag"] = 1;
               
               Model::factory('user_orders')->create( $order );  
}
            return $aOrder;           
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "user_orderModel", "get_and_change_uninform_orders", $user_id);
            throw new Exception ($e->getMessage(), $e->getCode());
        } 
    }

}

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

<?php
/**
 * 
 */
class missionModel extends Model {
    
  protected $_tableName = 'mission';

     //-----------------------------------------------------------------------------------------------------------------------
     //-----------------------------------------------------------------------------------------------------------------------
     //-----------------------------------------------------------------------------------------------------------------------
     //-----------------------------------------------------------------------------------------------------------------------
     //-----------------------------------------------------------------------------------------------------------------------
   
    
    
  
  
  
  
  
  
 
  
  
 
  
  

  
  
  public function getListMission($user_id){
       try{
           if(!Model::factory('user', $user_id)->exist()){
               return array();
               // errors::exc(errors::errorIncorrectInput, "user $user_id id not exist");
           }
           $listMission =  $this->getList(array("user_id" => $user_id));
           foreach($listMission as &$mission){
               if(isset($mission['user_id'])){
                   unset($mission['user_id']); 
               }
           }
           
           if(!is_array( $listMission ) || 0 == count($listMission)){
              $listMission = array(); 
           }
           
           return $listMission;
       } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "missionModel", "getListMission", $user_from);
            throw new Exception ($e->getMessage(), $e->getCode());
        } 
  } 
  
  public function getMissionByStatId($user_id, $mission_stat_id){
       try{
           if(!Model::factory('user', $user_id)->exist()){
               return array();
               // errors::exc(errors::errorIncorrectInput, "user $user_id id not exist");
           }  
           if(!Model::factory('mission_stat', $mission_stat_id)->exist()){
                errors::exc(errors::errorIncorrectInput, "mission stat id not exist");
           }
           
           $aMission = array();
           $listMission =  $this->getList(array("user_id" => $user_id, "mission_stat_id" => $mission_stat_id));
           if(0 != count($listMission)){
             $aMission = $listMission[0];  
           }
           if(count($listMission) > 1){
               foreach($listMission as $mission){
                   if($aMission["id"] != $mission["id"]){
                       $this->delete(array("id" => $mission["id"]));
                       $this->save();
                   }
               }
           }
           
           return $aMission;
       } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "missionModel", "getListMission", $user_from);
            throw new Exception ($e->getMessage(), $e->getCode());
        } 
  }
  
  
  
  public function checkAllPreviousMissionCompleted($user_id, $mission_stat_id){
       try{
           
              $aMissionStat =   Model::factory('mission_stat', $mission_stat_id)->get();
              $stage  = $aMissionStat["stage_stat_id"]; 
             
              //Условие начала миссии.
              //1. Если миссия первая в списке миссий этапа
              //2. Все предыдущие миссии уже игрались. 
             
             
              $listStageMissionStat = array();
              //Находим все статические миссиис сортировкой по полю position-------------------------------------------------------------------------
              $listStageMissionStat = Model::factory("mission_stat")->getList(array("stage_stat_id" => $stage), array("id", "position"), "position");
              
              if( 0 == count($listStageMissionStat)){
                   errors::exc(errors::errorIncorrectInput, "stage missions stat not exist");
              }
              
              $arr_mission_stat = array();
              
              //1. Если миссия первая в списке миссий этапа---------------------------------------
              $arr_mission_stat = reset($listStageMissionStat);
              if($aMissionStat["position"] == $arr_mission_stat["position"]){
                  return true;
              }
              //----------------------------------------------------------------------------------
               
              end($listStageMissionStat);
              $arr_mission_stat = current($listStageMissionStat);
              
              //находим текущую позицию-------------------------------------------
              do {
                  if($aMissionStat["position"] == $arr_mission_stat["position"]){
                      break;
                  }
                  $arr_mission_stat = prev($listStageMissionStat);    
              } while( FALSE != $arr_mission_stat );  

              //2. Все предыдущие миссии уже игрались---------------------------------------------
               $arr_mission_stat = prev($listStageMissionStat);
               if(FALSE == $arr_mission_stat){
                   return true;
               }  
               
               do {
                   $aMissionPrevious = $this->getMissionByStatId($user_id, $arr_mission_stat["id"]);
                   if(0 == count($aMissionPrevious)){
                       return false;
                   }
                   $arr_mission_stat = prev($listStageMissionStat);    
              } while( FALSE != $arr_mission_stat );  
              //----------------------------------------------------------------------------------
              
       return true;              
              
       } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "missionModel", "getListMission", $user_from);
            throw new Exception ($e->getMessage(), $e->getCode());
        } 
  }
  
  
  
  
   public function startMission($user_id, $mission_stat_id){
       try{
              if(!Model::factory('user', $user_id)->exist()){
                  errors::exc(errors::errorIncorrectInput, "user id not exist");
              }
              if(!Model::factory('mission_stat', $mission_stat_id)->exist()){
                  errors::exc(errors::errorIncorrectInput, "mission stat id not exist");
              }
              
              $aMissionStat = Model::factory('mission_stat', $mission_stat_id )->get(); 
              
              //-----------------------------------------------------------------------------------
              $listStage = Model::factory("stage")->getList(array("user_id" => $user_id, "stage_stat_id" => $aMissionStat["stage_stat_id"]));
              if(!is_array($listStage) || 0 == count($listStage)){
                  return array("result" => -141, "text" => "user stage not exist");  
              }
              //-----------------------------------------------------------------------------------
              
              $aMission = $this->getMissionByStatId($user_id, $mission_stat_id);
              
              //Условия начала миссии--------------------------------------------------------------
              //1. Если миссия уже игралась, то можно ее переиграть (в любом случае)
              //2. Если миссия первая в списке миссий этапа
              //3. Все предыдущие миссии уже игрались 
              
              if(0 == count($aMission)){
                  if(!$this->checkAllPreviousMissionCompleted($user_id, $mission_stat_id)){
                      return array("result" => -141, "text" => "not completed the previous mission");
                  }     
              } else {
                  if(0 == $aMissionStat["replay_flag"]){
                      return array("result" => -142, "text" => "replay unavailable for this mission");
                  }
              }
              //-----------------------------------------------------------------------------------
              
              $CostEnergy = Model::factory ( 'var' )->loadByKey ( 'mission_start_energy' )->value;
             
              if(!Model::factory("user", $user_id)->checkEnergy($CostEnergy)){
                  return array("result" => -3, "text" => "not enough energy");  
              }   
              
              $start_key = Model::factory("mission_key", $user_id)->setKey( $mission_stat_id );
             
              Model::factory("user", $user_id)->changeEnergy( - $CostEnergy);
              

              
              //---------------------------------------------------------------------------------------------------
              //записываем статистику по миссии
              //$initial_action(последний аргумент): 0 - начало миссии, 1 - успешное завершение миссии, 2 - проигрыш миссии,
              $initial_action = 0;
              $a = Model::factory("statistics_mission")->updateCounts($user_id, $mission_stat_id, $initial_action);
              //---------------------------------------------------------------------------------------------------
              
              return array("result" => 1, "mission" => array("mission_stat_id" => $mission_stat_id, "start_key" => $start_key ));
                   
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "missionModel", "startMission", $user_from);
            throw new Exception ($e->getMessage(), $e->getCode());
        } 
    }
    
    /*
    *
    * id миссии в аргументах вабрики прислать
    */
    
    public function endMission($user_id, $start_key, $new_point){
       try{
              if(!Model::factory('user', $user_id)->exist()){
                  errors::exc(errors::errorIncorrectInput, "user id not exist");
              }
              
              //-------------------------------------------------------------------------------------
              //флаг, определяющий каким образом подсчитывается выйгрыш в миссии
              $mission_prize_sum_system = 0;
              $mission_prize_sum_system = Model::factory ( 'var' )->loadByKey ( 'mission_prize_sum_system' )->value;
              if(1 == is_null($mission_prize_sum_system)){
                  $mission_prize_sum_system = 0;
              }
              //-------------------------------------------------------------------------------------
              
              
              //-------------------------------------------------------------------------------------
              $mission_stat_id = 0;
              $aMissionStat    = array();
              $aStage          = array();   
              //-------------------------------------------------------------------------------------
              
              if(!Model::factory("mission_key", $user_id)->checkKey( $start_key, $mission_stat_id )){
                  return array("result" => -2, "text" => "wrong mission start_key");
              }
              
              if(!Model::factory('mission_stat', $mission_stat_id)->exist()){
                  errors::exc(errors::errorIncorrectInput, "mission stat id not exist");
              }
              
             
              $aMissionStat = Model::factory('mission_stat', $mission_stat_id )->get();
              
              $point_in_star1  =  $aMissionStat['point_in_star1'];
              if( 1 == is_null($aMissionStat['point_in_star1']) ){
                  $point_in_star1 = 2147483647;
              }
              $point_in_star2  =  $aMissionStat['point_in_star2'];
              if( 1 == is_null($aMissionStat['point_in_star2']) ){
                  $point_in_star2 = 2147483647;
              }
              $point_in_star3  =  $aMissionStat['point_in_star3'];
              if( 1 == is_null($aMissionStat['point_in_star3']) ){
                  $point_in_star3 = 2147483647;
              }
              
              $new_star = 0;
              $old_star = 0;
              
              if($new_point > 0){
                  if( $new_point   >=  $point_in_star3){
                      $new_star = 3;
                  } else if( $new_point  >=  $point_in_star2){
                      $new_star = 2;
                  } else if( $new_point  >=  $point_in_star1){
                      $new_star = 1;
                  } 
              }
              $flag_win_without_new_star = false;
              
              if(0 == $new_star){
                  //если нет ни одной звесзы,
                  //миссия проиграна
              
                  //перед завершением миссии записываем статистику миссии:
                  //---------------------------------------------------------------------------------------------------
                  //записываем статистику по миссии
                  //$initial_action(последний аргумент): 0 - начало миссии, 1 - успешное завершение миссии, 2 - проигрыш миссии,
                  $initial_action = 2;
                  $a = Model::factory("statistics_mission")->updateCounts($user_id, $mission_stat_id, $initial_action, $new_point, $new_star);
                 //---------------------------------------------------------------------------------------------------
              
                  
                  
                  
				  return array("result" => 0);
                  
              } else {
         
                  //если есть хотябы одна звезда,
                  //миссия выйграна
                  
                  //возвращаем энергию, забранную до начала миссии----------------------------------
				  $flagReturnEnergy = Model::factory ( 'var' )->loadByKey ( 'mission_energy_win_return' )->value;
                  if($flagReturnEnergy == 1){
					  $CostEnergy = Model::factory ( 'var' )->loadByKey ( 'mission_start_energy' )->value;
				   	  Model::factory("user", $user_id)->changeEnergy( + $CostEnergy);
                  }
				  //--------------------------------------------------------------------------------         
              }
                 
              
              $aMission = $this->getMissionByStatId($user_id, $mission_stat_id);
    
              if(0 == count($aMission)){
                  
                   $aMission = array( "user_id"           =>   $user_id,
                                      "mission_stat_id"   =>   $mission_stat_id, 
                                      "point"             =>   0, 
                                      "star"              =>   0);
              } 
            
              //только если очков больше чем было, перезаписываем очки! 
              //но можем перезаписать звезды, если в mission_stat изменились данные
              if($new_point    > $aMission["point"]){
                  $aMission["point"] = $new_point;
              }  
              
              //--------------------------------------------------------------------------------
              //--------------------------------------------------------------------------------
              //--------------------------------------------------------------------------------
              //учет количества звезд и призов за них
              $prize_star_1 = false;
              $prize_star_2 = false;
              $prize_star_3 = false;                 
              
                 
              
              #//win without progress################# 
              
                  if(1 == $mission_prize_sum_system){    
                     switch( $aMission["star"] ){
                         case 3:{
                            $flag_win_without_new_star = true;  
                         } break;
                         case 2:{
                            if($new_star        == 3){
                                $prize_star_3 = true;  
                            } else {
                                $flag_win_without_new_star = true;  
                            }
                         } break;
                         case 1:{
                            if($new_star        == 3){
                                $prize_star_3 = true;  
                                $prize_star_2 = true;  
                            } else if($new_star == 2){
                                $prize_star_2 = true;  
                            } else {
                                $flag_win_without_new_star = true;  
                            }
                         } break;
                         case 0:{
                            if($new_star        == 3){
                                $prize_star_3 = true;  
                                $prize_star_2 = true;
                                $prize_star_1 = true;  
                            } else if($new_star == 2){
                                $prize_star_2 = true;  
                                $prize_star_1 = true;  
                            } else if($new_star == 1){
                                $prize_star_1 = true;   
                            } else {
                                $flag_win_without_new_star = true; 
                            }
                         } break;
                     }
                     
                  } else {
                       if($new_star > 0){
                           
                           $prize_star_1 = true;
                           $prize_star_3 = false;   
                           $prize_star_2 = false;   
                           
                       }  
                  }
                  
                  
                   //--------------------------------------------------------------------------------
                  //--------------------------------------------------------------------------------
                  //--------------------------------------------------------------------------------
                  if($new_star     > $aMission["star"]){
                      
                      $old_star          = $aMission["star"];
                      $aMission["star"]  = $new_star;                  
                      //переписать в stage число star-----------------------------------------------
                      $listStage = Model::factory("stage")->getList(array("user_id" => $user_id, "stage_stat_id" => $aMission["mission_stat_id"]));
                      $aStage    = $listStage[0];
                      if(is_array($aStage) && 0 != count($aStage)){
                          $aStage["star"] = $aStage["star"] + $new_star - $old_star;
                          Model::factory("stage")->create($aStage);
                      }
                      //----------------------------------------------------------------------------
                  } else {
                      $flag_win_without_new_star = true;
                  }
                  //--------------------------------------------------------------------------------
                  //--------------------------------------------------------------------------------
                  //--------------------------------------------------------------------------------
                  
                  //--------------------------------------------------------------------------------
                  //--------------------------------------------------------------------------------
                  //--------------------------------------------------------------------------------

                  $prize = array("booster_type" => 0, "booster_count" => 0, "money" => 0, "exp" => 0, "energy" => 0, "money2" => 0);
                  $prize2 = array("booster_type" => 0, "booster_count" => 0, "money" => 0, "exp" => 0, "energy" => 0, "money2" => 0);
                  $prize3 = array("booster_type" => 0, "booster_count" => 0, "money" => 0, "exp" => 0, "energy" => 0, "money2" => 0);
                  
                  if(false == $flag_win_without_new_star){
                      for($star_number = 3; $star_number > 0; $star_number-- ){
                          if(true == ${"prize_star_".$star_number}){
                          
                              if(0 == $mission_prize_sum_system){
                                  
                                  if( $old_star > 0 ){
                                  
                                      continue;      //уже выйгрыш за раунд получен, нового выйграша не будет
                                  
                                  }
                                  if(3 == $star_number || 2 == $star_number)
                                      {
                                          continue;  //перескакиваем на следующую итерацию
                                                     // т.е. обрабатываем приз который прописан для 1й звезды, остальные призы не учитываем, сколько бы звезд не было
                                      }
                              }   
                              
                              $prize_number = $star_number; 
                              if($star_number == 1){
                                  $prize_number = '';
                              }
                              
                              $booster_type  =  $aMissionStat['prize'.$prize_number.'_booster_type'];
                              $booster_count =  $aMissionStat['prize'.$prize_number.'_booster_count'];
                              $money1        =  $aMissionStat['prize'.$prize_number.'_money1'];
                              $money2        =  $aMissionStat['prize'.$prize_number.'_money2'];
                              $energy        =  $aMissionStat['prize'.$prize_number.'_energy'];
                              $exp           =  $aMissionStat['prize'.$prize_number.'_exp'];
                              
                              
                              if($booster_count > 0){
                                  Model::factory("user_booster", $user_id)->giveBoosterToUser( array( $booster_type => $booster_count) );
                                  
                                  ${"prize".$prize_number}["booster_type"] =  $booster_type;
                                  ${"prize".$prize_number}["booster_count"] = $booster_count;
                              }
                              
                              if($money1 > 0){
                                   Model::factory("user", $user_id)->changeMoney( $money1, 0, 1);
                                   ${"prize".$prize_number}["money"] = $money1;
                              }
                              
                              if($money2 > 0){
                                   Model::factory("user", $user_id)->changeMoney( 0, $money2, 1);
                                   
                                   ${"prize".$prize_number}["money2"] = $money2;
                              }
                              
                              if($energy > 0){
                                    Model::factory("user", $user_id)->changeEnergy( + $energy);
                                    ${"prize".$prize_number}["energy"] = $energy;
                              }
                              
                              
                              if($exp > 0){
                                   $reason_id = 100;
                                   Model::factory("user", $user_id)->changeExp($exp, $reason_id);
                                   ${"prize".$prize_number}["exp"] = $exp;
                              }
                          }
                      }
                  }
                  
                 
              
              
            
              $this->create($aMission);
              $this->save();
              Model::factory("mission_key", $user_id)->deleteKey( $start_key );
              
              //-------------------------------------------------------------------------------- 
              //---------------------------------------------------------------------------------------------------
              //записываем статистику по миссии
              //$initial_action(последний аргумент): 0 - начало миссии, 1 - успешное завершение миссии, 2 - проигрыш миссии,
              $initial_action = 1;
              $a = Model::factory("statistics_mission")->updateCounts($user_id, $mission_stat_id, $initial_action, $new_point, $new_star);
              //---------------------------------------------------------------------------------------------------
              
              
              if($flag_win_without_new_star == true)
              {
                  return array("result" => 1, "mission" => array("mission_stat_id" => $mission_stat_id, "point" => $new_point, "star" => $new_star), "prize" => $prize, "prize2" => $prize2, "prize3" => $prize3);  
              } 
              
              return array("result" => 1, "mission" => array("mission_stat_id" => $mission_stat_id, "point" => $new_point, "star" => $new_star), "prize" => $prize, "prize2" => $prize2, "prize3" => $prize3);
                   
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "missionModel", "endMission", $user_from);
            throw new Exception ($e->getMessage(), $e->getCode());
        } 
    }
    
    /*
    *
    * Посчитать все stars набранные игроком за во всех играх
    * 
    * Посчитать все stars набранные игроком за во всех играх 
    * 
    */
    public function calculateStars($user_id){
        try{
            if(!Model::factory('user', $user_id)->exist()){
                errors::exc(errors::errorIncorrectInput, "user id not exist");
            }
            $list_mission = $this->getListMission( $user_id ); 
            $star = 0;
            foreach($list_mission as $mission){
                $star+= $mission["star"];
            }                            
      
            return $star;
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "missionModel", "calculateStars", $user_from);
            throw new Exception ($e->getMessage(), $e->getCode());
        } 
    }  
    
    
    
    
       
}


      

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

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


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

<?php
/**
 * 
 */
class event_statModel extends Model {
    
  protected $_tableName = 'event_stat';

     //-----------------------------------------------------------------------------------------------------------------------
     //-----------------------------------------------------------------------------------------------------------------------
     //-----------------------------------------------------------------------------------------------------------------------
     //-----------------------------------------------------------------------------------------------------------------------
     //-----------------------------------------------------------------------------------------------------------------------
    
       
}


      

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

<?php
/**
 * 
 */
class missionModel extends Model {
    
  protected $_tableName = 'mission';

     //-----------------------------------------------------------------------------------------------------------------------
     //-----------------------------------------------------------------------------------------------------------------------
     //-----------------------------------------------------------------------------------------------------------------------
     //-----------------------------------------------------------------------------------------------------------------------
     //-----------------------------------------------------------------------------------------------------------------------
   
    
    
  
  
  
  
  
  
 
  
  
 
  
  

  
  
  public function getListMission($user_id){
       try{
           if(!Model::factory('user', $user_id)->exist()){
               return array();
               // errors::exc(errors::errorIncorrectInput, "user $user_id id not exist");
           }
           $listMission =  $this->getList(array("user_id" => $user_id));
           foreach($listMission as &$mission){
               if(isset($mission['user_id'])){
                   unset($mission['user_id']); 
               }
           }
           
           if(!is_array( $listMission ) || 0 == count($listMission)){
              $listMission = array(); 
           }
           
           return $listMission;
       } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "missionModel", "getListMission", $user_from);
            throw new Exception ($e->getMessage(), $e->getCode());
        } 
  } 
  
  public function getMissionByStatId($user_id, $mission_stat_id){
       try{
           if(!Model::factory('user', $user_id)->exist()){
               return array();
               // errors::exc(errors::errorIncorrectInput, "user $user_id id not exist");
           }  
           if(!Model::factory('mission_stat', $mission_stat_id)->exist()){
                errors::exc(errors::errorIncorrectInput, "mission stat id not exist");
           }
           
           $aMission = array();
           $listMission =  $this->getList(array("user_id" => $user_id, "mission_stat_id" => $mission_stat_id));
           if(0 != count($listMission)){
             $aMission = $listMission[0];  
           }
           if(count($listMission) > 1){
               foreach($listMission as $mission){
                   if($aMission["id"] != $mission["id"]){
                       $this->delete(array("id" => $mission["id"]));
                       $this->save();
                   }
               }
           }
           
           return $aMission;
       } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "missionModel", "getListMission", $user_from);
            throw new Exception ($e->getMessage(), $e->getCode());
        } 
  }
  
  
  
  public function checkAllPreviousMissionCompleted($user_id, $mission_stat_id){
       try{
           
              $aMissionStat =   Model::factory('mission_stat', $mission_stat_id)->get();
              $stage  = $aMissionStat["stage_stat_id"]; 
             
              //Условие начала миссии.
              //1. Если миссия первая в списке миссий этапа
              //2. Все предыдущие миссии уже игрались. 
             
             
              $listStageMissionStat = array();
              //Находим все статические миссиис сортировкой по полю position-------------------------------------------------------------------------
              $listStageMissionStat = Model::factory("mission_stat")->getList(array("stage_stat_id" => $stage), array("id", "position"), "position");
              
              if( 0 == count($listStageMissionStat)){
                   errors::exc(errors::errorIncorrectInput, "stage missions stat not exist");
              }
              
              $arr_mission_stat = array();
              
              //1. Если миссия первая в списке миссий этапа---------------------------------------
              $arr_mission_stat = reset($listStageMissionStat);
              if($aMissionStat["position"] == $arr_mission_stat["position"]){
                  return true;
              }
              //----------------------------------------------------------------------------------
               
              end($listStageMissionStat);
              $arr_mission_stat = current($listStageMissionStat);
              
              //находим текущую позицию-------------------------------------------
              do {
                  if($aMissionStat["position"] == $arr_mission_stat["position"]){
                      break;
                  }
                  $arr_mission_stat = prev($listStageMissionStat);    
              } while( FALSE != $arr_mission_stat );  

              //2. Все предыдущие миссии уже игрались---------------------------------------------
               $arr_mission_stat = prev($listStageMissionStat);
               if(FALSE == $arr_mission_stat){
                   return true;
               }  
               
               do {
                   $aMissionPrevious = $this->getMissionByStatId($user_id, $arr_mission_stat["id"]);
                   if(0 == count($aMissionPrevious)){
                       return false;
                   }
                   $arr_mission_stat = prev($listStageMissionStat);    
              } while( FALSE != $arr_mission_stat );  
              //----------------------------------------------------------------------------------
              
       return true;              
              
       } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "missionModel", "getListMission", $user_from);
            throw new Exception ($e->getMessage(), $e->getCode());
        } 
  }
  
  
  
  
   public function startMission($user_id, $mission_stat_id){
       try{
              if(!Model::factory('user', $user_id)->exist()){
                  errors::exc(errors::errorIncorrectInput, "user id not exist");
              }
              if(!Model::factory('mission_stat', $mission_stat_id)->exist()){
                  errors::exc(errors::errorIncorrectInput, "mission stat id not exist");
              }
              
              $aMissionStat = Model::factory('mission_stat', $mission_stat_id )->get(); 
              
              //-----------------------------------------------------------------------------------
              $listStage = Model::factory("stage")->getList(array("user_id" => $user_id, "stage_stat_id" => $aMissionStat["stage_stat_id"]));
              if(!is_array($listStage) || 0 == count($listStage)){
                  return array("result" => -141, "text" => "user stage not exist");  
              }
              //-----------------------------------------------------------------------------------
              
              $aMission = $this->getMissionByStatId($user_id, $mission_stat_id);
              
              //Условия начала миссии--------------------------------------------------------------
              //1. Если миссия уже игралась, то можно ее переиграть (в любом случае)
              //2. Если миссия первая в списке миссий этапа
              //3. Все предыдущие миссии уже игрались 
              
              if(0 == count($aMission)){
                  if(!$this->checkAllPreviousMissionCompleted($user_id, $mission_stat_id)){
                      return array("result" => -141, "text" => "not completed the previous mission");
                  }     
              } else {
                  if(0 == $aMissionStat["replay_flag"]){
                      return array("result" => -142, "text" => "replay unavailable for this mission");
                  }
              }
              //-----------------------------------------------------------------------------------
              
              $CostEnergy = Model::factory ( 'var' )->loadByKey ( 'mission_start_energy' )->value;
             
              if(!Model::factory("user", $user_id)->checkEnergy($CostEnergy)){
                  return array("result" => -3, "text" => "not enough energy");  
              }   
              
              $start_key = Model::factory("mission_key", $user_id)->setKey( $mission_stat_id );
             
              Model::factory("user", $user_id)->changeEnergy( - $CostEnergy);
              

              
              //---------------------------------------------------------------------------------------------------
              //записываем статистику по миссии
              //$initial_action(последний аргумент): 0 - начало миссии, 1 - успешное завершение миссии, 2 - проигрыш миссии,
              $initial_action = 0;
              $a = Model::factory("statistics_mission")->updateCounts($user_id, $mission_stat_id, $initial_action);
              //---------------------------------------------------------------------------------------------------
              
              return array("result" => 1, "mission" => array("mission_stat_id" => $mission_stat_id, "start_key" => $start_key ));
                   
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "missionModel", "startMission", $user_from);
            throw new Exception ($e->getMessage(), $e->getCode());
        } 
    }
    
    /*
    *
    * id миссии в аргументах вабрики прислать
    */
    
    public function endMission($user_id, $start_key, $new_point){
       try{
              if(!Model::factory('user', $user_id)->exist()){
                  errors::exc(errors::errorIncorrectInput, "user id not exist");
              }
              
              //-------------------------------------------------------------------------------------
              //флаг, определяющий каким образом подсчитывается выйгрыш в миссии
              $mission_prize_sum_system = 0;
              $mission_prize_sum_system = Model::factory ( 'var' )->loadByKey ( 'mission_prize_sum_system' )->value;
              if(1 == is_null($mission_prize_sum_system)){
                  $mission_prize_sum_system = 0;
              }
              //-------------------------------------------------------------------------------------
              
              
              //-------------------------------------------------------------------------------------
              $mission_stat_id = 0;
              $aMissionStat    = array();
              $aStage          = array();   
              //-------------------------------------------------------------------------------------
              
              if(!Model::factory("mission_key", $user_id)->checkKey( $start_key, $mission_stat_id )){
                  return array("result" => -2, "text" => "wrong mission start_key");
              }
              
              if(!Model::factory('mission_stat', $mission_stat_id)->exist()){
                  errors::exc(errors::errorIncorrectInput, "mission stat id not exist");
              }
              
             
              $aMissionStat = Model::factory('mission_stat', $mission_stat_id )->get();
              
              $point_in_star1  =  $aMissionStat['point_in_star1'];
              if( 1 == is_null($aMissionStat['point_in_star1']) ){
                  $point_in_star1 = 2147483647;
              }
              $point_in_star2  =  $aMissionStat['point_in_star2'];
              if( 1 == is_null($aMissionStat['point_in_star2']) ){
                  $point_in_star2 = 2147483647;
              }
              $point_in_star3  =  $aMissionStat['point_in_star3'];
              if( 1 == is_null($aMissionStat['point_in_star3']) ){
                  $point_in_star3 = 2147483647;
              }
              
              $new_star = 0;
              $old_star = 0;
              
              if($new_point > 0){
                  if( $new_point   >=  $point_in_star3){
                      $new_star = 3;
                  } else if( $new_point  >=  $point_in_star2){
                      $new_star = 2;
                  } else if( $new_point  >=  $point_in_star1){
                      $new_star = 1;
                  } 
              }
              $flag_win_without_new_star = false;
              
              if(0 == $new_star){
                  //если нет ни одной звесзы,
                  //миссия проиграна
              
                  //перед завершением миссии записываем статистику миссии:
                  //---------------------------------------------------------------------------------------------------
                  //записываем статистику по миссии
                  //$initial_action(последний аргумент): 0 - начало миссии, 1 - успешное завершение миссии, 2 - проигрыш миссии,
                  $initial_action = 2;
                  $a = Model::factory("statistics_mission")->updateCounts($user_id, $mission_stat_id, $initial_action, $new_point, $new_star);
                 //---------------------------------------------------------------------------------------------------
              
                  
                  
                  
				  return array("result" => 0);
                  
              } else {
         
                  //если есть хотябы одна звезда,
                  //миссия выйграна
                  
                  //возвращаем энергию, забранную до начала миссии----------------------------------
				  $flagReturnEnergy = Model::factory ( 'var' )->loadByKey ( 'mission_energy_win_return' )->value;
                  if($flagReturnEnergy == 1){
					  $CostEnergy = Model::factory ( 'var' )->loadByKey ( 'mission_start_energy' )->value;
				   	  Model::factory("user", $user_id)->changeEnergy( + $CostEnergy);
                  }
				  //--------------------------------------------------------------------------------         
              }
                 
              
              $aMission = $this->getMissionByStatId($user_id, $mission_stat_id);
    
              if(0 == count($aMission)){
                  
                   $aMission = array( "user_id"           =>   $user_id,
                                      "mission_stat_id"   =>   $mission_stat_id, 
                                      "point"             =>   0, 
                                      "star"              =>   0);
              } 
            
              //только если очков больше чем было, перезаписываем очки! 
              //но можем перезаписать звезды, если в mission_stat изменились данные
              if($new_point    > $aMission["point"]){
                  $aMission["point"] = $new_point;
              }  
              
              //--------------------------------------------------------------------------------
              //--------------------------------------------------------------------------------
              //--------------------------------------------------------------------------------
              //учет количества звезд и призов за них
              $prize_star_1 = false;
              $prize_star_2 = false;
              $prize_star_3 = false;                 
              
                 
              
              #//win without progress################# 
              
                  if(1 == $mission_prize_sum_system){    
                     switch( $aMission["star"] ){
                         case 3:{
                            $flag_win_without_new_star = true;  
                         } break;
                         case 2:{
                            if($new_star        == 3){
                                $prize_star_3 = true;  
                            } else {
                                $flag_win_without_new_star = true;  
                            }
                         } break;
                         case 1:{
                            if($new_star        == 3){
                                $prize_star_3 = true;  
                                $prize_star_2 = true;  
                            } else if($new_star == 2){
                                $prize_star_2 = true;  
                            } else {
                                $flag_win_without_new_star = true;  
                            }
                         } break;
                         case 0:{
                            if($new_star        == 3){
                                $prize_star_3 = true;  
                                $prize_star_2 = true;
                                $prize_star_1 = true;  
                            } else if($new_star == 2){
                                $prize_star_2 = true;  
                                $prize_star_1 = true;  
                            } else if($new_star == 1){
                                $prize_star_1 = true;   
                            } else {
                                $flag_win_without_new_star = true; 
                            }
                         } break;
                     }
                     
                  } else {
                       if($new_star > 0){
                           
                           $prize_star_1 = true;
                           $prize_star_3 = false;   
                           $prize_star_2 = false;   
                           
                       }  
                  }
                  
                  
                   //--------------------------------------------------------------------------------
                  //--------------------------------------------------------------------------------
                  //--------------------------------------------------------------------------------
                  if($new_star     > $aMission["star"]){
                      
                      $old_star          = $aMission["star"];
                      $aMission["star"]  = $new_star;                  
                      //переписать в stage число star-----------------------------------------------
                      $listStage = Model::factory("stage")->getList(array("user_id" => $user_id, "stage_stat_id" => $aMission["mission_stat_id"]));
                      $aStage    = $listStage[0];
                      if(is_array($aStage) && 0 != count($aStage)){
                          $aStage["star"] = $aStage["star"] + $new_star - $old_star;
                          Model::factory("stage")->create($aStage);
                      }
                      //----------------------------------------------------------------------------
                  } else {
                      $flag_win_without_new_star = true;
                  }
                  //--------------------------------------------------------------------------------
                  //--------------------------------------------------------------------------------
                  //--------------------------------------------------------------------------------
                  
                  //--------------------------------------------------------------------------------
                  //--------------------------------------------------------------------------------
                  //--------------------------------------------------------------------------------

                  $prize = array("booster_type" => 0, "booster_count" => 0, "money" => 0, "exp" => 0, "energy" => 0, "money2" => 0);
                  $prize2 = array("booster_type" => 0, "booster_count" => 0, "money" => 0, "exp" => 0, "energy" => 0, "money2" => 0);
                  $prize3 = array("booster_type" => 0, "booster_count" => 0, "money" => 0, "exp" => 0, "energy" => 0, "money2" => 0);
                  
                  if(false == $flag_win_without_new_star){
                      for($star_number = 3; $star_number > 0; $star_number-- ){
                          if(true == ${"prize_star_".$star_number}){
                          
                              if(0 == $mission_prize_sum_system){
                                  
                                  if( $old_star > 0 ){
                                  
                                      continue;      //уже выйгрыш за раунд получен, нового выйграша не будет
                                  
                                  }
                                  if(3 == $star_number || 2 == $star_number)
                                      {
                                          continue;  //перескакиваем на следующую итерацию
                                                     // т.е. обрабатываем приз который прописан для 1й звезды, остальные призы не учитываем, сколько бы звезд не было
                                      }
                              }   
                              
                              $prize_number = $star_number; 
                              if($star_number == 1){
                                  $prize_number = '';
                              }
                              
                              $booster_type  =  $aMissionStat['prize'.$prize_number.'_booster_type'];
                              $booster_count =  $aMissionStat['prize'.$prize_number.'_booster_count'];
                              $money1        =  $aMissionStat['prize'.$prize_number.'_money1'];
                              $money2        =  $aMissionStat['prize'.$prize_number.'_money2'];
                              $energy        =  $aMissionStat['prize'.$prize_number.'_energy'];
                              $exp           =  $aMissionStat['prize'.$prize_number.'_exp'];
                              
                              
                              if($booster_count > 0){
                                  Model::factory("user_booster", $user_id)->giveBoosterToUser( array( $booster_type => $booster_count) );
                                  
                                  ${"prize".$prize_number}["booster_type"] =  $booster_type;
                                  ${"prize".$prize_number}["booster_count"] = $booster_count;
                              }
                              
                              if($money1 > 0){
                                   Model::factory("user", $user_id)->changeMoney( $money1, 0, 1);
                                   ${"prize".$prize_number}["money"] = $money1;
                              }
                              
                              if($money2 > 0){
                                   Model::factory("user", $user_id)->changeMoney( 0, $money2, 1);
                                   
                                   ${"prize".$prize_number}["money2"] = $money2;
                              }
                              
                              if($energy > 0){
                                    Model::factory("user", $user_id)->changeEnergy( + $energy);
                                    ${"prize".$prize_number}["energy"] = $energy;
                              }
                              
                              
                              if($exp > 0){
                                   $reason_id = 100;
                                   Model::factory("user", $user_id)->changeExp($exp, $reason_id);
                                   ${"prize".$prize_number}["exp"] = $exp;
                              }
                          }
                      }
                  }
                  
                 
              
              
            
              $this->create($aMission);
              $this->save();
              Model::factory("mission_key", $user_id)->deleteKey( $start_key );
              
              //-------------------------------------------------------------------------------- 
              //---------------------------------------------------------------------------------------------------
              //записываем статистику по миссии
              //$initial_action(последний аргумент): 0 - начало миссии, 1 - успешное завершение миссии, 2 - проигрыш миссии,
              $initial_action = 1;
              $a = Model::factory("statistics_mission")->updateCounts($user_id, $mission_stat_id, $initial_action, $new_point, $new_star);
              //---------------------------------------------------------------------------------------------------
              
              
              if($flag_win_without_new_star == true)
              {
                  return array("result" => 1, "mission" => array("mission_stat_id" => $mission_stat_id, "point" => $new_point, "star" => $new_star), "prize" => $prize, "prize2" => $prize2, "prize3" => $prize3);  
              } 
              
              return array("result" => 1, "mission" => array("mission_stat_id" => $mission_stat_id, "point" => $new_point, "star" => $new_star), "prize" => $prize, "prize2" => $prize2, "prize3" => $prize3);
                   
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "missionModel", "endMission", $user_from);
            throw new Exception ($e->getMessage(), $e->getCode());
        } 
    }
    
    /*
    *
    * Посчитать все stars набранные игроком за во всех играх
    * 
    * Посчитать все stars набранные игроком за во всех играх 
    * 
    */
    public function calculateStars($user_id){
        try{
            if(!Model::factory('user', $user_id)->exist()){
                errors::exc(errors::errorIncorrectInput, "user id not exist");
            }
            $list_mission = $this->getListMission( $user_id ); 
            $star = 0;
            foreach($list_mission as $mission){
                $star+= $mission["star"];
            }                            
      
            return $star;
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "missionModel", "calculateStars", $user_from);
            throw new Exception ($e->getMessage(), $e->getCode());
        } 
    }  
    
    
    
    
       
}


      

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

<?php
/**
 * 
 * Класс модели пользователя
 */
class goldpriceModel extends Model {
	
	protected $_tableName = 'gold_prices';
	
}

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

<?php
/**
 * 
 */
class lotteryModel extends Model {
    
    
    /**
    * Запуск колеса фортуны
    * @param $cost_type 
    * @return mix return array("result" => 1, "cost_type" => $cost_type, "prize_sector" => $prize_sector, "prize" => $prize);
    */
    public function useLottery( $user_id, $cost_type = 0){
       try{
       
           
          if(  $cost_type < 0 || $cost_type > 1 ){
              errors::exc(errors::errorIncorrectInput, "cost_type $cost_type not exist");
          }
              
              
          $lottery_active_id          = Model::factory ( 'var' )->loadByKey ( 'lottery_active_id' )->value;
          $lottery_sector_count       = Model::factory ( 'var' )->loadByKey ( 'lottery_sector_count' )->value;
               
          if(!Model::factory('lottery_stat', $lottery_active_id)->exist()){
              errors::exc(errors::errorIncorrectInput, "lottery stat id not exist");
          }
                  
          $aLotteryStat = Model::factory('lottery_stat', $lottery_active_id )->get(); 


          $lottery_cost_money1    = $aLotteryStat["cost_money1"];
          $lottery_cost_money2    = $aLotteryStat["cost_money2"]; 
          //-----------------------------------------------------------------------------------------------
          //Проверить наличие средств для снятия 
          switch( $cost_type ){
              
              case 0:{
                 
                      
                 if( Model::factory("user", $user_id)->checkMoney( $lottery_cost_money1, 0) ){
                      
                      //$reason_id = 102;                                                                          
                      //Model::factory("user", $user_id)->changeMoney( - $lottery_cost_money1, 0, $reason_id);
                         
                 } else {
                 
                      return array("result" => -125, "text" => "not enough money1");
                 }
              } break;
              case 1:{
                  
                  
                  if( Model::factory("user", $user_id)->checkMoney( 0, $lottery_cost_money2) ){
                      
                      //$reason_id = 102;                                                                          
                      //Model::factory("user", $user_id)->changeMoney( 0, - $lottery_cost_money2, $reason_id);
              
                 } else {
                 
                      return array("result" => -125, "text" => "not enough money1");
                 
                 }
              } break;
              case 2:{
                  //открытие этапа за валюту соц сети
                  //действие доступно только из index_cback_od.php (в index_cback_vk.php обработчика нет)
            
              } break;
          }
          
          //-----------------------------------------------------------------------------------------------------------------
          
          
               
               
               if($lottery_sector_count > 8){
                 $lottery_sector_count = 8;  
               }
               if($lottery_sector_count < 1){
                  $lottery_sector_count = 1; 
               }
               
               $prize_sector_number = rand(0,$lottery_sector_count - 1 );
               
               $prize = array("booster_type" => 0, "booster_count" => 0, "money1" => 0, "exp" => 0, "energy" => 0);   
               
               
               $sector_type  = $aLotteryStat["sector_".$prize_sector_number."_type"];
               $sector_count = $aLotteryStat["sector_".$prize_sector_number."_count"];
               $sector_extra = $aLotteryStat["sector_".$prize_sector_number."_extra"];
          
               switch($sector_type){
                   
                   case 0 :{  // type : 0 - money1
                        $money1 = $sector_count;
                        if($money1 > 0){
                           
                            Model::factory("user", $user_id)->changeMoney( $money1, 0, 1);
                           
                            $prize["money1"] = $money1;
                        }
                   } break;
             
                   case 1 :{  // type : 1 - energy
                        
                        $energy = $sector_count;
                        
                        if($energy > 0){
                        
                            Model::factory("user", $user_id)->changeEnergy( + $energy);
                            $prize["energy"] = $energy;
                        }
                   
                   } break;
                   
                   case 2 :{  // type : 1 - booster
                    
                        $booster_type  = $sector_extra;
                        $booster_count = $sector_count;
                    
                        if($booster_count > 0){
                        
                           Model::factory("user_booster", $user_id)->giveBoosterToUser( array( $booster_type => $booster_count) );
                              
                           $prize["booster_type"]   = $booster_type;
                           $prize["booster_count"]  = $booster_count;
                        }
                   } break;
                   
                   case 3 :{  // type : 1 - exp
                        $exp = $sector_count;
                        if($exp > 0){
                        
                           $reason_id = 101;
                           Model::factory("user", $user_id)->changeExp($exp, $reason_id);
                           $prize["exp"] = $exp;
                        }
                   } break;
                   
                   case 4 :{  // type : 1 - action_id
                          
                           $prize["action_id"] = $sector_extra;
                   
                   } break;
                   default:{
                       
                   }
               }
               
               
               //-----------------------------------------------------------------------------------------------
          //Снятие среств 
          switch( $cost_type ){
              
              case 0:{
                  $reason_id = 102;                                                                          
                  Model::factory("user", $user_id)->changeMoney( - $lottery_cost_money1, 0, $reason_id);
              }break;
              case 1:{
                  
                  $reason_id = 102;                                                                          
                  Model::factory("user", $user_id)->changeMoney( 0, - $lottery_cost_money2, $reason_id);
              } break;
              case 2:{
                  //открытие этапа за валюту соц сети
                  //действие доступно только из index_cback_od.php (в index_cback_vk.php обработчика нет)
                  continue;   
              } break;
          }
          
          //-----------------------------------------------------------------------------------------------------------------
             
               return array("result" => 1, "cost_type" => $cost_type, "prize_sector_number" => $prize_sector_number, "prize" => $prize);
           
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "lotteryModel", "useLottery", $this->id);
            throw new Exception ($e->getMessage(), $e->getCode());
        }
    }  
    
       
}


      

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

<?php
/**
 * 
 * Обработка подарков 
 */
class giftModel extends Model {

    protected $_tableName = 'gift';
    
    /**
    * Создать запись
    */                                          
    public function createRecord( $user_id_out = -1, $user_id_in = -1, $type = -1, $count = 0, $status = 0, $time_now = 0){
        try{
            
            if(0 == $time){
                $time_now = SConfig::$time;
            }
            $arr_record = array(  "user_id_out" => $user_id_out, 
                                  "user_id_in"  => $user_id_in, 
                                  "type"        => $type, 
                                  "count"       => $count, 
                                  "status"      => $status,             
                                  "time"        => $time_now 
                               );
           
            return  Model::factory("gift")->create( $arr_record );
 
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "giftModel", "createRecord", $user_id_out);
            throw new Exception ($e->getMessage(), $e->getCode());
        } 
        
    }
    
    /**
    * Послать подарок
    *  -  -  (bigint)  user_from              : номер игрока из соц сети который посылает подарок
    *  -  -  (bigint)  user_to                : номер игрока из соц сети которому посылается подарок (который просит подарок)
    */                                          
    public function sendGift($user_from, $user_to, $type = -1, $count = 1, $ask_id = -1){
       try{
           
            if(!Model::factory('user', $user_from)->exist()){
                return array("result" => -1, "text" => "user_from not exist"); 
            }
            
            if(!Model::factory('user', $user_to)->exist()){
                //return array("result" => -1, "text" => "user_to not exist"); 
                //можно просить у того кого еще нет в игре
            }
            
            //-------------------------------------------------------------
            switch($type){
                case 0: //энергия
                break;
                case 1: //деньги
                break;
                default:
                   return array("result" => -2, "text" => "type not exist");  
                break;
            }
            //-------------------------------------------------------------
            
            $gift_time_limit       = Model::factory ( 'var' )->loadByKey ( 'gift_time_limit' )->value;
            
            $flag_new_send = false;
            $flag_answer_send = false;
            $gift_answer_send = array();
            $arr_gift = array();
            
            
            $list_gift = array();
            if( $ask_id != -1){
                //---------------------------------------------------------------------------------------
                $gift = array();
                if(!Model::factory("gift", $ask_id)->exist()){
                    return array("result" => -102, "text" => "ask not exist");
                } else {
                    $gift = Model::factory("gift", $ask_id)->get();
                    if($gift["user_id_out"] != $user_from || $gift["user_id_in"]!= $user_to){
                       return array("result" => -103, "text" => "user_out or user_in error"); 
                    }
                    
                    if( $gift["status"] == 2){
                        $this->timeToGift( $gift );
                        if($gift["time"] == 0){
                            Model::factory("gift")->delete(array("id" => $gift["id"] ));
                            return array("result" => -102, "text" => "ask not exist");
                        }
                    }
                    
                    if($gift["status"] != 0){
                       return array("result" => -104, "text" => "ask status error"); 
                    }
                }
                
                $flag_new_send    = false; 
                $flag_answer_send = true;
                $gift_answer_send = $gift;
                //---------------------------------------------------------------------------------------  
            } else {
                //---------------------------------------------------------------------------------------
            
                $list_gift = Model::factory("gift")->getList(array("user_id_out" => $user_from, "user_id_in" => $user_to));
                if( is_array($list_gift) && 0 != count($list_gift)){
                   
                   if(0 != count($list_gift)){
        
                       foreach($list_gift as $gift){
                          
                           if(2 == $gift["status"]){ 
                               $this->timeToGift( $gift );
                               if($gift["time"] == 0){
                                   Model::factory("gift")->delete(array("id" => $gift["id"] ));
                               }
                           }  
                           
                           if(0 == $gift["status"] && $type == $gift["type"]){
                                $gift_answer_send = $gift;  
                                $flag_answer_send = true;
                                break;               
                           }
                               
                           if(1 == $gift["status"] && $type == $gift["type"]){
                               $this->timeToGift( $gift );
                               if($gift["time"] == 0){
                                   $gift["time"] = SConfig::$time;
                                   Model::factory("gift")->create( $gift );
                                   $arr_gift = $gift; 
                                   break;
                               } else {
                                   return array("result" => -101, "text" => "too little time since the previous ask");
                               }
                           }
                       }
                   }
  
                } else {
                   $flag_new_send = true;
                }
                //---------------------------------------------------------------------------------------
            }
            
            if(true == $flag_new_send || true == $flag_answer_send) {
                $status   = 1; //подарок посылается
                
                 switch( $type ){
                     case 0:
                     case 1:
                         {
                          
                          //списать энергию--------------------------------------------------------
                          if(0){
                              $energy = Model::factory('user', $user_from)->checkEnergyRecoveryStatus();
                              if( $energy['energy'] < $count){
                                  return array("result" => -20, "text" => "nothing to give");
                              }
                              
                              $reason_id = 10; // Проверить!
                              Model::factory('user', $user_from)->changeEnergy( - $count,  $reason_id);
                          }
                          //-----------------------------------------------------------------------
                          
                          if(true == $flag_new_send ){
                           
                              $obj_gift = Model::factory("gift")->createRecord( $user_from, $user_to, $type, $count, $status);
                              $arr_gift = $obj_gift->get();
                         
                          } else if(true == $flag_answer_send){ 
                              
                              $gift_answer_send["status"] = $status;
                              $gift_answer_send["time"]   = SConfig::$time;
                              $obj_gift = Model::factory("gift")->create( $gift_answer_send ); 
                              $arr_gift = $obj_gift->get();  
                          }
                          
                     } break;
                 }
            }
           
           if( is_array($arr_gift) && 0 != count($arr_gift)){
               $this->timeToGift( $arr_gift );
               return array("result" => 1, "gift" => $arr_gift);
           } else {
               return array("result" => 0, "gift" => array()); 
           }
           
           
           
           return array();
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "giftModel", "sendGift", $user_from);
            throw new Exception ($e->getMessage(), $e->getCode());
        } 
    } 
    
    /**
    * Просить подарок
    */                                          
    public function askGift($user_from, $user_to, $type = -1, $count = 1){
        try{ 
           
            
            if(!Model::factory('user', $user_from)->exist()){
                //return array("result" => -1, "text" => "user_from not exist"); 
            }
            
            if(!Model::factory('user', $user_to)->exist()){
                return array("result" => -1, "text" => "user_to not exist"); 
                //можно просить у того кого еще нет в игре
            }
            
            //-------------------------------------------------------------
            switch($type){
                case 0: //энергия
                break;
                case 1: //деньги
                break;
                default:
                   return array("result" => -2, "text" => "type not exist");  
                break;
            }
            //-------------------------------------------------------------
            
            $flag_new_ask = true;
            $arr_gift = array();
            
            $list_gift = Model::factory("gift")->getList(array("user_id_out" => $user_from, "user_id_in" => $user_to));
            if( is_array($list_gift) && 0 != count($list_gift)){
               
                   foreach($list_gift as $gift){
                       if($type == $gift["type"]){
                             $arr_gift = $gift;
                             $flag_new_ask = false;
                             break;
                       }  
                   }
                   
            } else {
               $flag_new_ask = true; 
            } 
            
            if(true == $flag_new_ask) {
                $status   = 0;
                $obj_gift = Model::factory("gift")->createRecord( $user_from, $user_to, $type, $count, $status);
                $arr_gift = $obj_gift->get();
            }
           
           //ответы-----------------------------------------------------------------------------------
           if( is_array($arr_gift) && 0 != count($arr_gift)){
               $this->timeToGift( $arr_gift );
               if(true == $flag_new_ask){
                    $this->timeToGift( $arr_gift );
                    return array("result" => 1, "gift" => $arr_gift);                     
               }
           
               if($arr_gift["status"] == 0){
                   if($arr_gift["time"] <= 0){
                        $arr_gift["time"] =  SConfig::$time;
                        Model::factory("gift")->create( $arr_gift ); 
                        $this->timeToGift( $arr_gift );
                        return array("result" => 1, "gift" => $arr_gift);   
                   } else {
                        return array("result" => -101, "text" => "too little time since the previous ask");
                   }
               } else {
                   return array("result" => -105, "text" => "gift has already come or too little time since the previous get a gift");
               }

           } else {
               return array("result" => 0, "gift" => array()); 
           }
           //-----------------------------------------------------------------------------------------
    
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "giftModel", "askGift", $user_from);
            throw new Exception ($e->getMessage(), $e->getCode());
        } 
    }
    
    
    /**
    * Получить подарок
    */                                          
    public function getGift($user_id, $gift_id ){
       try{
           
            // $user_id = $user_to т.к. это тот игрок который забирает подарок 
            
            if(!Model::factory("gift", $gift_id)->exist()){
                return array("result" => -107, "text" => "gift not exist"); 
            }
            
            //-------------------------------------------------------------
            switch($type){
                case 0: //энергия
                break;
                case 1: //деньги
                break;
                default:
                   return array("result" => -2, "text" => "type not exist");  
                break;
            }
            //-------------------------------------------------------------
           
            $arr_gift = Model::factory("gift", $gift_id)->get();
            
            $user_from = $arr_gift["user_id_out"];
            $user_to   = $arr_gift["user_id_in"];
            $type      = $arr_gift["type"];
            $count     = $arr_gift["count"];
            
            if(!Model::factory('user', $user_from)->exist()){
                return array("result" => -1, "text" => "user_from not exist"); 
            }
            
            if(!Model::factory('user', $user_to)->exist()){
                return array("result" => -1, "text" => "user_to not exist"); 
            }
            
            $gift_time_limit       = Model::factory ( 'var' )->loadByKey ( 'gift_time_limit' )->value;
            
           

            $flag_gift    = false;
            
            if( $arr_gift["status"] == 2){
                 $this->timeToGift( $arr_gift );
                 if($arr_gift["time"] == 0){
                      Model::factory("gift")->delete(array("id" => $arr_gift["id"] ));
                      return array("result" => -102, "text" => "get not exist");
                 }
            }
                    
            if($arr_gift["status"] != 1){
                 return array("result" => -106, "text" => "get status error");
            } else {
          
                 $status   = 2; //подарок забирается
                 switch( $type ){
                     case 0:{
                          
                          $energy = Model::factory('user', $user_to)->checkEnergyRecoveryStatus();
                          
                          $reason_id = 11; // Проверить!
                          Model::factory('user', $user_to)->changeEnergy( $count,  $reason_id);
                          
                          $arr_gift["status"] = 2;
                          $arr_gift["time"]   = SConfig::$time;
                          $obj_gift = Model::factory("gift")->create( $arr_gift ); 
                          $arr_gift = $obj_gift->get();
                          $this->timeToGift( $arr_gift );
                          return array("result" => 1, "gift" => $arr_gift);
                          
                     } break;
                     case 1:{
                          
                          $money1    = $count;
                          $money2    = 0;
                          $reason_id = 11; // Проверить!
                          Model::factory('user', $user_to)->changeMoney( $money1,  0, $reason_id);
                          
                          $arr_gift["status"] = 2;
                          $arr_gift["time"]   = SConfig::$time;
                          $obj_gift = Model::factory("gift")->create( $arr_gift ); 
                          $arr_gift = $obj_gift->get();
                          $this->timeToGift( $arr_gift );
                          return array("result" => 1, "gift" => $arr_gift);
                          
                     } break;
                     default: {
                          return array("result" => -107, "text" => "gift type error");
                     }
                 }
            }
           
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "giftModel", "getGift", $user_id);
            throw new Exception ($e->getMessage(), $e->getCode());
        } 
    }
    
    /**
    * Получить свежие данные о подарках
    */                                          
    public function refreshGift($user_id){
       try{
           $arr_gift = array();
           $list_gift_from = Model::factory("gift")->getList(array("user_id_out" => $user_id));
           $list_gift_to   = Model::factory("gift")->getList(array("user_id_in" => $user_id));
           foreach($list_gift_from as $gift_from){
                           
