Часть 6 из 12
Строки: 10001-12000 из 22262
================================================================================

               
               $this->timeToGift( $gift_from );
               
               if($gift_from["status"] == 2 && $gift_from["time"] == 0){
                   Model::factory("gift")->delete(array("id" => $gift_from["id"] ));
               }
               
               $arr_gift[] = $gift_from;       
           }
           foreach($list_gift_to as $gift_to){
               
               $this->timeToGift( $gift_to );
               
               if($gift_to["status"] == 2 && $gift_to["time"] == 0){
                   Model::factory("gift")->delete(array("id" => $gift_to["id"] ));
               }
               
               $arr_gift[] = $gift_to; 
           }
           
           return array("result" => 1, "gift" => $arr_gift);
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "giftModel", "refreshGift", $user_from);
            throw new Exception ($e->getMessage(), $e->getCode());
        } 
    }
    
    public function timeToGift( &$arr_gift ){ 
        
         $gift_time_limit       = Model::factory ( 'var' )->loadByKey ( 'gift_time_limit' )->value;
            
         if( SConfig::$time > $arr_gift["time"] + $gift_time_limit ){
             $arr_gift["time"] = 0;
         } else {
             $arr_gift["time"] = $arr_gift["time"] + $gift_time_limit - SConfig::$time; 
         }
    }
    
    
      
}

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

<?php
/**
 * 
 * Тех таблица
 */
class library_statModel extends Model {

    protected $_tableName = 'library_stat';

}

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

<?php
/**
 * 
 * Хранит подобранный список плейлистов из таблицы user_playlsit, которые может использовать игрок в следующей дуэли(game)
 */
class user_playlist_setModel extends Model {
    
    protected $_tableName = 'user_playlist_set';
  
}

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

<?php
/**
 *    
 */
class user_playlistModel extends Model {
    
    protected $_tableName = 'user_playlist';
    
    //protected $_tableName = 'game';
    /**
    * Добавляет запись в user_playlist, не проверяет есть ли уже такая запись
    * @param $user_id id игрока в соц сети
    * @param use_status = 1 (0 - дается в аренду, 1 - отдается навсегда)
    * @param use_count  = 1 сколько раз можно использовать плейлист до того как он исчезнет из пользования, если use_status = 1, поле игнарируется
    * @return array $aNewPlaylist 
    */ 
    public function add($user_id, $playlist_id, $use_status = 1, $use_count = 1, $id_user_playlist = NULL) {
        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 stat id not exist");
            }
            
            $aPlaylist = array("user_id"     => $user_id, 
                               "playlist_id" => $playlist_id,
                               "use_status"  => $use_status,
                               "use_count"   => $use_count); 
                               
            if($id_user_playlist != NULL){
                $aPlaylist['id'] = $id_user_playlist; 
            }
            
            $oNewPlaylist  = $this->create( $aPlaylist );
            $this->save();
            $aNewPlaylist  = $oNewPlaylist->get();
            
            unset($aNewPlaylist['user_id']);
            
            return $aNewPlaylist;
            
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "user_playlistModel", "get_available_playlist_set", $user_id);
            throw new Exception ($e->getMessage(), $e->getCode());
        }
    }
    
    //protected $_tableName = 'game';
    /**
    * Предоставить список доступных плейлистов (id статических плейлистов)
    * @param $user_id id игрока в соц сети
    * @param $count число возвращаемых плейлистов id игрока в соц сети
    * @param $flag_all флаг, в случае если флан TRUE возвращаются все возможные доступные плейлисты
    * @param use_status = 1 (0 - дается в аренду, 1 - отдается навсегда)
    * @param use_count  = 1 сколько раз можно использовать плейлист до того как он исчезнет из пользования, если use_status = 1, поле игнарируется
    * @return array $aPlaylistStatSet
    */ 
    public function get_available_playlist_set($user_id, $count = 4, $flag_all = FALSE) {
        try{
            
            if(!Model::factory("user", $user_id)->exist()){
                errors::exc(errors::errorIncorrectInput, "user id not exist");
            }
            
            $aPlaylistStatSet = array();
            $listUserPlaylist = $this->getList(array("user_id" => $user_id));
            foreach($listUserPlaylist as $aUserPlaylist){
                if(!in_array($aUserPlaylist["playlist_id"], $aPlaylistStatSet)){
                    if($this->check_playlist_available($user_id, $aUserPlaylist['playlist_id'])){
                         $aPlaylistStatSet[] = $aUserPlaylist["playlist_id"];
                    }
                }
            }
            $aPlaylistStatSet = array_unique($aPlaylistStatSet);                 //удаляем повторяющиеся по значению элементы 
           
            shuffle ( $aPlaylistStatSet );                                       //перемешиваем массив   
            
            if(count($aPlaylistStatSet) > $count && $flag_all != TRUE){
                 $aPlaylistStatSet = array_slice($aPlaylistStatSet , 0, $count);                     //оставляем только первых $count значений(сбрасываем ключи массива)
            } else{
                 $aPlaylistStatSet = array_slice($aPlaylistStatSet, 0, count($aPlaylistStatSet));    //сбрасываем ключи массива 
            } 
            return $aPlaylistStatSet;
            
            
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "user_playlistModel", "get_available_playlist_set", $user_id);
            throw new Exception ($e->getMessage(), $e->getCode());
        } 
    }
    
    
    /**
    * Проверяет доступен ли данный статический плейлист для пользователя, удаляет все нелегальные плейлисты, если такие имеются 
    * @param $user_id 
    * @param $playlist_id 
    * @param $out_playlist_id значение походящего плейлиста, возвращаемый параметр.
    * @return bool (+ параметр возвращаемый по ссылке ) 
    */ 
    public function check_playlist_available($user_id, $playlist_id, &$out_playlist_id = NULL) {
        try{
            if($out_playlist_id != NULL){
               $out_playlist_id = NULL; 
            }
            
            if(!Model::factory("user", $user_id)->exist()){
                errors::exc(errors::errorIncorrectInput, "user id not exist");
            }
            if(!Model::factory("playlist_stat", $playlist_id)->exist()){
                $listNotExistPlaylist = $this->getList(array("user_id" => $user_id, "playlist_id" => $playlist_id));
                foreach($listNotExistPlaylist as $aPlaylist){
                    Model::factory("user_playlist", $aPlaylist["id"])->delete();
                    //или $this->delete(array("id" => $aPlaylist["id"]));
                }
                return false;
            }
            
            $aPlaylistStatSet = array();
            $listUserPlaylist = $this->getList(array("user_id" => $user_id, "playlist_id" => $playlist_id));
            if(0 == count($listUserPlaylist)){
                return false;
            } else if(1 == count($listUserPlaylist)){
                 if($listUserPlaylist[0]['use_status'] == 1 || ($listUserPlaylist[0]['use_status'] == 0 && $listUserPlaylist[0]['use_count'] > 0 )){
                      
                      $out_playlist_id = $listUserPlaylist[0]["id"];
                     
                      return true;
                 } else {
                      //if($listUserPlaylist[0]['use_status'] == 0 && $listUserPlaylist[0]['use_count'] <= 0 ){
                           //---------------------------------------------------------------------------------
                           //аренда закончилась, сбой, удаление лишнего плейлиста 
                           Model::factory("user_playlist", $listUserPlaylist[0]["id"])->delete();
                           //или $this->delete(array("id" => $listUserPlaylist[0]["id"]));
                           //---------------------------------------------------------------------------------
                           return false;    
                      //}
                      //return true;
                 } 
            } else {
            //удаление лишних, в случае если они по-каким причинам их много-------------------------------------------------------------------
            //---------------------------------------------------------------------------------
                       
                 $iPermanentPlaylist = NULL;
                 $iRentPlaylist      = NULL;
                 $iRentUseCountMax   = 0;
                 
                 foreach($listUserPlaylist as $aPlaylist){
                     if(1 == $aPlaylist['use_status']){
                         $iPermanentPlaylist = $aPlaylist['id'];
                         break;
                     } else {
                         if($iRentUseCountMax < $aPlaylist['use_count']){
                              $iRentPlaylist      = $aPlaylist['id'];
                              $iRentUseCountMax   = $aPlaylist['use_count'];    
                         }
                     }
                 }
                 
                 if(NULL == $iPermanentPlaylist && NULL == $iRentPlaylist){ 
                     return false;
                 }
                 
                 foreach($listUserPlaylist as $aPlaylist){
                     if(NULL != $iPermanentPlaylist){
                         if($aPlaylist['id'] != $iPermanentPlaylist){
                              Model::factory("user_playlist", $aPlaylist['id'])->delete();
                              //или $this->delete(array("id" => $aPlaylist['id']));   
                         } else {
                              $out_playlist_id = $iPermanentPlaylist;
                         }
                     } else {
                         if(NULL != $iRentPlaylist){
                             if($aPlaylist['id'] != $iRentPlaylist){
                                 Model::factory("user_playlist", $aPlaylist['id'])->delete();
                                 //или $this->delete(array("id" => $aPlaylist['id']));   
                             } else {
                                $out_playlist_id = $iRentPlaylist; 
                             }
                         }
                     }
                 }
                 return true;
            }    
                   //----------------------------------------------------------------------------------
            return false;
            
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "user_playlistModel", "check_playlist_available", $user_id);
            throw new Exception ($e->getMessage(), $e->getCode());
        } 
    }
    
    
    /**
    * Проверяет доступен ли данный статический плейлист для пользователя, и если доступный использует его
    * в случае если плейлист куплен арендован - уменьшает число доступных игр
    * @param bigint $user_id     номер игрока в соц. сети
    * @param int    playlist_id  номер прейлиста в таблице playlist_stat
    * @return bool  
    */ 
    public function usePlaylist($user_id, $playlist_id){
        try{
            if(!$this->check_playlist_available($user_id, $playlist_id, $out_playlist_id)){
                return false;
            } else {
                if(!Model::factory("user_playlist", $out_playlist_id)->exist()){
                    errors::exc(errors::errorIncorrectDBValue, "out playlist id not exist");
                }
                $aPlaylist = Model::factory("user_playlist", $out_playlist_id)->get();
                if($aPlaylist['use_status'] == 1){
                    return true;
                } else if($aPlaylist['use_status'] == 0){
                    if($aPlaylist['use_count'] > 0){
                        $aPlaylist['use_count'] = $aPlaylist['use_count'] - 1;
                        Model::factory("user_playlist")->create($aPlaylist);
                        return true;
                    } else {
                        Model::factory("user_playlist", $out_playlist_id)->delete();
                        //или Model::factory("user_playlist")->delete(array('id' => $out_playlist_id));
                        return false;
                    }
                } else {
                    errors::exc(errors::errorIncorrectDBValue, "playlist status is incorrect");
                }
                
                errors::exc(errors::errorUnexpectedEnd, "unexpected end of function");
                return false;
                 
            }
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "user_playlistModel", "use_playlist", $user_id);
            throw new Exception ($e->getMessage(), $e->getCode());
        }
    }
    
    
    /**
    * Покупает или берет в аренду плейлист
    * @param bigint  $user_id                номер игрока из соц сети
    * @param int     $shop_playlist_stat_id  номер плейлиста из таблицы shop_playlist_stat
    * @param int    sale_method    способ продажи
    *  - sale_method = 0, продажа из магазина в игре, за игровую валюту 
    *  - sale_method = 1, продажа за валюту соц сети, <b>фактически дарение</b>, 
    * т.к. обработка списания валюты соц.сети сводится к возврату положительного ответа на запрос 
    * от сервера соц.сети, без явного запроса на списание валюты
    * игнорируются стоимость валюте1,валюте2 и энергии (соответственно cost_money1, cost_money2, cost_energy)
    * а также флаг видимости в игровом магазине (visible_flag) 

    * @return array = array("result" => 1, 'shop_playlist_stat_id' => int, "user_playlist" => $array());
    */ 
    public function buyPlaylist($user_id, $shop_playlist_stat_id ) {
        try{
            
            
            if(!Model::factory('user', $user_id)->exist()){
                return array("result" => -1, "text" => "user not exist"); 
            }
            
            if(!Model::factory("shop_playlist_stat", $shop_playlist_stat_id)->exist()){
                return array("result" => -2, "text" => "no entry in the price of store "); 
            }          
               
            $aPrice = Model::factory("shop_playlist_stat", $shop_playlist_stat_id)->get();
            $aUserProfile  = Model::factory("user",$user_id)->getProfile();
            
            $CostMoney1 = $aPrice["cost_money1"];
            $CostMoney2 = $aPrice["cost_money2"];
            $CostEnergy = 0;//$CostEnergy = $aPlaylistInfo["cost_energy"];
                                                                                        
            //!!!ситуация когда плейлист взят в аренду, но его пытаются купить навсегда, т.к. 
            //-----------------------------------------------------------------------------------
            if(!Model::factory("playlist_stat", $aPrice["buy_playlist"])->exist()){
                return array("result" => -1, "text" => "playlist not exist");  
            }
 
            if($aPrice["visible_flag"] == 0){
                return array("result" => -2, "text" => "price record is not available now");  
            }
                
            if(!Model::factory("user", $user_id)->checkMoney($CostMoney1, $CostMoney2)){
                return array("result" => -3, "text" => "not enough money");  
            }
                //if(!Model::factory("user", $user_id)->checkEnergy($CostEnergy)){
                //    return array("result" => -4, "text" => "not enough energy");  
                //}
            if(! Model::factory("shop_playlist_set_stat", $shop_playlist_stat_id)->exist()){
               return array("result" => -2, "text" => "no entry in the price of store "); 
            }
            
            //-----------------------------------------------------------------------------------
            $playlist_info = Model::factory("shop_playlist_set_stat", $aPrice["buy_playlist"])->get();
            $aPlaylistInfo["playlist_id"]  = $playlist_info["type"];
            $aPlaylistInfo["use_status"]   = $playlist_info["status"];
            $aPlaylistInfo["use_count"]        = $playlist_info["count"];
            //-----------------------------------------------------------------------------------
            //$resultGive = $this->givePlaylistSet($user_id, $shop_playlist_stat_id );
            $resultGive = $this->givePlaylistToUser($user_id, array( $aPlaylistInfo["playlist_id"] ), $aPlaylistInfo["use_status"], $aPlaylistInfo["use_count"]);
            //givePlaylistToUser обрабатывает попытку добавления плейтиста в пользовании пользователя следующим образом:
            //1.если плейлиста нет, он добавляется (возвращается в a_playlist)
            //2.если прейлист уже есть у пользователя в пользовании, происходит следующее: 
            //-в случае если плейлист уже есть со статусом "взят в аренду", он еще раз не может быть добавлен со статусом "сдан в аренду" (возвращается в массиве a_playlist_already_get)
            //-в случае если плейлист уже есть со статусом "взят в аренду", он может быть добавлен со статусом "куплен навсегда" (возвращается в массиве a_playlist)
            //3.если плейлист добавлен со статусом "куплен навсегда", он не может быть еще раз добавлен (возвращается в массиве a_playlist_already_get)
  
            $userPlaylistRecord = array();
            if($resultGive['result'] !=1){
                return array("result" => -7, 'test' => "error in give playlist function");
            } else {
                if( 1 != empty($aPlaylistInfo) && 1 != empty($resultGive["a_playlist"])){
                    foreach($resultGive["a_playlist"] as $val){
                        if($aPlaylistInfo["playlist_id"] == $val["playlist_id"]){
                            $reason_id = 7;                        //аренда плейлиста 
                            if($aPlaylistInfo["use_status"] == 1){ //покупка плейлиста
                               $reason_id = 8; 
                            }    
                            ///деньги списать-------------------------------------------------------------------
                            
                            Model::factory( "user", $user_id)->changeMoney( - $CostMoney1, - $CostMoney2, $reason_id);
                            Model::factory( "user", $user_id)->changeEnergy( - $CostEnergy, $reason_id);
                            //----------------------------------------------------------------------------------
                            return array("result" => 1, 'shop_playlist_stat_id' => $shop_playlist_stat_id, "user_playlist" => $val);
                        }
                    }
                } else if( 1 != empty($aPlaylistInfo) && 1 != empty($resultGive["a_playlist_already_get"])){
                    foreach($resultGive["a_playlist_already_get"] as $val){
                         if($aPlaylistInfo["playlist_id"] == $val["playlist_id"]){
                             if($aPlaylistInfo["use_status"] == 1){
                                return array("result" => -5, 'test' => "playlist already bought");    
                             } else {
                                return array("result" => -6, 'test' => "playlist already in rent");
                             }
                                  
                         }
                     }
                } else if(1 != empty($aPlaylistInfo) && 1 != empty($resultGive["a_playlist_change"])){
                    foreach($resultGive["a_playlist_change"] as $val){
                         if($aPlaylistInfo["playlist_id"] == $val["playlist_id"]){
                            $reason_id = 8;                        //покупка плейлиста 
                            ///деньги списать-------------------------------------------------------------------
                            
                            Model::factory( "user", $user_id)->changeMoney( - $CostMoney1, - $CostMoney2, $reason_id);
                            Model::factory( "user", $user_id)->changeEnergy( - $CostEnergy, $reason_id);
                            
                            //----------------------------------------------------------------------------------
                            return array("result" => 1, 'shop_playlist_stat_id' => $shop_playlist_stat_id, "user_playlist" => $val);
                         }
                     }
                }
                return array("result" => -6, 'test' => "playlist can not be added");
            }
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "user_playlistModel", "buyPlaylist", $user_id);
            throw new Exception ($e->getMessage(), $e->getCode());
        } 
    } 
    
    
    /**
    * Отдает игроку плейлисты в пользование
    * @param bigint $user_id          номер игрока из соц сети
    * @param int    $id_playlist_stat номер плейлиста из таблицы playlist_stat
    * @param int    $use_status       статус пользования (0 - дается в аренду, 1 - отдается навсегда)
    * @param int    $use_count        сколько раз можно использовать плейлист до того как он исчезнет из пользования, если use_status = 1, поле игнарируется
    * @return array =
    * result 
    * a_players_id              плейлисты добавленные игроку
    * a_players_id_already_get  плейлисты которые уже есть у игрока
    */ 
    public function givePlaylistToUser( $user_id, $array_playlist_id, $use_status, $use_count) {
        try{
            if(!Model::factory('user', $user_id)->exist()){
                errors::exc(errors::errorIncorrectInput, "user id not exist");
            }
            $aPlaylist           = array(); //плейлисты новые 
            $aPlaylistAlreadyGet = array(); //плейлисты уже находящиеся в пользовании у игрока
            $aPlaylistChange     = array(); //плейлисты сменившие статус "use_status" c 0(аренда) на 1(навсегда)  
            
            $listUserPlaylist   = Model::factory('user_playlist')->getList(array('user_id' => $user_id));
            
            foreach($array_playlist_id as $playlist_id){
                $flagAlreadyGet = false;
                $flagChangeRent = false;
                $idChangeRent   = NULL;    
                $idAlreadyGet   = 0;
                
                //проверка - не добавлены ли уже эти плейлисты
                foreach($listUserPlaylist as $value){
                    if($value['playlist_id'] == $playlist_id){
                       $flagAlreadyGet        = true;
                       //------------------------------------------
                       //если плейлист записан с use_status == 0(взят в аренду), а приходит запрос на запись с use_status == 1(куплен навсегда) запрос отрабатывает
                       //и плейлист перезаписывается как новый
                       if($use_status == 1 && $value['use_status'] == 0){
                           $flagChangeRent        = true;
                           $idChangeRent          = $value['id']; 
                           break;   
                       }
                       //------------------------------------------
                       $aPlaylistAlreadyGet[] = $value; 
                    }
               }
               
               if($flagAlreadyGet == false){  
                      $aPlaylist[]       = Model::factory('user_playlist')->add( $user_id, $playlist_id, $use_status, $use_count );
               } else {
                   if($flagChangeRent == true){ 
                      $aPlaylistChange[] = Model::factory('user_playlist')->add( $user_id, $playlist_id, $use_status, $use_count, $idChangeRent);
                   }
               } 
            }
            
            return array('result' => 1, 'a_playlist' => $aPlaylist, 'a_playlist_already_get' => $aPlaylistAlreadyGet, 'a_playlist_change' => $aPlaylistChange);
            
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "user_playlistModel", "givePlaylistToUser", $user_id);
            throw new Exception ($e->getMessage(), $e->getCode());
        }  
    }
    
    
    /**
    * Назначет создаваемому игроку плейлисты 
    * @param bigint  user_id id игрока из соц сети
    */ 
    public function givePlaylistToNewUser($user_id){
      try{
          
          $base_playlist_forever    = Model::factory ( 'var' )->loadByKey ( 'base_playlist_forever' )->value;
          $base_playlist_for_rent   = Model::factory ( 'var' )->loadByKey ( 'base_playlist_for_rent' )->value;
          $base_playlist_rent_count = Model::factory ( 'var' )->loadByKey ( 'base_playlist_rent_count' )->value;
          //-------------------------------------------------------------------------------------
          //плейлисты в постоянное пользование
          $aPlaylistForever = explode(",", $base_playlist_forever); 
          $array1 = $this->givePlaylistToUser($user_id, $aPlaylistForever, 1, 1);
          //-------------------------------------------------------------------------------------
          //плейлисты во временно пользование
          $aPlaylistForRent = explode(",", $base_playlist_for_rent); 
          $array2 = $this->givePlaylistToUser($user_id, $aPlaylistForRent, 0, $base_playlist_rent_count );
          //-------------------------------------------------------------------------------------
          if( 0 != count($array1['a_playlist'])             || 
              0 != count($array1['a_playlist_already_get']) ||
              0 != count($array1['a_playlist'])             || 
              0 != count($array1['a_playlist_already_get'])){
                  
              $aUserPlaylist = array_merge($array1['a_playlist'], $array1['a_playlist_already_get'],$array2['a_playlist'], $array2['a_playlist_already_get']); 
           }
           return array("result" => 1, "user_playlist" => $aUserPlaylist);  
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "gameModel", "givePlaylistToNewUser", $user_id);
            throw new Exception ($e->getMessage(), $e->getCode());
        }  
    }
    
    public function givePlaylistSet($user_id, $buy_playlist ){ 
        try{
            $aUserPlaylist = array();
            
            if(!Model::factory('user', $user_id)->exist()){
                return array("result" => -1, "text" => "user not exist"); 
            }
            
            if(! Model::factory("shop_playlist_set_stat", $buy_playlist)->exist()){
               return array("result" => -2, "text" => "no entry in the price of store "); 
            }
            
            $playlist_info = Model::factory("shop_playlist_set_stat", $buy_playlist)->get();
            $type   = $playlist_info["type"];
            $status = $playlist_info["status"];
            $count  = $playlist_info["count"];
            
            $aUserPlaylist = $this->givePlaylistToUser( $user_id, array( $type ), $status, $count); 
            
            return $aUserPlaylist;
      
         } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "user_boosterModel", "givePlaylistSet", $user_id);
            throw new Exception ($e->getMessage(), $e->getCode());
        } 
     }
    
    
    
}

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

<?php
/**
 * 
 * Рассылка сообщений между игроками 
 */
class user_game_ask_bufferModel extends Model {

    protected $_tableName = 'user_game_ask_buffer';
    
    
    /**
    * как 
    * @param bigint $user_id    номер игрока из соц сети
    * result array
    */
    public function add($game_id){
        try{
            
            $question_chars_count = Model::factory ( 'var' )->loadByKey ( 'question_chars_count' )->value;
            $position_bonus_char  = rand(2, $question_chars_count - 1);
            
            //-----------------------------------------------------------------------------
            $arr_souns = array();
            
            
            
            //1) найти случайное слово-------------------------------------------------------------------
            $sDBName      = DB_NAME;
            $s_query_select = "SELECT question FROM `$sDBName`.`task_stat` ORDER BY RAND() LIMIT 1";
            $aQuestion = DBAccess::query( $s_query_select, array('id'), PDO::FETCH_ASSOC );
            $question = $aQuestion[0]["question"];
            
            $str_question = Model::factory("word")->convert_to_in($question); //convert
            
            $str_souns_add = "";
          
            $question_count = strlen( $str_question );
          
            if( $question_chars_count < $question_count){
                errors::exc(errors::errorIncorrectDBValue, "in question too many chars" );
            }
           
            $open_chars_count = Model::factory ( 'var' )->loadByKey ( 'open_chars_count' )->value;
            
            if( $open_chars_count < $question_count){
                errors::exc(errors::errorIncorrectDBValue, "in question too many chars" );
            } else if($open_chars_count > $question_count){
              
                //--------------------------------------------------------------------------------------------
                //находим недостающие буквы
                $list_sound_0 = Model::factory("char_stat")->getList(array("sound_type" => 0), array("char"));
                $list_sound_1 = Model::factory("char_stat")->getList(array("sound_type" => 1), array("char"));
               
                $souns_count_0 = count($list_sound_0);
                $souns_count_1 = count($list_sound_1);
               
                $arr_sound_0 = array();
                $arr_sound_1 = array();
                
                
                //--------------------------------------------------------------------------------------------------------------------
                for($i = 0; $i < 6 - ceil($question_count/2); $i++){
                    if( $i != 0){
                        do{
                           $char = $list_sound_0[ rand(0, $souns_count_0 - 1)]["char"]; 
                           $char = Model::factory("word")->convert_to_in($char); //convert
                        } while( in_array( $char , $arr_sound_0) == TRUE || strpos($str_question, $char) !== FALSE);
                        $arr_sound_0[$i] = $char;
                    } else {
                        //специально нет проверки на повторяющиеся символы со словом вопросом, чтобы встречались повторяющиеся символы
                        $char  = $list_sound_0[ rand(0, $souns_count_0 - 1)]["char"]; 
                        $char  = Model::factory("word")->convert_to_in($char); //convert
                        $arr_sound_0[$i] = $char;
                    }
                }
                //--------------------------------------------------------------------------------------------------------------------
                for($i = 0; $i < 6 - floor($question_count/2); $i++){
                    if( $i != 0){
                        do{
                           $char = $list_sound_1[ rand(0, $souns_count_1 - 1)]["char"]; 
                           $char = Model::factory("word")->convert_to_in($char); //convert
                        } while( in_array( $char , $arr_sound_0) == TRUE || strpos($str_question, $char) !== FALSE);
                        $arr_sound_1[$i] = $char;
                    } else {
                        //специально нет проверки на повторяющиеся символы со словом вопросом, чтобы встречались повторяющиеся символы
                        $char  = $list_sound_1[ rand(0, $souns_count_1 - 1)]["char"]; 
                        $char  = Model::factory("word")->convert_to_in($char); //convert
                        $arr_sound_1[$i] = $char;
                    }
                }
                //--------------------------------------------------------------------------------------------------------------------
                $str_souns_add = implode("", $arr_sound_0).implode("", $arr_sound_1);
                //-------------------------------------------------------------------------------------------- 
            }
            $str_open_chars = "";
            $str_open_chars = $str_question.$str_souns_add;
             //-----------------------------------------------------------------------------       
            $str_open_chars = str_shuffle( $str_open_chars );
            //-----------------------------------------------------------------------------
            $open_chars  = Model::factory("word")->convert_to_out($str_open_chars); //convert
            $obj_ask = $this->create(array("id" => $game_id, "position_bonus_char" => $position_bonus_char, "open_chars" => $open_chars));
            $arr_ask = $obj_ask->get();
            
            return $arr_ask;
            //return array("id" => $arr_ask["id"], "position_bonus_char" => $arr_ask["position_bonus_char"], "open_chars" => $open_chars);

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

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

<?php
/**
 * 
 */
class lottery_statModel extends Model {
    
  protected $_tableName = 'lottery_stat';

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


      

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

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

================================================================================
ФАЙЛ: app/models/shop/shop_playlist_set_statModel.php.php
================================================================================

<?php
/**
 * 
 */
class shop_playlist_set_statModel extends Model {
    
    protected $_tableName = 'shop_playlist_set_stat';
    
    public function getData(){
        try{
             
            $list   = Model::factory("shop_playlist_set_stat")->getList(array(),array("id","type","status","count"));
            return  $list;
  
        } catch(Exception $e) {
            
        LOG_CRASH::add($e->getCode(), $e->getMessage(), "shop_status_set_statModel", "getData");
        throw new Exception ($e->getMessage(), $e->getCode());
        }
    }
}

================================================================================
ФАЙЛ: app/models/shop/shop_promotion_statModel.php
================================================================================

<?php
/**
 * 
 */
class shop_promotion_statModel extends Model {
    
    protected $_tableName = 'shop_promotion_stat';
    
    public function getData(){
        try{
             
            $list   = Model::factory("shop_promotion_stat")->getList(array(),array("id","buy_promotion","buy_way","cost_money1","cost_money2","visible_flag","social_shop_id"));
            return  $list;
  
        } catch(Exception $e) {
            
        LOG_CRASH::add($e->getCode(), $e->getMessage(), "shop_promotion_statModel", "getData");
        throw new Exception ($e->getMessage(), $e->getCode());
        }
    }
}

================================================================================
ФАЙЛ: app/models/shop/shop_money1_statModel.php
================================================================================

<?php
/**
 * 
 */
class shop_money1_statModel extends Model {
    
   protected $_tableName = 'shop_money1_stat';
    
   public function getData(){
        try{
             
            $list   = Model::factory("shop_money1_stat")->getList(array(),array("id","count","buy_way","bonus_percent","cost_money2","visible_flag","social_shop_id"));
            return  $list;
  
        } catch(Exception $e) {
            
        LOG_CRASH::add($e->getCode(), $e->getMessage(), "shop_money1_statModel", "getData");
        throw new Exception ($e->getMessage(), $e->getCode());
        }
    }
    
    
}

================================================================================
ФАЙЛ: app/models/shop/shop_energy_statModel.php
================================================================================

<?php
/**
 * 
 */
class shop_energy_statModel extends Model {
	
	protected $_tableName = 'shop_energy_stat';
                
    public function getData(){
        try{
             
            $list   = $this->getList(array(),array("id","count","buy_way","bonus_percent","cost_money1","cost_money2","visible_flag","social_shop_id"));
            return  $list;
      
        } catch(Exception $e) {
                       
        LOG_CRASH::add($e->getCode(), $e->getMessage(), "shop_money1_statModel", "getData");
        throw new Exception ($e->getMessage(), $e->getCode());
        }
    }
}

================================================================================
ФАЙЛ: app/models/shop/shop_playlist_set_statModel.php
================================================================================

<?php
/**
 * 
 */
class shop_playlist_set_statModel extends Model {
    
    protected $_tableName = 'shop_playlist_set_stat';
    
    public function getData(){
        try{
             
            $list   = Model::factory("shop_playlist_set_stat")->getList(array(),array("id","type","status","count"));
            return  $list;
  
        } catch(Exception $e) {
            
        LOG_CRASH::add($e->getCode(), $e->getMessage(), "shop_status_set_statModel", "getData");
        throw new Exception ($e->getMessage(), $e->getCode());
        }
    }
}

================================================================================
ФАЙЛ: app/models/shop/shop_money2_statModel.php
================================================================================

<?php
/**
 * 
 */
class shop_money2_statModel extends Model {
    
    protected $_tableName = 'shop_money2_stat';
    
       public function getData(){
        try{
             
            $list   = Model::factory("shop_money2_stat")->getList(array(),array("id","count","buy_way","bonus_percent","cost_money1","visible_flag","social_shop_id"));
            return  $list;
  
        } catch(Exception $e) {
            
        LOG_CRASH::add($e->getCode(), $e->getMessage(), "shop_money2_statModel", "getData");
        throw new Exception ($e->getMessage(), $e->getCode());
        }
    }
    
}

================================================================================
ФАЙЛ: app/models/shop/shop_booster_statModel.php
================================================================================

<?php
/**
 * 
 */
class shop_booster_statModel extends Model {
    
    protected $_tableName = 'shop_booster_stat';
    
        public function getData(){
        try{
             
            $list   = Model::factory("shop_booster_stat")->getList(array(),array("id","buy_booster_set","buy_way","cost_money1","cost_money2","visible_flag","social_shop_id"));
            return  $list;
  
        } catch(Exception $e) {
            
        LOG_CRASH::add($e->getCode(), $e->getMessage(), "shop_booster_statModel", "getData");
        throw new Exception ($e->getMessage(), $e->getCode());
        }
    }
    
}

================================================================================
ФАЙЛ: app/models/shop/shop_booster_set_statModel.php
================================================================================

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

================================================================================
ФАЙЛ: app/models/shop/shop_game_in_max_statModel.php
================================================================================

<?php
/**
 * 
 */
class shop_game_in_max_statModel extends Model {
    
    protected $_tableName = 'shop_game_in_max_stat';
    
    public function getData(){
        try{
             
            $list   = Model::factory("shop_game_in_max_stat")->getList(array(),array("id","count","buy_way","bonus_percent","cost_money1","cost_money2","visible_flag","social_shop_id"));
            return  $list;
  
        } catch(Exception $e) {
            
        LOG_CRASH::add($e->getCode(), $e->getMessage(), "shop_game_in_max_statModel", "getData");
        throw new Exception ($e->getMessage(), $e->getCode());
        }
    }
}

================================================================================
ФАЙЛ: app/models/shop/shop_game_out_max_statModel.php
================================================================================

<?php
/**
 * 
 */
class shop_game_out_max_statModel extends Model {
    
    protected $_tableName = 'shop_game_out_max_stat';
    
    public function getData(){
        try{
             
            $list   = Model::factory("shop_game_out_max_stat")->getList(array(),array("id","count","buy_way","bonus_percent","cost_money1","cost_money2","visible_flag","social_shop_id"));
            return  $list;
  
        } catch(Exception $e) {
            
        LOG_CRASH::add($e->getCode(), $e->getMessage(), "shop_game_out_max_statModel", "getData");
        throw new Exception ($e->getMessage(), $e->getCode());
        }
    }
}

================================================================================
ФАЙЛ: app/models/shop/shop_stage_statModel.php
================================================================================

<?php
/**
 * 
 */
class shop_stage_statModel extends Model {
    
    protected $_tableName = 'shop_stage_stat';
    
    public function getData(){
        try{
             
            $list   = Model::factory("shop_stage_stat")->getList(array(),array("id","buy_stage_stat_id","buy_way","cost_money1","cost_money2","visible_flag","social_shop_id"));
            return  $list;
  
        } catch(Exception $e) {
            
        LOG_CRASH::add($e->getCode(), $e->getMessage(), "shop_stage_statModel", "getData");
        throw new Exception ($e->getMessage(), $e->getCode());
        }
    }
    
}

================================================================================
ФАЙЛ: app/models/shop/shop_energy_max_statModel.php
================================================================================

<?php
/**
 * 
 */
class shop_energy_max_statModel extends Model {
    
    protected $_tableName = 'shop_energy_max_stat';
    
    public function getData(){
        try{
             
            $list   = Model::factory("shop_energy_max_stat")->getList(array(),array("id","count","buy_way","bonus_percent","cost_money1","cost_money2","visible_flag","social_shop_id"));
            return  $list;
  
        } catch(Exception $e) {
            
        LOG_CRASH::add($e->getCode(), $e->getMessage(), "shop_energy_max_statModel", "getData");
        throw new Exception ($e->getMessage(), $e->getCode());
        }
    }
}

================================================================================
ФАЙЛ: app/models/shop/shop_playlist_statModel.php
================================================================================

<?php
/**
 * 
 */
class shop_playlist_statModel extends Model {
    
    protected $_tableName = 'shop_playlist_stat';
    
    public function getData(){
        try{
             
            $list   = Model::factory("shop_playlist_stat")->getList(array(),array("id","buy_playlist","buy_way","cost_money1","cost_money2","visible_flag","social_shop_id"));
            return  $list;
  
        } catch(Exception $e) {
            
        LOG_CRASH::add($e->getCode(), $e->getMessage(), "shop_playlist_statModel", "getData");
        throw new Exception ($e->getMessage(), $e->getCode());
        }
    }
}

================================================================================
ФАЙЛ: app/models/shop/shop_booster_stat_setModel.php
================================================================================

<?php
/**
 * 
 */
class shop_booster_set_statModel extends Model {
    
    protected $_tableName = 'shop_booster_set_stat';
    
    public function getData(){
        try{
             
            $list   = Model::factory("shop_booster_set_stat")->getList(array(),array("id","type","count"));
            return  $list;
  
        } catch(Exception $e) {
            
        LOG_CRASH::add($e->getCode(), $e->getMessage(), "shop_booster_set_statModel", "getData");
        throw new Exception ($e->getMessage(), $e->getCode());
        }
    }
}

================================================================================
ФАЙЛ: app/models/shop/shopModel.php
================================================================================

<?php
/**
 * Магазин 
 * 
 * 
 */
class shopModel extends Model {
    //protected $_tableName = 'shop_social_stat';
   
   /**
    * Возвращает все статические данные о покупаемых товарах
    * 
    * @param bigint $user_id       id-пользователя в соц. сети
    * @param int    $goods_id      id-пользователя в соц. сети
    * @param int    $social_money  Кол-во единиц валюты соц сети
    */
    public function getClientPrice(&$list_price = array()){
        try{

            $list_price["shop_social_stat"]        = Model::factory("shop_social_stat")->getData();
            
            $list_price["shop_money1_stat"]        = Model::factory("shop_money1_stat")->getData();
            $list_price["shop_money2_stat"]        = Model::factory("shop_money2_stat")->getData();
            
            $list_price["shop_energy_stat"]        = Model::factory("shop_energy_stat")->getData();
            $list_price["shop_energy_max_stat"]    = Model::factory("shop_energy_max_stat")->getData();
            
            $list_price["shop_booster_stat"]       = Model::factory("shop_booster_stat")->getData();
            $list_price["shop_booster_set_stat"]   = Model::factory("shop_booster_set_stat")->getData();
            
            
            $list_price["shop_stage_stat"]         = Model::factory("shop_stage_stat")->getData();
            
            //$list_price["shop_playlist_stat"]      = Model::factory("shop_playlist_stat")->getData();
            //$list_price["shop_playlist_set_stat"]  = Model::factory("shop_playlist_set_stat")->getData();
            
            $list_price["shop_promotion_stat"]     = Model::factory("shop_promotion_stat")->getData();
            
            return $list_price;       
        } catch(Exception $e) {
            
        LOG_CRASH::add($e->getCode(), $e->getMessage(), "shopModel", "getClientPrice");
        throw new Exception ($e->getMessage(), $e->getCode());
        }
    }
    
    /**
    * put your comment there...
    * 
    * @param bigint $user_id       id-пользователя в соц. сети
    * @param int    $goods_id      id-пользователя в соц. сети
    * @param int    $social_money  Кол-во единиц валюты соц сети
    */
    public function buyGoods($user_id, $goods_id, $social_money){
         try{
       
                if(!Model::factory('user', $user_id)->exist()){

                    errors::exc(errors::errorIncorrectInput, "user_id not exist" );
            
                }
                if(!Model::factory('shop_social_stat', $goods_id)->exist()){

                    errors::exc(errors::errorIncorrectInput, "goods_id not exist in shop" );
                }
                
                $arr_shop_social = Model::factory('shop_social_stat', $goods_id)->get();  
                
                if($arr_shop_social['cost_social_money'] != $social_money){

                    errors::exc(errors::errorIncorrectInput, "social money cost not equal with server" );
                }
                 //--------------------------------------------------------------------------
                //выдача товаров
                //--------------------------------------------------------------------------
                //валюты и энергия:
                $money1 = 0;
                $money2 = 0;
                if(-1 != $arr_shop_social['buy_money1'] && 0 != $arr_shop_social['buy_money1']){
                   $money1 = $arr_shop_social['buy_money1']; 
                }
                if(-1 != $arr_shop_social['buy_money2'] && 0 != $arr_shop_social['buy_money2']){
                   $money2 = $arr_shop_social['buy_money2']; 
                }
                if(0 != $money1 || 0 != $money2){  
                    if(!Model::factory("user", $user_id)->changeMoney($money1, $money2, 1)){

                        errors::exc(errors::errorIncorrectInput, "change money error" );
                    } 
                }
                if(0 < $arr_shop_social['buy_energy']){
                    if(!Model::factory("user", $user_id)->addEnergy( $arr_shop_social['buy_energy_type_using'], $arr_shop_social['buy_energy'])){

                        errors::exc(errors::errorIncorrectInput, "change energy error" );
                    }
                }
                 if(0 < $arr_shop_social['buy_energy_max']){
                    if(!Model::factory("user", $user_id)->addEnergyMax( $arr_shop_social['buy_energy_max'])){

                        errors::exc(errors::errorIncorrectInput, "change energy_max error" );
                    }
                }
                
                //--------------------------------------------------------------------------
                //Входящие, исходящие игры
                if(FALSE == is_null( $arr_shop_social['buy_game_out_max']) &&  $arr_shop_social['buy_game_out_max'] != "" &&  $arr_shop_social['buy_game_out_max'] != -1 ){
                    if(0 < $arr_shop_social['buy_game_out_max']){
                        if(!Model::factory("user", $user_id)->addGameOutMax(  $arr_shop_social['buy_game_out_max'])){

                            errors::exc(errors::errorIncorrectInput, "change game_out_max error" );
                        }
                    }
                }
                if(FALSE == is_null( $arr_shop_social['buy_game_in_max']) &&  $arr_shop_social['buy_game_in_max'] != "" &&  $arr_shop_social['buy_game_in_max'] != -1 ){
                
                    if(0 < $arr_shop_social['buy_game_in_max']){
                        if(!Model::factory("user", $user_id)->addGameInMax(  $arr_shop_social['buy_game_in_max'])){

                            errors::exc(errors::errorIncorrectInput, "change game_in_max error" );
                        }
                    }
                }
                
                //--------------------------------------------------------------------------
                //остальные товары
                //--------------------------------------------------------------------------
                //бустеры
                if(FALSE == is_null( $arr_shop_social['buy_booster_set']) &&  $arr_shop_social['buy_booster_set'] != "" &&  $arr_shop_social['buy_booster_set'] != -1) {
                    
                   // передается str
                   $aUserBoosters = Model::factory('user_booster', $user_id)->giveBoosterSet( $arr_shop_social['buy_booster_set'] );
                   if(TRUE == is_null( $aUserBoosters ) || FALSE == is_array( $aUserBoosters )){

                       errors::exc(errors::errorIncorrectInput, "can not buy booster" );
                   }
                }
                
                //--------------------------------------------------------------------------
                //этапы
                if(FALSE == is_null( $arr_shop_social['buy_stage']) &&  $arr_shop_social['buy_stage'] != "" && $arr_shop_social['buy_stage'] != -1 ) {
                    
                  
                   $stage_stat_id = $arr_shop_social["buy_stage"]; //еквивалентно buy_stage_stat_id в табл.shop_stage_stat
                   $cost_type     = 3;
                   
                   $aStage = Model::factory("stage")->stageStart($user_id, $stage_stat_id, $cost_type);
                   //$aUserBoosters = Model::factory('user_booster', $user_id)->giveBoosterSet( $arr_shop_social['buy_booster_set'] );
                   if(TRUE == is_null( $aStage ) || FALSE == is_array( $aStage )){
                       //return -309;
                       errors::exc(errors::errorIncorrectInput, "can not buy stage" );
                       
                   } else if($aStage["result"] == -170){
                       
                       //errors::exc(errors::errorIncorrectInput, "first stage in company must be free" ); 
                       return 0;
                       
                   } else if($aStage["result"] < 0){
                       //? почему тут нет ошибки ? 
                       //return -310;
                       //errors::exc(errors::errorIncorrectInput, "can not buy stage" );
                   }
                }
                
                //--------------------------------------------------------------------------
                //плейлисты:
                if(0){
                    if(FALSE == is_null( $arr_shop_social['buy_playlist']) ) {
                        
                       // передается id
                       $aUserPlaylist = Model::factory('user_playlist')->givePlaylistSet($user_id,  $arr_shop_social['buy_playlist'] );
                       if(TRUE == is_null( $aUserPlaylist ) || FALSE == is_array( $aUserPlaylist )){
                           errors::exc(errors::errorIncorrectInput, "can not buy playlist" );
                       }
                    }
                }
                //--------------------------------------------------------------------------  
                return 1;       
            } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "shopModel", "buyGoods");
            throw new Exception ($e->getMessage(), $e->getCode());
            }
    }  
}

================================================================================
ФАЙЛ: app/models/shop/shop_game_out_max_statModel.php.php
================================================================================

<?php
/**
 * 
 */
class shop_game_out_max_statModel extends Model {
    
    protected $_tableName = 'shop_game_out_max_stat';
    
    public function getData(){
        try{
             
            $list   = Model::factory("shop_game_out_max_stat")->getList(array(),array("id","count","buy_way","bonus_percent","cost_money1","cost_money2","visible_flag","social_shop_id"));
            return  $list;
  
        } catch(Exception $e) {
            
        LOG_CRASH::add($e->getCode(), $e->getMessage(), "shop_game_out_max_statModel", "getData");
        throw new Exception ($e->getMessage(), $e->getCode());
        }
    }
}

================================================================================
ФАЙЛ: app/models/shop/shop_social_statModel.php
================================================================================

<?php
/**
 * Магазин товаров в соц сети(валюта, энергия, бустреы и т.д.).
 * 
 * 
 */
class shop_social_statModel extends Model {
    
    protected $_tableName = 'shop_social_stat';
    
    public function getData(){
        try{
             
            $list   = Model::factory("shop_social_stat")->getList(array(),array("id","buy_money1","buy_money2","buy_energy","buy_booster_set","buy_promotion","cost_social_money","description","image_path"));
            return  $list;
  
        } catch(Exception $e) {
            
        LOG_CRASH::add($e->getCode(), $e->getMessage(), "shop_social_statModel", "getData");
        throw new Exception ($e->getMessage(), $e->getCode());
        }
    }
}

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

<?php
/**
 * 
 * Класс обработки раунда
 */
class user_roundModel extends Model{
    
    protected $_tableName = 'user_round';
    
    
    
    /**
    * Инициализация раунда
    * 
    * Только при создании раунда вызывается
    * 
    * @param (bigint)   user_id        : номер игрока в таблице users
    * @param (int)      $game_id       : номер игрока в таблице users
    * @param (&array)   &$aRound       : массив данных о раудне (массив возвращается по ссылке)
    * @param (&object)  &$oRound       : object раунда (возвращается по ссылке)
    * 
    * @return 1 int 
    */ 
    
    public function createRound($user_id, $game_id, &$aRound = array(), &$oRound = NULL){
        try{
            $new_round["user_game_id"]            = $game_id;
            $new_round["round_completed_flag"]    = 0;
            $new_round["user_result_0"]           = -1;
            $new_round["user_result_1"]           = -1;
            $new_round['time_start_server']       = SConfig::$time;
            //--------------------------------------------------------------------------------------
            $oRound          = Model::factory('user_round')->create( $new_round );
            $aRound          = $oRound ->get();
            //--------------------------------------------------------------------------------------
            return 1;
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "user_roundModel", "createRound", $user_id);
            throw new Exception ($e->getMessage(), $e->getCode());
        }
    } 
    
    /**
    * Получить все раунды с заданиями в текущей игре (в случае если раунд создан в текущей сессии он не будет возвращен)
    * 
    * @param  (bigint)    user_id        : номер игрока в таблице users
    * @param  (int)       round_id       : id раунда<div></div>

    * 
    * @return (array)     aRoundTaskSet 
    */ 
    public function getGameRoundSet($user_id, $game_id){
        try{
            $aGameRoundSet = Model::factory("user_round")->getList(array("user_game_id" => $game_id), array(), "id");
            //--------------------------------------------------------------------------------------
            return $aGameRoundSet;
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "user_roundModel", "getGameRoundSet", $user_id);
            throw new Exception ($e->getMessage(), $e->getCode());
        }
     }
    
    /**
    * дополняет массив $aRoundSet массивом $addRound, который уже частично имеется в первом
    * требуется для записи статистики 
    * при этом сохранения не происходит 
    * 
    * @param  (bigint)    user_id        : номер игрока в таблице users
    * @param  (array)     aRoundSet      : дополняемый массив
    * @param  (array)     addRound       : массив которым дополняется первый

    * 
    * @return (array)     aRoundTaskSet 
    */  
    public function combineRound($user_id, $aRoundSet, $addRound){
       try{  
           
           foreach($aRoundSet as &$round){
                if($round["id"] == $addRound["id"]){
                   foreach($round as $key => $value){
                      $round[ $key ] = $addRound[ $key ] ;  
                   }
                }
           }
           return $aRoundSet;
       } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "user_roundModel", "combineRound", $user_id);
            throw new Exception ($e->getMessage(), $e->getCode());
        }
       
    }
     
    /**
    * Подготавливает данные для возврата их клиенту (запрос start)
    * @return array Массив возвращаемых значений, cодержит:
    *  -  (array)  aRound   :  передается по ссылке, массив с данными о игре
    */ 
    public function convertRound( $user_id, &$aRound ){
          try{
              unset($aRound["time_start_server"]);
               // действий в данный момент не требуется              
             } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "user_roundModel", "convertRound", $user_id);
            throw new Exception ($e->getMessage(), $e->getCode());
        } 
    } 
    
        /**
    * Очищает поля в массиве соответствующем строке из user_round перед перезаписью 
    * @param (bigint) $user_id bigint номер игрока в таблице users
    * @param (int)    $game_id id игры к которой относя раунды
    * @return 1 int 
    */   
    public function deleteRoundSet($user_id, $game_id ){
        try{
            $list =  Model::factory("user_round")->getList(array("user_game_id" => $game_id), array("id"));
             foreach($list as $game){
               Model::factory("user_round", $game["id"])->delete();    
             }
            //или
            //Model::factory("user_round")->delete(array("user_game_id" => $game_id));
            
            return 1;
            
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "user_roundModel", "deleteRoundSet", $user_id);
            throw new Exception ($e->getMessage(), $e->getCode());
        }                        
    }
    /**
    * Посчитать количество проиграных раундов 
    * 
    * @param int   user_number порядковый номер игрока (1 или 2)
    * @param array round_set   массив ранудов
    * 
    * @return int lose_count количество проигранных игроком раундов
    */
    public function getLoseRoundsCount( $user_number, $round_set){
        try{
            $lose_count = 0;
            if( 0 != $user_number || 1 != $user_number){
                foreach($round_set as $round){
                   if(0 == $round["user_result_".$user_number]){
                       $lose_count++;
                   }
                }
            }
            return $lose_count;
            
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "user_roundModel", "getLoseRoundsCount");
            throw new Exception ($e->getMessage(), $e->getCode());
        }
    }
}

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

<?php
/**
 * 
 * Класс модели пользователя
 */
class user_daily_actionsModel extends Model {
    protected $_tableName = 'user_daily_actions';
    
    /**
     * Создает новую запись инициализируя значения по-умолчанию
     * (id пользователя передается в аргументах обращении к фабрике)
     * @return mix Созданный объект
     */ 
    public function createRecord() {
        try{
            $id_user = $this->id;
            $aRecord = array('id'            => $id_user,
                             'visit_time'    => SConfig::$time,
                             'visit_count'   => 1,
                             'count_of_days' => 0 );
            $oRecord = $this->create($aRecord);
            return $oRecord;
            
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "user_daily_actionsModel", "createRecord", $id_user);
            throw new Exception ($e->getMessage(), $e->getCode());
        }  
    }
    
    /**
    * Функция определяет действия которые необходимо выполнить когда наступает новый день
    * (id пользователя передается в аргументах обращении к фабрике)
    * @param $count_of_days = 0 Какой день подряд пользователь заходит в игру
    * @return mix 
    */ 
    private function  new_day_actions( $count_of_days = 0){
        try{
            
            $user_id = $this->id;
            $money1 = 0;
            $money2 = 0;
            $energy = 0;
            $lottery_money2 = 0;
          
           //-------------------------------------------------------------------------------------------------
           //-------------------------------------------------------------------------------------------------
           //-------------------------------------------------------------------------------------------------
          
           //Касается лотереи:
            $lottery_recovery_system = (int) Model::factory ( 'var' )->loadByKey ( 'lottery_recovery_system' )->value;
            //0 - не восстанавливается никогда
            //1 - восстанавливается 1 единица money2 в день, если money2 == 0 
            //2 - прибавляется 1 единица money2 в день
            
            switch( $lottery_recovery_system ){
                case 0: { 
                       
                } break;
                case 1: {
                    
                    if( false == Model::factory('user', $user_id)->checkMoney( 0, 1)){ 
                         //т.е. если нет 1 единицы money2
                         $reason_id = 17;
                         $lottery_money2 = 1;
                         Model::factory('user', $user_id)->changeMoney(0, $lottery_money2, $reason_id);
                    } else {
                       
                    }       
                } break;
                case 2: {
                    $reason_id = 17;
                    $lottery_money2 = 1;
                    Model::factory('user', $user_id)->changeMoney(0, $lottery_money2, $reason_id);  
                } break;
                default:{
                   
                }  break;
            }
           
           //-------------------------------------------------------------------------------------------------
           //-------------------------------------------------------------------------------------------------
           //-------------------------------------------------------------------------------------------------
           //Тут писать действия которые необходимо произвести если пришел новый день!
            if(Model::factory('daily_bonus_stat', $count_of_days)->exist()){
                $aDailyBonusStat =  Model::factory('daily_bonus_stat',$count_of_days)->get();
                $money1  = $aDailyBonusStat['money1'];
                $money2  = $aDailyBonusStat['money2'];
                $energy  = $aDailyBonusStat['energy'];
                
                if($money1 > 0 || $money2 > 0){
                     $reason_id = 7;
                     Model::factory('user', $user_id)->changeMoney($money1, $money2, $reason_id);
                }
                if($energy > 0){
                     $reason_id = 7;
                     Model::factory('user', $user_id)->changeEnergy($energy, $reason_id);
                }
                
                //добавить добавление энергии при необходимости 
                Model::factory('user',$user_id)->save();
            } 
            //-------------------------------------------------------------------------
            return array("money1" => $money1, "money2" => $money2, "energy" => $energy, "lottery" => array("money2" => $lottery_money2));
         
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "user_daily_actionsModel", "new_day_actions", $user_id);
            throw new Exception ($e->getMessage(), $e->getCode());
        }  
    }
    
    
    /**
    * Проверка при инициализации, когда пользователь последний раз был в игре
    * (id пользователя передается в аргументах обращении к фабрике)
    * @return mix Созданный объект
    */ 
    public function check(){
        try{
            $id_user = $this->id;
           
            $daily_bonus_day_count = Model::factory ( 'var' )->loadByKey ( 'daily_bonus_day_count' )->value;
            
            if(!Model::factory('user', $id_user)->exist()){
                return -1;        
            } 
            
            $TimeNow = SConfig::$time;
            $count_of_days = 0;
            $visit_time    = 0;
            $visit_count   = 0;
           
            $fNewDay       = 0;
            
            if(!$this->exist()){
                    $this->createRecord();
                    $fNewDay = 1;
                    
            } else {

                $last_count_of_days = $this->count_of_days;  
                
                $iTodayInYear  = date('z', $TimeNow);
                $iPastInYear   = date('z', $this->visit_time);
                $flagPastLeap  = date('L', $this->visit_time);
                
                if($iTodayInYear != $iPastInYear){
        
                      //НОВЫЙ ДЕНЬ  
                      $fNewDay = 1;
                      if(($iPastInYear + 1 == $iTodayInYear) || 
                         ($iPastInYear == 364 && $iTodayInYear == 0 && $flagPastLeap == 0) ||
                         ($iPastInYear == 365 && $iTodayInYear == 0 && $flagPastLeap == 1)) 
                      {
                           if($last_count_of_days >= 0 && $last_count_of_days < $daily_bonus_day_count - 1){
                               $count_of_days = $last_count_of_days + 1 ;  
                           } 
                           else if($last_count_of_days >= $daily_bonus_day_count - 1 || $last_count_of_days < 0) {
                                $count_of_days = 0;
                           } else {
                                $count_of_days = $last_count_of_days + 1 ; 
                           }
                      } else {  
                           $count_of_days = 0;
                      }
                }
            }
                
            $this->visit_time  = $TimeNow;
            
            if( $fNewDay == 1   ){
                $this->visit_count =  1;
                $this->count_of_days = $count_of_days;
                $this->save();
                    
                //-------------------------------------------------------------------------------------------------
                $add_bonus = $this->new_day_actions( $count_of_days );
                //-------------------------------------------------------------------------------------------------
                
                return array('result' => 1, 'flag_daily_bonus' => 1, 'count_of_days' => $count_of_days, "bonus_money1" => $add_bonus["money1"], "bonus_money2" => $add_bonus["money2"], "bonus_energy" => $add_bonus["energy"], "flag_lottery_bonus' => 0", "bonus_lottery" => $add_bonus["lottery"]);
               
            } else {
                $this->visit_count +=  1;
                $this->save();
                return array('result' => 1, 'flag_daily_bonus' => 0, 'count_of_days' => $count_of_days, 'flag_lottery_bonus' => 0);
            }
            
            return 0;
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "user_daily_actionsModel", "check", $id_user);
            throw new Exception ($e->getMessage(), $e->getCode());
        }  
    } 
}

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

<?php
/**
 * 
 * Класс 
 */
class session_keyModel extends Model {
	
	protected $_tableName = 'session_key';
	
    public function set_skey( $user_id ){
        try{
            $s_key = rand(0, 10000000);
            $aKey = array("id" => $user_id, "s_key" => $s_key);
            $this->create( $aKey );
            
            //Model::factory('log_activity_user')->create();
            
            return $s_key;
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "session_keyModel", "set_skey", $user_id);
            throw new Exception ($e->getMessage(), $e->getCode());
        }  
    }
    
    public function get_skey( $user_id ){
        try{
            $aKey = Model::factory('session_key', $user_id)->get();  
           
            //LOG::printText("id_user:$id_user");
            
            $a1 = $aKey['id']; 
            $a2 = $aKey['s_key']; 
            
            //LOG::printText("aK_user:$a1");
            //LOG::printText("aK_skey:$a2");
           
           
            if(count($aKey) <= 1) 
            {
                return -1;
            } 
            return $aKey['s_key'];
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "session_keyModel", "get_skey", $user_id);
            throw new Exception ($e->getMessage(), $e->getCode());
        }  
    }
}

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

<?php
/**
 * 
 * Класс модели пользователя
 *
 */
class abstractModel {
    protected $_data = array ();
    protected $_dataUpdate = array ();
    protected $_tableName = '';
    protected $_idName = 'id';
    protected $_belongs_to = array ();
    
    /**
     * @param number $id
     */
    public function __construct($id = NULL) {
        if (! $this->loadFromCache ( $id ))
            $this->loadFromDb ( $id );
    }
    
    public function __destruct() {
        $this->save ();
    }
    
    public function loadFromArray($data, $force = false) {
        foreach ( $data as $k => $v ) {
            if ($force)
                $this->_data [$k] = $v;
            else
                $this->$k = $v;
        }
    }
    
    public function loadFromCache($id) {
        $this->_dataUpdate = array ();
        if (isset ( $id ) && is_numeric ( $id )) {
            $this->_data = CacheAccess::get ( $this->_tableName . '_' . $id );
        } else {
            $this->_data = array ();
        }
        $result = ( boolean ) $this->_data;
        //        if ($result) {
        //            $this->loadRelations ();
        //        }
        return $result;
    }
    
    public function loadRelations() {
        foreach ( $this->_belongs_to as $linkName => $linkCond ) {
            $this->_data [$linkName] = new $linkCond ['model'] ( $this->$linkCond ['foreign_key'] );
        }
    }
    
    /**
     * Загрузка данных в класс из базы
     */
    public function loadFromDb($id) 
    {
        $this->_dataUpdate = array ();
        if (isset ( $id ) && is_numeric ( $id )) 
        {
            $this->_data [$this->_idName] = $id;
            $result = DBAccess::select ( $this->_tableName, array ($this->_idName => $this->_data [$this->_idName] ) );
            if (isset ( $result [0] ) && isset ( $result [0] [$this->_idName] )) 
            {
                $this->_data = $result [0];
                //    $this->loadRelations ();
                $this->saveToCache ();
                return true;
            }
        } 
        else 
        {
            $this->_data = array ();
        }
        return false;
    }
    
    public function saveToCache() {
        if ($this->exist ()) {
            $data = $this->_data;
            foreach ( $this->_belongs_to as $k => $v ) {
                unset ( $data [$k] );
            }
            return CacheAccess::set ( $this->_tableName . '_' . $this->_data [$this->_idName], 
                    $data, 86400 );
        } else
            return false;
    }
    
    /**
     * 
     */
    public function save() {
        if (count ( $this->_dataUpdate ) && isset ( $this->_data [$this->_idName] ) && $this->_data [$this->_idName]) {
            $result = ( boolean ) DBAccess::update ( $this->_tableName, $this->_dataUpdate, 
                    array ($this->_idName => $this->_data [$this->_idName] ) );
            if ($result) {
                foreach ( $this->_dataUpdate as $key => $value ) {
                    $this->_data [$key] = $value;
                }
                $this->saveToCache ();
                $this->_dataUpdate = array ();
            }
            return $result;
        }
        return true;
    }
    
    /**
     * Проверка существует ли
     * @return boolean
     */
    public function exist() 
    {
        return count ( $this->_data ) > 1 ? true : false;
    }
    
    protected function _prepareOutput($data, $user = NULL) {
        return $data;
    }
    
    public function get() 
    {
        $result = array ();
        // Подгрузка отображаемых зависимостей
        foreach ( $this->_belongs_to as $linkName => $linkCond ) 
        {
            if (isset ( $this->_belongs_to [$linkName] ['get'] ))
                $this->$linkName;
        }
        
        foreach ( $this->_data as $key => $value ) 
        {
            if (is_object ( $value ) && isset ( $this->_belongs_to [$key] )) 
            {
                if (isset ( $this->_belongs_to [$key] ['get'] ))
                    $result [$key] = $value->get ();
            } 
            else 
            {
                $result [$key] = isset ( $this->_dataUpdate [$key] ) ? $this->_dataUpdate [$key] : $value;
            }
        }
        
        return $this->_prepareOutput ( $result );
    }
    
    public function getList($where = array(), $fields = NULL, $order = '', $user = NULL) {
        $result = DBAccess::select ( $this->_tableName, $where, $fields, $order );
        foreach ( $result as $key => $value ) {
            $result [$key] = $this->_prepareOutput ( $value, $user );
        }
        return $result;
    }
    
    public function delete() {
        if ($this->exist ()) {
            CacheAccess::delete ( $this->_tableName . '_' . $this->_data [$this->_idName] );
            $result = ( boolean ) DBAccess::delete ( $this->_tableName, 
                    array ($this->_idName => $this->_data [$this->_idName] ) );
        } else {
            $result = false;
        }
        if ($result) {
            $this->_data = $this->_dataUpdate = array ();
        }
        return $result;
    }
    
    public function __get($name) 
    {
        if (isset ( $this->_belongs_to [$name] ) && ! isset ( $this->_data [$name] )) 
        {
            $this->_data [$name] = new $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 
        {
            throw new Exception ( $name . ' is not property', errors::errorUnknown );
        }
    }
    
    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 {
            throw new Exception ( $name . ' is not property', errors::errorUnknown );
        }
    }

}

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

<?php
/**
 * 
 */
     
 class gameModel extends Model {

    
    //protected $_tableName = 'game';
   
    //--------------------------------------------------------------------------------------------------------------------------------
    //--------------------------------------------------------------------------------------------------------------------------------
    //--------------------------------------------------------------------------------------------------------------------------------
    //--------------------------------------------------------------------------------------------------------------------------------
    
    
    /**
    * Инициализирует игру (дуэль) с двумя игроками 
    * Выбор плейлиста происходит следующим после этого запросом
    * @param  bigint $user_id_0 номер игрока0 в соц. сети
    * @param  bigint $user_id_1 номер игрока1 в соц. сети
    * @return mix array("result" => 1, "game" => $aNewUserGame);
    */ 
    public function initGame($user_id_0, $user_id_1, $friend_flag = 0) {
        try{
            
            $invite_flag = 0;
            if(!Model::factory("user", $user_id_1)->exist()){
              $invite_flag = 1;  
            }
            
            
            if(!Model::factory("user", $user_id_0)->exist()){
                errors::exc(errors::errorIncorrectInput,"user_out id not exist" );
            }
