Часть 4 из 12
Строки: 6001-8000 из 22262
================================================================================

                   $prize["money"] =  0;
                   $prize["exp"] = 0;
                   
                   $booster_type  =  $stage_stat['prize_booster_type'];
                   $booster_count =  $stage_stat['prize_booster_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;
                   } 
                   
                   if($stage_stat['prize_money1']){
                        $prize["money"] = $stage_stat['prize_money1']; 
                        Model::factory("user", $user_id)->changeMoney( $stage_stat['prize_money1'], 0, 1);
                   }
                      
                   if($stage_stat['exp']){
                        $prize["exp"] = $stage_stat['prize_exp'];
                        Model::factory("user", $user_id)->changeMoney( $stage_stat['prize_exp'], 0, 1);
                   }
                  
                   Model::factory("stage")->create( $stage );
                  
                   //запуск таймера на следующий по порядку этап------------------------------------------------------------ 
                   Model::factory("stage")->stageTimerStart($user_id, $company_stat_id, $next_stage_position);
                   //-------------------------------------------------------------------------------------------------------
              } else {
                  return array("result" => 0);
              }   
              //-----------------------------------------------------------------------------------------------------------
               
              return array("result" => 1, "stage" => $stage, "prize" => $prize);
                           
           } catch(Exception $e) {
                
                LOG_CRASH::add($e->getCode(), $e->getMessage(), "stageModel", "stageEnd", $user_id);
                throw new Exception ($e->getMessage(), $e->getCode());
           }
      } 
      
    /**
    * Просить ключ
    */                                          
    public function stageKeyAsk($user_id, $user_donator_id,  $stage_stat_id = -1){
        try{ 
            
            if(!Model::factory('user', $user_id)->exist()){
                return array("result" => -1, "text" => "user_id not exist"); 
            }
            
            if(!Model::factory('user', $user_donator_id)->exist()){
                //return array("result" => -1, "text" => "user_to not exist"); 
                //можно просить у того кого еще нет в игре
            }
            
           
           //-----------------------------------------------------------------------------------------------------------------
           //-----------------------------------------------------------------------------------------------------------------
           //Проверки
           $stage_stat      = Model::factory("stage_stat",   $stage_stat_id)->get();
           $stage_position  = $stage_stat["position"];
           $stage           = Model::factory("stage")->getList(array("user_id"=> $user_id, "stage_stat_id" => $stage_stat_id));
           
           //Проверка не запущел ли уже этап----------------------------------------------------------------------------------
           if( count($stage) != 0){
               return array("result" => -120, "text" => "stage already exist");
           }
           
           //Этапа не существует - нужно проверить можно ли его запустить-----------------------------------------------------
           //Пройден ли предыдущий этап---------------------------------------------------------------------------------------
           if($stage_position > 0){
              $arr_previous_stage_stat = array();
              if($this->getPreviousStage($user_id, $stage_stat_id, $arr_previous_stage_stat)){
           
                  if(!$this->checkCompliteStage( $user_id, $arr_previous_stage_stat["id"])){
                      return array("result" => -121, "text" => "previous stage not complete");
                  } 
              } 
           } 
           //Предыдущий этап компании пройдет, можно просить ключ
           //----------------------------------------------------------------------------------------------------------------- 
           //----------------------------------------------------------------------------------------------------------------- 
           
           
           $flag_new_ask = false;
           $stage_key      = array();
            
           $list_stage_key = Model::factory("stage_key")->getList(array("user_id"         => $user_id, 
                                                                        "user_donator_id" => $user_donator_id,
                                                                        "stage_stat_id"   => $stage_stat_id));
                                                               
                                                               
           if( is_array($list_stage_key) && 0 != count($list_stage_key)){
                 $flag_new_ask = false;
                 $stage_key      = $list_stage_key[0];
           } else {
                 $flag_new_ask = true; 
           } 
            
            
           //stage_key_time_limit
            
           if(true == $flag_new_ask) {
                
               $status   = 0;
               $stage_key = array("user_id"          => $user_id, 
                                 "user_donator_id"  => $user_donator_id, 
                                  "stage_stat_id"    => $stage_stat_id,
                                  "status"           => 0,
                                  "time"             => SConfig::$time);
               $obj_stage_key = Model::factory("stage_key")->create( $stage_key );
               $stage_key = $obj_stage_key->get();  
                   
               $this->timeToStageKeyAsk( $stage_key );
                    
               return array("result" => 1, "stage_key" => $stage_key);   
           } else {
                    
               $this->timeToStageKeyAsk( $stage_key );
                    
               if($stage_key["status"] == 0){
                  if($stage_key["time"] <= 0){
                          
                     $stage_key["time"] =  SConfig::$time;
                     Model::factory("stage_key")->create( $stage_key ); 
                         
                     $this->timeToStageKeyAsk( $stage_key );
                        
                     return array("result" => 1, "stage_key" => $stage_key);   
                  } else {
                     return array("result" => -121, "text" => "too little time since the previous ask");
                  }
               } else {
                  return array("result" => -122, "text" => "key has already come or too little time since the previous get a key");
               }
               return array("result" => -121, "text" => "ask already exists");  
           }
            
    
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "stageModel", "stageKeyAsk", $user_id);
            throw new Exception ($e->getMessage(), $e->getCode());
        } 
    }   
    
    /**
    * Послать подарок
    *  -  -  (bigint)  user_from              : номер игрока из соц сети который посылает подарок
    *  -  -  (bigint)  user_to                : номер игрока из соц сети которому посылается подарок (который просит подарок)
    */                                          
    public function stageKeySend($user_donator_id, $stage_key_id){
       try{
           
            if(!Model::factory('user', $user_donator_id)->exist()){
                return array("result" => -1, "text" => "user_donator_id not exist"); 
            }
            
            if( !Model::factory("stage_key", $stage_key_id)->exist()){
                return array("result" => -123, "text" => "stage_key id not exist"); 
            }
           
            $stage_key = Model::factory("stage_key", $stage_key_id)->get();
            
            $user_id = $stage_key["user_id"];
            
            if(!Model::factory('user', $user_id)->exist()){
                return array("result" => -1, "text" => "user_id not exist"); 
            }
            
            if(1 == $stage_key["status"]){
                return array("result" => -124, "text" => "stage_key hes already send");
            }
            
            if(0 != $stage_key["status"]){
                return array("result" => -125, "text" => "stage_key not in ask status");
            }
            //////////////////////////////////////////////////////////////////////
            //////////////////////////////////////////////////////////////////////
            //////////////////////////////////////////////////////////////////////
            //////////////////////////////////////////////////////////////////////
            //Проверка - в тему ли вообще этот запрос?
            //И пора ли открвать этот этап или нет
            
            //выполнен ли предыдущий этап?
            //if(!$this->checkCompliteStage($user_id , $stage_key["stage_stat_id"])){
            //    errors::exc(errors::errorIncorrectInput, "stage missions stat not exist");
            //}
            //////////////////////////////////////////////////////////////////////
            //////////////////////////////////////////////////////////////// //////
            //////////////////////////////////////////////////////////////////////
            //////////////////////////////////////////////////////////////////////
            
            
            $stage_key["status"] = 1;
            $stage_key["time"]   = SConfig::$time;
            
            Model::factory("stage_key")->create( $stage_key ); 
            
            $stage_key["time"] =  0; 
            
            return array("result" => 1, "stage_key" => $stage_key); 
           
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "stageModel", "stageKeySend", $user_id);
            throw new Exception ($e->getMessage(), $e->getCode());
        } 
    } 
    
    /**
    * Послать подарок
    *  -  -  (bigint)  user_from              : номер игрока из соц сети который посылает подарок
    *  -  -  (bigint)  user_to                : номер игрока из соц сети которому посылается подарок (который просит подарок)
    */                                          
    public function stageKeyCancel($user_id, $stage_key_id){
       try{
           
           
            if(!Model::factory('user', $user_id)->exist()){
                return array("result" => -1, "text" => "$user_id not exist"); 
            }
            
            if( !Model::factory("stage_key", $stage_key_id)->exist()){
                return array("result" => -123, "text" => "stage_key id not exist"); 
            }
           
            $stage_key = Model::factory("stage_key", $stage_key_id)->get();
            
            if($stage_key["user_id"] != $user_id && $stage_key["user_donator_id"] != $user_id ){
                return array("result" => -126, "text" => "illegal user try cancel stage key ask"); 
            } 
            
            if(1 == $stage_key["status"]){
                return array("result" => -127, "text" => "can not cancel active key, status = 1");  
            }
            
            Model::factory("stage_key")->delete(array("id" => $stage_key_id));
            
            return array("result" => 1, "stage_key_id" => $stage_key_id); 
           
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "stageModel", "stageKeyCancel", $user_id);
            throw new Exception ($e->getMessage(), $e->getCode());
        } 
    }
    
    public function timeToStageKeyAsk( &$arr_ask ){ 
        try{
        
             $stage_key_time_limit       = Model::factory ( 'var' )->loadByKey ( 'stage_key_time_limit' )->value;
             
             if(0 == $arr_ask["status"]){   
                 if( SConfig::$time > $arr_ask["time"] + $stage_key_time_limit ){
                     $arr_ask["time"] = 0;
                 } else {
                     $arr_ask["time"] = $arr_ask["time"] + $stage_key_time_limit - SConfig::$time; 
                 }
             }  else {
                $arr_ask["time"] = SConfig::$time - $arr_ask["time"];
             }
             return true;
         } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "stageModel", "timeToStageKeyAsk");
            throw new Exception ($e->getMessage(), $e->getCode());
        }
    }     
    
    //просьбы ключей для этапов----------------------------------------------------------------------------------------------
    //-----------------------------------------------------------------------------------------------------------------------
    //-----------------------------------------------------------------------------------------------------------------------
    //-----------------------------------------------------------------------------------------------------------------------
    //-----------------------------------------------------------------------------------------------------------------------
  
  
    public function checkStageTime($user_id, $company_stat_id, $stage_position){
        try{
            
            if(!Model::factory('user', $user_id)->exist()){
                return array("result" => -1, "text" => "$user_id not exist"); 
            }
            
            if(!Model::factory('company_stat', $company_stat_id)->exist()){
               //return array();
                errors::exc(errors::errorIncorrectInput, "company_stat $company_stat_id not exist");
            }
            
            //-----------------------------------------------------------------------------------------------------------------------
            //-----------------------------------------------------------------------------------------------------------------------
            //этапа может еще не существовать на момент подсчета времени
            if(0){
                $arr_stage_stat = Model::factory("stage_stat")->getList(array("company_stat_id" => $company_stat_id, "position" => $stage_position));
                if(!is_array($arr_stage_stat) || 0 == count($arr_stage_stat)){
                     errors::exc(errors::errorIncorrectInput, "error in position? stage_stat not found");
                }
                $stage_stat_id = $arr_stage_stat[0]["id"];
            }
            //-----------------------------------------------------------------------------------------------------------------------
            //-----------------------------------------------------------------------------------------------------------------------
            
            
            if(0){
                $stage_stat       = Model::factory("stage_stat",   $stage_stat_id)->get();
                $company_stat_id  =  $stage_stat["company_stat_id"];
                $stage_position   =  $stage_stat["position"];
            }
           
            $list_stage_time = Model::factory("stage_time")->getList(array("user_id"          => $user_id, 
                                                                           "company_stat_id"  => $company_stat_id,
                                                                           "stage_position"   => $stage_position));
           
            $time_to_open = 0;
            if( is_array($list_stage_time) && 0 != count($list_stage_time)){
                 
                 $time_start        = $list_stage_time[0]["time"]; 
                 $time_after_start  = SConfig::$time - $list_stage_time[0]["time"]; 
                
                 $stage_start_cost_time       = Model::factory ( 'var' )->loadByKey ( 'stage_start_cost_time' )->value;
          
                 if($time_after_start >= $stage_start_cost_time){
                    $time_to_open = 0;  
                 } else {
                    $time_to_open = $stage_start_cost_time - $time_after_start; 
                 }
                 
                 return array("result" => 1, "stage_time_id" => $list_stage_time[0]["id"], "company_stat_id" => $company_stat_id, "stage_position" => $stage_position, "time" => $time_to_open); 
                
            } else {
                  return array("result" => -127, "text" => "stage time not exist"); 
            } 
            
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "stageModel", "checkStageTime", $user_id);
            throw new Exception ($e->getMessage(), $e->getCode());
        }
   }
   
    public function getStageActualTime($user_id){
       try{
           if(!Model::factory('user', $user_id)->exist()){
               return array();
               // errors::exc(errors::errorIncorrectInput, "user $user_id id not exist");
           }
           
           $listTime =  Model::factory("stage_time")->getList(array("user_id" => $user_id));
           $stage_start_cost_time       = Model::factory ( 'var' )->loadByKey ( 'stage_start_cost_time' )->value;
                          
           foreach($listTime as &$stage_time){
               if(isset($stage_time['user_id'])){
                   //-----------------------------------------------------------------------
                   if( is_array($stage_time) && 0 != count($stage_time)){
                 
                         $time_start        = $stage_time["time"]; 
                         $time_after_start  = SConfig::$time - $stage_time["time"]; 
                        
                   
                         if($time_after_start >= $stage_start_cost_time){
                            $time_to_open = 0;  
                         } else {
                            $time_to_open = $stage_start_cost_time - $time_after_start; 
                         }
                       $stage_time['time'] = $time_to_open;   
                    }
                   //-----------------------------------------------------------------------
                   unset($stage_time['user_id']); 
               }
           }
           
           if(!is_array( $listTime ) || 0 == count($listTime)){
              $listTime = array(); 
           }
           
           return $listTime;
       } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "stageModel", "getStageActualTime", $user_id);
            throw new Exception ($e->getMessage(), $e->getCode());
        } 
  }
  
    public function  getPreviousStage( $user_id, $stage_stat_id, &$arr_previous_stage_stat = array()){
       try{ 
       
           $stage_stat      = Model::factory("stage_stat",   $stage_stat_id)->get();
           $company_stat_id = $stage_stat["company_stat_id"];
           $stage_position  = $stage_stat["position"];
           $company_stat    = Model::factory("company_stat", $company_stat_id)->get();
           
           $arr_previous_stage_stat     = array();
               

           $previous_stage_position = 0;
           if($stage_stat["position"] > 0){
              $previous_stage_position = $stage_stat["position"] - 1;
              
              while($previous_stage_position >= 0){ 
                  $list_previous_stage_stat   = Model::factory("stage_stat")->getList( array("position"        => $previous_stage_position,
                                                                                             "company_stat_id" => $stage_stat["company_stat_id"]
                                                                                      ));
                  $arr_previous_stage_stat = $list_previous_stage_stat[0]; 
                  if(!is_array($arr_previous_stage_stat) || 0 == count($arr_previous_stage_stat) ){
                      $previous_stage_position--;
                      continue;
                  }
                  break;                                                             
              }
        
              $previous_stage      = Model::factory("stage")->getList(array("user_id"=> $user_id, "stage_stat_id" => $arr_previous_stage_stat["id"]));
              if( !is_array($previous_stage) || count($previous_stage) == 0 ){
                 return false;
              }
              return true;                                                              
           } 
              
           return false;     
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "stageModel", "getPreviousStage", $user_id);
            throw new Exception ($e->getMessage(), $e->getCode());
        }
        
    }
    
    public function  checkStageMissionComplite( $user_id, $stage_stat_id, &$star_count = 0 ){
       try{ 
           
           //-------------------------------------------------------------------------------------------
           
           $listStageMissionStat = array();
           //Находим все статические миссиис сортировкой по полю position-------------------------------------------------------------------------
           $listStageMissionStat = Model::factory("mission_stat")->getList(array("stage_stat_id" => $stage_stat_id), array("id"));
            
           if( 0 == count($listStageMissionStat)){
                errors::exc(errors::errorIncorrectInput, "stage missions stat not exist");
           }
           
           
           //1. Если миссия первая в списке миссий этапа---------------------------------------
           //2. Все миссии уже игрались---------------------------------------------
           foreach($listStageMissionStat as $arr_mission_stat){
               $aMission = Model::factory("mission")->getMissionByStatId($user_id, $arr_mission_stat["id"]);
               if(0 == count($aMission)){
                   return false;
               } else {
                   $star_count+= $aMission["star"];
               } 
           }

              return true;
           
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "stageModel", "checkStageMissionComplite", $user_id);
            throw new Exception ($e->getMessage(), $e->getCode());
        }
        
    } 
    
    
    public function checkCompliteStage( $user_id, $stage_stat_id ){
       try{ 
           
           //-------------------------------------------------------------------------------------------
           
           $listStage = array();
           //Находим все статические миссиис сортировкой по полю position-------------------------------------------------------------------------
           $listStage = Model::factory("stage")->getList(array( "user_id"=> $user_id, "stage_stat_id" => $stage_stat_id, "flag_complete" => 1), array("id","flag_complete"));
            
           if( !is_array($listStage) || 0 == count($listStage)){
               return false;
           }  else {
               return true;
           }
           return false;
           
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "stageModel", "checkCompliteStage", $user_id);
            throw new Exception ($e->getMessage(), $e->getCode());
        }
        
    } 
    
      public function refreshStage( $user_id ){
          try{ 
              
                $result['result'] = 1;  
                $result['stage']       = Model::factory('stage')->getListStage($user_id);
                $result['stage_key']   = Model::factory('stage')->getStageActualKey($user_id);
                $result['stage_time']  = Model::factory('stage')->getStageActualTime($user_id);
               
                return $result;
                
          } catch(Exception $e) {
                
                LOG_CRASH::add($e->getCode(), $e->getMessage(), "stageModel", "refreshStage", $user_id);
                throw new Exception ($e->getMessage(), $e->getCode());
          }
      } 
}


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

<?php
/**
 * 
 * Класс обработки раунда
 */
class user_taskModel extends Model{
    
    protected $_tableName = 'user_task';
    
    /**
    * Инициализация задания для раунда
    * 
    * Происходит при создании раунда вызывается
    * 
    * @param (bigint)   user_id        : номер игрока в таблице users
    * @param (int)      round_id       : id раунда<div></div>
    * @param (int)      active_user    : порядковый номер пользователя загадывающего задание
    * @param (int)      question_id    : номер статического задания
    * @param (&array)   aTaskSet       : возвращает список заданий
    * 
    * @return 1 int 
    */ 
    public function createTask($user_id, $round_id, $active_user, $question_id, $str_question, &$aTask, &$word_mask){
        try{
            
            $try_count = Model::factory ( 'var' )->loadByKey ( 'question_try_count' )->value;
           
            //-------------------------------------------------------------------------------
            //подбор открытых изначально букв
            //1) ищем гласные в слове
            //находим недостающие буквы
            $question_count = strlen($str_question) ;
                
            $char          = "";
            $arr_pos_char  = array();
            $bit_mask      = 0;
            $arr_word_mask = "";
            $word_mask     = "";
            //--------------------------------------------------------------------------------------------------------------------
            for($i = 0; $i < $question_count; $i++){
                $word_mask = $word_mask.'*';
                if(0 == count($arr_pos_char)){
                    
                    $char       = Model::factory("word")->convert_to_out($str_question[$i]);
                    $list_sound = Model::factory("char_stat")->getList( array("char" => $char, 'sound_type' => 0), array("sound_type"));
                    if( is_array($list_sound) && 0 != count($list_sound)){
                        $char           = $str_question[$i]; 
                        $arr_pos_char[] = $i;
                        continue;
                    }
                } else {
                   if( $char === $str_question[$i]){
                        $arr_pos_char[] = $i; 
                    }
                }
            }   
       
            //bit--------------------------
            foreach($arr_pos_char as $pos){
               $bit_mask |= 1 << $pos;
               $word_mask[ $pos ] = $char;
            }
            //bit-->
            
            //задание создается для другого игрока
            $next_active_user = 0;
            if($active_user == 0){
                $next_active_user = 1; 
            } else {
                $next_active_user = 0;
            }  
            //-------------------------------------------------------------------------------
            $aTask = array( "user_round_id" => $round_id,
                            "task_stat_id"  => $question_id,
                            "result_user"   => -1,
                            "active_user"   => $next_active_user,
                            "try_count"     => $try_count,
                            "bit_mask"      => $bit_mask,
                            "fail_signs"    => "",
                            "history"       => "".Model::factory("word")->convert_to_out($char));
                            
            Model::factory("user_task")->create($aTask); 
            //--------------------------------------------------------------------------------------
            return 1;
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "user_taskModel", "createTaskSet", $user_id);
            throw new Exception ($e->getMessage(), $e->getCode());
        }
    }
  
    /**
    * Инициализация задания для раунда
    * 
    * Происходит при создании раунда вызывается
    * 
    * @param (&array)   aTaskSet       : передаваемый по ссылке массив с набором заданий
    * 
    * @return 1 int 
    */ 
    public function getTaskSetWithQuestion($user_id, &$aTaskSet){
        try{
            //подготовка данных к отправке клиенту 
            for($i = 0; $i < count($aTaskSet); $i++){
               $aTaskStat = Model::factory("task_stat", $aTaskSet[$i]["task_stat_id"] )->get();
               $question_shuffle          = ""; 
                    
               $count = 0;
               while(10 > $count){

                  $word = $aTaskStat['question'];
                  //str_shuffle  не работает с юникодом
                  $code = mb_detect_encoding($word);
                  $word = iconv($code,'cp1251',$word);
                  $question_shuffle = str_shuffle($word);
                  $flag_shuffle = true;
                  if(0 != strcmp($word, $question_shuffle)){
                       $flag_shuffle = true;
                  }
                  $question_shuffle = iconv('cp1251', $code, $question_shuffle);
                  if($flag_shuffle == true){
                       break;
                  }
                  $count++;
               }
               if($count >= 10 ){
                   errors::exc(errors::errorLogic,"multiple failures with stirring words" ); 
               }
               
               $aTaskSet[$i]["question"] = $question_shuffle;
               $aTaskSet[$i]["answer"]   = md5($aTaskStat['text']);
            }
            //----------------------------------------------------------------------------------
            return 1;
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "user_taskModel", "createTaskSet", $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 getRoundTaskSet($user_id, $round_id){
        try{
            $aRoundTaskSet = Model::factory("user_task")->getList(array("user_round_id" => $round_id), array(), "id");
            //--------------------------------------------------------------------------------------
            return $aRoundTaskSet;
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "user_taskModel", "createTaskSet", $user_id);
            throw new Exception ($e->getMessage(), $e->getCode());
        }
     }
     
    /**
    * Подготавливает данные для возврата их клиенту (запрос start)
    * @return array Массив возвращаемых значений, cодержит:
    *  -  (bigint) user_id    :  идентификатор пользователя в игре 
    *  -  (array)  aTaskSet   :  передается по ссылке, массив с данными о игре
    */ 
    public function convertTask($user_id, $word_mask, &$aTask ){
          try{
               unset($aTask["bit_mask"]);
               $aTask["mask"] = Model::factory("word")->convert_to_out($word_mask);
              
          } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "gameModel", "convertTaskSet", $user_id);
            throw new Exception ($e->getMessage(), $e->getCode());
        } 
    }
    
    /**
    * Подготавливает данные для возврата их клиенту (запрос start)
    * @return array Массив возвращаемых значений, cодержит:
    *  -  (bigint) user_id    :  идентификатор пользователя в игре 
    *  -  (array)  aTaskSet   :  передается по ссылке, массив с данными о игре
    */ 
    public function convertTaskSet($user_id, &$aTaskSet ){
          try{
                 foreach($aTaskSet as &$aTask){
                    unset($aTask["bit_mask"]);
                    if(! is_null($aTask["mask"])){
                        $aTask["mask"] = Model::factory("word")->convert_to_out($word_mask);
                    }
                 }
               // действий в данный момент не требуется              
             } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "gameModel", "convertTaskSet", $user_id);
            throw new Exception ($e->getMessage(), $e->getCode());
        } 
    }
    
    /**
    * обновляет данные в списке заданий (запрос end)
    * @return array Массив возвращаемых значений, cодержит:
    *  -  (bigint) user_id    :  идентификатор пользователя в игре 
    *  -  (array)  aTaskSet   :  передается по ссылке, массив с данными о игре
    */ 
    public function updateTaskSet($user_id, $aTaskSet){
        try{
            foreach( $aTaskSet as $task){
                $this->create( $task );
            }
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "gameModel", "updateTaskSet", $user_id);
            throw new Exception ($e->getMessage(), $e->getCode());
        } 
    } 
    
    
    /**
    * Удалить задания относящиеся к раунду
    * 
    * Только при создании раунда вызывается
    * 
    * @param  (bigint)    user_id        : номер игрока в таблице users
    * @param  (int)       round_id       : id раунда

    * 
    * @return (array)     1 
    */ 
    public function deleteTaskSet($user_id, $round_id){
        try{
            //---------------------------------------------------------------------------------------
             $list =  Model::factory("user_task")->getList(array("user_round_id" => $round_id), array("id"));
             foreach($list as $task){
               Model::factory("user_task", $task["id"])->delete();    
             }
             //или
             //Model::factory("user_task")->delete(array("user_round_id" => $round_id));
            //--------------------------------------------------------------------------------------
            return 1;
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "user_taskModel", "createTaskSet", $user_id);
            throw new Exception ($e->getMessage(), $e->getCode());
        }
     }
     
     
     //---------------------------------------------------------------------------------------------------
     //---------------------------------------------------------------------------------------------------
     //---------------------------------------------------------------------------------------------------
     //---------------------------------------------------------------------------------------------------
     //---------------------------------------------------------------------------------------------------
    
        
     /**
     * При загадывании слова добавляет пустую букву - игрок может выбрать любую букву из алфавита и добавить в список допустимых для использования (в конец списка). 
     * 
     * Бустрер 2 (при загадывании)   
     * 
     * @param bigint user_id
     * @param int    task_id
     * 
     * @return int 1 - успех
     */
     public function addMySignInOpenChar($user_id, $game_id, $sign, &$open_chars){
         try{
             
             //------------------------------------------------------------------
             //<--проверки
             if( !Model::factory("user_game", $game_id)->exist()){
                 errors::exc(errors::errorIncorrectInput,"user_game not exist" );
             }
             $game = Model::factory("user_game", $game_id)->get(); 
             if( ! Model::factory("game")->isPlayerTurn($user_id, $game)){
                 errors::exc(errors::errorIncorrectInput,"another player turn" ); 
             }
             //------------------------------------------------------------------

             if(!Model::factory("user_game_ask_buffer", $game_id)->exist()){ 
                  errors::exc(errors::errorIncorrectInput,"user_game_ask_buffer is not exist" ); 
             }
             $terms = Model::factory("user_game_ask_buffer", $game_id)->get();
             
             $str_open_chars = Model::factory("word")->convert_to_in( $terms["open_chars"] );
             $str_sign = Model::factory("word")->convert_to_in( $sign );
             $str_open_chars .= $str_sign;
             
             $open_chars = Model::factory("word")->convert_to_out( $str_open_chars );
             $terms["open_chars"] = $open_chars;
             Model::factory("user_game_ask_buffer")->create($terms);
         
             return 1;
         } catch(Exception $e) {
            
             LOG_CRASH::add($e->getCode(), $e->getMessage(), "user_taskModel", "addTry", $user_id);
             throw new Exception ($e->getMessage(), $e->getCode());
         }
     }  
     
    /**
     * При загадывании слова игроку дается возможность удалить ненужные ему буквы кандидаты и на их место будут добавлены другие (выбирает сервер)
     * Бустер активируется только если сейчас ход текущего игрока. 
     * Возвращается полная строка новых символов. Клиент сам сопоставляет какие символы были изменеы
     * 
     * Бустрер 3 (при загадывании)   
     * 
     * @param bigint user_id
     * @param int    task_id
     * 
     * @return int 1 - успех
     */
     public function replaceSigns($user_id, $game_id, $open_chars_old, &$open_chars){
         try{
             
             //гласные менять на гласные, согласные на согласные 
             //------------------------------------------------------------------
             //<--проверки
             if( !Model::factory("user_game", $game_id)->exist()){
                  errors::exc(errors::errorIncorrectInput,"user_game not exist" );
             }
             $game = Model::factory("user_game", $game_id)->get(); 
             
             if( ! Model::factory("game")->isPlayerTurn($user_id, $game)){
                 errors::exc(errors::errorIncorrectInput,"another player turn" ); 
             }
             //------------------------------------------------------------------

             if(!Model::factory("user_game_ask_buffer", $game_id)->exist()){ 
                  errors::exc(errors::errorIncorrectInput,"user_game_ask_buffer is not exist" ); 
             }
             $terms = Model::factory("user_game_ask_buffer", $game_id)->get();
             
             $str_open_chars     = Model::factory("word")->convert_to_in( $terms["open_chars"] );
             $str_open_chars_old = Model::factory("word")->convert_to_in( $open_chars_old );
             
             $open_chars_length = strlen( $str_open_chars );
             $replace_count = 0;
             $replace_count_limit = Model::factory ( 'var' )->loadByKey ( 'replace_signs_limit' )->value;
             
             $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);
                             
             for( $pos = 0; $pos < $open_chars_length; $pos++){
                 if( !is_null( $str_open_chars[ $pos ] )  && !is_null( $str_open_chars_old[ $pos ] ) ){
                     
                         if( $str_open_chars_old[ $pos ] === "*"){
                             if($replace_count >= $replace_count_limit ){
                                 errors::exc(errors::errorIncorrectInput,"replace count limit" ); 
                             }
                             $str_replace_char = Model::factory("word")->convert_to_out( $str_open_chars[ $pos ] );
                             $list_char = Model::factory("char_stat")->getList(array("char" => $str_replace_char));
                             $char     = "";
                             $str_char = "";
                             if( 0 == $list_char[0]["sound_type"]){
                                 $char     = $list_sound_0[ rand(0, $souns_count_0 - 1)]["char"]; 
                                 $str_char = Model::factory("word")->convert_to_in($char); //convert
                             } else {
                                 $char     = $list_sound_1[ rand(0, $souns_count_1 - 1)]["char"]; 
                                 $str_char = Model::factory("word")->convert_to_in($char); //convert
                             }
                             $str_open_chars[ $pos ]  =  $str_char;
                             $replace_count++;
                          }
                          
                 } else {
                     errors::exc(errors::errorIncorrectInput,"open_chars error" ); 
                 }  
             }
             
             
             $open_chars = Model::factory("word")->convert_to_out( $str_open_chars );
             $terms["open_chars"] = $open_chars;
             Model::factory("user_game_ask_buffer")->create($terms);
         
             return 1;
         } catch(Exception $e) {
            
             LOG_CRASH::add($e->getCode(), $e->getMessage(), "user_taskModel", "addTry", $user_id);
             throw new Exception ($e->getMessage(), $e->getCode());
         }
     } 
      
     /**
     * Добавляет одну попытку для угадывания задания при использовании бустера
     * 
     * Бустрер 0  
     * 
     * @param bigint user_id
     * @param int    task_id
     * 
     * @return int 1 - успех
     */
     public function addTry($user_id, $task_id, &$try_count){
         try{
           
             //------------------------------------------------------------------
             //<--проверки
             if( !Model::factory("user_task", $task_id)->exist()){ 
                 return 0; 
             }
             $task = Model::factory("user_task",$task_id)->get();
             
             $try_count = 0;
             $try_count = $task["try_count"];
             
             if( !Model::factory("user_round", $task["user_round_id"])->exist()){ 
                 errors::exc(errors::errorIncorrectInput,"user_round not exist" );
             }
             $round = Model::factory("user_round", $task["user_round_id"])->get(); 
             if( !Model::factory("user_game", $round["user_game_id"])->exist()){
                 errors::exc(errors::errorIncorrectInput,"user_game not exist" );
             }
             $game = Model::factory("user_game", $round["user_game_id"])->get(); 
             if( ! Model::factory("game")->isPlayerTurn($user_id, $game)){
                 errors::exc(errors::errorIncorrectInput,"another player turn" ); 
             }
             if( $game["active_round_id"] != $round["id"]){
                 errors::exc(errors::errorIncorrectInput,"round is not acrive" ); 
             }
             //------------------------------------------------------------------
             //проверки>
                 
             $question_try_count = Model::factory ( 'var' )->loadByKey ( 'question_try_count' )->value;
            
             if($question_try_count <= $task["try_count"]){
                 return 0;
             }
                 
             $task["try_count"] += 1;
             $try_count = $task["try_count"];
       
             Model::factory("user_task")->create( $task );
             return 1;

         } catch(Exception $e) {
            
             LOG_CRASH::add($e->getCode(), $e->getMessage(), "user_taskModel", "addTry", $user_id);
             throw new Exception ($e->getMessage(), $e->getCode());
         }
     }
     
     /**
     * Открывает одну правильную букву. (Находит и сообщает игроку одну неизвествую букву в угадываемом слове)
     * 
     * Бустрер 1   
     * 
     * @param bigint user_id
     * @param int    task_id
     * 
     * @return int 1 - успех
     */
     public function getRightSign($user_id, $task_id, &$sign){
         try{
             //------------------------------------------------------------------
             //<--проверки
             if( !Model::factory("user_task", $task_id)->exist()){ 
                 return 0; 
             }
             $task = Model::factory("user_task",$task_id)->get();
             if( !Model::factory("user_round", $task["user_round_id"])->exist()){ 
                 errors::exc(errors::errorIncorrectInput,"user_round not exist" ); 
             }
             $round = Model::factory("user_round", $task["user_round_id"])->get(); 
             if( !Model::factory("user_game", $round["user_game_id"])->exist()){
                 errors::exc(errors::errorIncorrectInput,"user_game not exist" );
             }
             $game = Model::factory("user_game", $round["user_game_id"])->get(); 
             if( ! Model::factory("game")->isPlayerTurn($user_id, $game)){
                 errors::exc(errors::errorIncorrectInput,"another player turn" );  
             }
             if( $game["active_round_id"] != $round["id"]){
                 errors::exc(errors::errorIncorrectInput,"round is not acrive" ); 
             }
             //------------------------------------------------------------------
             //проверки>
                 
             $task = Model::factory("user_task",$task_id)->get();
             $task_stat = Model::factory("task_stat", $task["task_stat_id"])->get();
                 
             $str_question   = Model::factory("word")->convert_to_in($task_stat["question"]); //convert
             $bit_mask       = $task['bit_mask'];
                 
             //ищем позиции не открытых букв
             $open_sign_count = 0;
             $arr_lock_pos = array();
             $word_length = strlen( $str_question );
             for($pos = 0; $pos < $word_length;  $pos++){
                $bin_pos = 1 << $pos;
                if( $bit_mask & $bin_pos){
                   // буква открыта
                } else {
                   $arr_lock_pos[] = $pos; 
                }
             }
                 
             if( ! is_array($arr_lock_pos) || 0 < count($arr_lock_pos)){
                 $pos_open = $arr_lock_pos [ rand(0, count($arr_lock_pos) - 1) ]; 
                 $str_sign = $str_question[ $pos_open ];
                 $sign     = Model::factory("word")->convert_to_out( $str_sign );
                 return 1;
             } else {
                 return 0;
             } 
             
             return 0;
         } catch(Exception $e) {
            
             LOG_CRASH::add($e->getCode(), $e->getMessage(), "user_taskModel", "addTry", $user_id);
             throw new Exception ($e->getMessage(), $e->getCode());
         }
     }
     
     
 
     
     /**
     * Использовать бустер ( booster type = 4 ). Скрыть символы не входящие в слово.
     *
     * Используетяся при разгадывании слова. Скрывает несколько не используемых в слове букв.
     * Не используемые буквы добавляются в uset_task.fail_signs, это значит что клиент должен сопоставить  history и fail_signs, и все чего нет в history а есть при этом в fail_signs - это не ошибки а скрытые буквы. 
     * 
     * Бустрер 4 (при разгадывании)   
     * 
     * @param bigint user_id
     * @param int    task_id
     * 
     * @return int 1 - успех
     */
     public function freezeSigns($user_id, $task_id, &$fail_signs){
         try{
             
             //------------------------------------------------------------------
             //<--проверки
             if( !Model::factory("user_task", $task_id)->exist()){ 
                 return 0; 
             }
             $task = Model::factory("user_task",$task_id)->get();
             if( !Model::factory("user_round", $task["user_round_id"])->exist()){ 
                 errors::exc(errors::errorIncorrectInput,"user_round not exist" ); 
             }
             $round = Model::factory("user_round", $task["user_round_id"])->get(); 
             if( !Model::factory("user_game", $round["user_game_id"])->exist()){
                 errors::exc(errors::errorIncorrectInput,"user_game not exist" );
             }
             $game = Model::factory("user_game", $round["user_game_id"])->get(); 
             if( ! Model::factory("game")->isPlayerTurn($user_id, $game)){
                 errors::exc(errors::errorIncorrectInput,"another player turn" );  
             }
             if( $game["active_round_id"] != $round["id"]){
                 errors::exc(errors::errorIncorrectInput,"round is not acrive" ); 
             }
             //------------------------------------------------------------------
             //проверки>

             $task_stat = Model::factory("task_stat", $task["task_stat_id"])->get();
                 
             $str_question   = Model::factory("word")->convert_to_in($task_stat["question"]); //convert
             
             $arr_question = array();
             for($pos = 0; $pos < strlen( $str_question ); $pos++){
                $arr_question[] =  $str_question[ $pos ];
             }
             
             $list_char_stat =  Model::factory("char_stat")->getList(); 
             $arr_char_stat = array();
             foreach($list_char_stat as $char_stat){
                 $arr_char_stat[] = Model::factory("word")->convert_to_in( $char_stat["char"] );
             }
             
             $arr_missing_chars = array_diff ( $arr_char_stat, $arr_question );
             
             $str_fail_signs = Model::factory("word")->convert_to_in( $task["fail_signs"]);
             $arr_fail_signs = array();
            
             for($pos = 0; $pos < strlen( $str_fail_signs ); $pos++){
                $arr_fail_signs[] =  $str_fail_signs[ $pos ];
             }
             
             $arr_missing_chars  = array_diff( $arr_missing_chars , $arr_fail_signs);
              
             $freeze_signs_limit = $question_try_count = Model::factory ( 'var' )->loadByKey ( 'freeze_signs_limit' )->value;
             
             $pos_chars = array();
             if($freeze_signs_limit <= count($arr_missing_chars)){
                 while(count($pos_chars) < $freeze_signs_limit){
                    
                     $pos = rand(0, count($arr_missing_chars) - 1);
                     if(!in_array($pos, $pos_chars)){
                        $pos_chars[] = $pos;
                     }
                 }
             } else {
                 return 0;
             }
             
             $arr_missing_chars = array_values($arr_missing_chars);
             foreach($pos_chars as $fail_char_pos){
                 $str_fail_signs .= $arr_missing_chars[ $fail_char_pos ];
             }
                 
             $fail_signs =  Model::factory("word")->convert_to_out( $str_fail_signs );
             $task["fail_signs"] = $fail_signs;
             Model::factory("user_task")->create( $task );
         
             return 1;
         } catch(Exception $e) {
            
             LOG_CRASH::add($e->getCode(), $e->getMessage(), "user_taskModel", "addTry", $user_id);
             throw new Exception ($e->getMessage(), $e->getCode());
         }
     } 
      //При загадывании слова добавляет пустую букву - игрок может выбрать любую букву из алфавита и поставить в любое место и изменить ее.  
     // Убирает определенное количество букв которые не использууюся в слове
     // Открывает одну правильную букву.

    // При загадывании слова добавляет пустую букву - игрок может выбрать любую букву из алфавита и поставить в любое место и изменить ее. 
    // При загадывании слова игроку дается возможность удалить ненужные ему буквы кандидаты и на их место будут добавлены другие (выбирает сервер)
}

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

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

    protected $_tableName = 'char_stat';

}

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

<?php
/**
 * 
 * Класс модели пользователя
 */
class varModel extends Model {
	
	protected $_tableName = 'vars';
	
	/**
	 * @param string $key
	 * @return Model
	 */
	public function loadByKey($key) {  
        try{
		
            $this->_data = CacheAccess::get ( $this->_tableName . '_key_' . $key );
		    if (! $this->_data) {
			    $result = DBAccess::select ( $this->_tableName, array ('key' => $key ) );
			    if (isset ( $result [0] )) {
				    $this->loadFromArray ( $result [0], true );
				    $this->saveToCache ();
			    } else {
				    $this->_data = array ();
			    }
		    }
		    return $this;
        
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "varModel", "loadByKey");
            throw new Exception ($e->getMessage(), $e->getCode());
        } 
	}
    
    //Model::factory('var')->getValue('vinyl_layer_cost');
    public function getValue($key) {
        try{
        
            $list_value = Model::factory('var')->getList(array('key' => $key), array('value'));
            $value = $list_value[0]['value'];
            return $value;

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

}

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

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

================================================================================
ФАЙЛ: app/models/playlist/playlist_statModel.php
================================================================================

<?php
/**
 * 
 */
class playlist_statModel extends Model {
    
    protected $_tableName = 'playlist_stat';
    
      public function addPlaylist($name_playlist, $enabled_flag = 1){
        try{
            $listPlaylist =  $this->getList(array("name" => $name_playlist));
            if(0 == isset($listPlaylist) || 0 == count($listPlaylist)){
                $this->create(array("name" => $name_playlist,  "enabled_flag" => $enabled_flag));
                $this->save();
                return 1;
            } else {
                return 0;
            }
        //--------------------------------------------------------------------------
        return -1;
        } catch(Exception $e) {
            
        LOG_CRASH::add($e->getCode(), $e->getMessage(), "playlist_statModel", "addPlaylist");
        throw new Exception ($e->getMessage(), $e->getCode());
        }       
    }
    
    /**
    * 
    * Возвращает все плейлисты которые сейчас есть в наличии
    * 
    */
    
     public function getListPlaylist(){
         try{
            return $this->getList();
         } catch(Exception $e) {
            
        LOG_CRASH::add($e->getCode(), $e->getMessage(), "playlist_statModel", "getListPlaylist");
        throw new Exception ($e->getMessage(), $e->getCode());
        } 
     }
     
     public function getIdPlaylist( $playlist_name ){
         try{
            $listPlaylist = $this->getList(array( "name" => $playlist_name ), array("id"));
            return $listPlaylist[0]["id"];
         } catch(Exception $e) {
            
        LOG_CRASH::add($e->getCode(), $e->getMessage(), "playlist_statModel", "getListPlaylist");
        throw new Exception ($e->getMessage(), $e->getCode());
        } 
     }
     
     public function setNamePlaylist( $new_name, $enabled_flag = 1 ){
         try{  
             $this->name = $new_name;
             $this->enabled_flag = $enabled_flag; 
             $this->save();
             return true;
         } catch(Exception $e) {
            
        LOG_CRASH::add($e->getCode(), $e->getMessage(), "playlist_statModel", "getListPlaylist");
        throw new Exception ($e->getMessage(), $e->getCode());
        } 
     }
     
      public function getNamePlaylist( $playlist_id ){
         try{
            $listPlaylist = $this->getList(array( "id" => $playlist_id ), array("name"));
            return $listPlaylist[0]["name"];
         } catch(Exception $e) {
            
        LOG_CRASH::add($e->getCode(), $e->getMessage(), "playlist_statModel", "getListPlaylist");
        throw new Exception ($e->getMessage(), $e->getCode());
        } 
     }
     
     
     public function deletePlaylist($name_playlist){
        try{
            
            $listPlaylist =  $this->getList(array("name" => $name_playlist));
            if(0 == isset($listPlaylist) || 0 == count($listPlaylist)){
                return 0;
            } else {
                $playlist_task = Model::factory("task_stat")->getListTask($listPlaylist[0]["id"]);
                foreach($playlist_task as $task){
                    Model::factory("task_stat")->deleteTaskById($task["id"]);
                }
                $this->delete(array("id" => $listPlaylist[0]["id"]));
                $this->save();
                return 1;
            }
        //--------------------------------------------------------------------------
        return -1;
        } catch(Exception $e) {
            
        LOG_CRASH::add($e->getCode(), $e->getMessage(), "playlist_statModel", "deletePlaylist");
        throw new Exception ($e->getMessage(), $e->getCode());
        }       
    }
    
    
 }

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

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

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

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

     /**
     * 
     */ 
    public function setKey( $mission_stat_id = -1) {
        try{
            
            if($mission_id == -1){
                errors::exc(errors::errorIncorrectInput, "mission_stat_id not exist in set key"); 
            }
            
            if(!isset($this->id)){
                errors::exc(errors::errorIncorrectInput, "id not exist");
            }
            $user_id = $this->id;
            if(!Model::factory('user', $user_id)->exist()){
                errors::exc(errors::errorIncorrectInput, "user id not exist");
            }
            $start_key = rand(0,1000000);
            $id_user = $this->id;
            $aRecord = array('id'              => $user_id,
                             'key'             => $start_key,
                             'mission_stat_id' => $mission_stat_id );
            $this->create($aRecord);
            $this->save();
            
            return $start_key;
            
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "user_daily_actionsModel", "createRecord", $id_user);
            throw new Exception ($e->getMessage(), $e->getCode());
        }  
    }
    
    public function checkKey( $start_key = -1, &$mission_stat_id) {
        try{
            
            if(!isset($this->id)){
                errors::exc(errors::errorIncorrectInput, "id not exist");
            }
            $user_id = $this->id;
            if(!Model::factory('user', $user_id)->exist()){
                errors::exc(errors::errorIncorrectInput, "user id not exist");
            }
            
            $aKey = $this->get();
            if(isset($aKey["mission_stat_id"])){
               $mission_stat_id = $aKey["mission_stat_id"];
            } else {
               return false; 
            }
            if(!isset($aKey["key"])){
                return false;
            }
            if($aKey["key"] == $start_key && $start_key != -1){
                return true;
            }
            
            return false;
            
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "user_daily_actionsModel", "createRecord", $id_user);
            throw new Exception ($e->getMessage(), $e->getCode());
        }  
    }
    
    public function deleteKey( $start_key = -1) {
        try{
            
            if(!isset($this->id)){
                errors::exc(errors::errorIncorrectInput, "id not exist");
            }
            $user_id = $this->id;
            if(!Model::factory('user', $user_id)->exist()){
                errors::exc(errors::errorIncorrectInput, "user id not exist");
            }
            
         
            if(!isset($this->key)){
                return false;
            }
            $this->delete();
            $this->save();
         
            return false;
            
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "user_daily_actionsModel", "createRecord", $id_user);
            throw new Exception ($e->getMessage(), $e->getCode());
        }  
    }
    
}

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

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

    protected $_tableName = 'admin';       

}

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

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

	protected $_tableName = 'mail';
	

    
    /**
    * Посылает письмо
    * @param bigint   $user_id    номер игрока из соц сети
    * @param string   $title      заголовок письма (не обязательно)
    * @param int      $text       текст письма
    * result int      $mail_id    номер сообщения из табл. "mail"
    */                                          
    public function sendMail($user_from, $user_to, $title = "", $text = ""){
       try{
           
           if(0){
               if(!Model::factory('user', $user_from)->exist()){
                    errors::exc(errors::errorIncorrectInput, "user_from id not exist");
               }
               if(!Model::factory('user', $user_to)->exist()){
                    errors::exc(errors::errorIncorrectInput, "user_to id not exist");
               }
           }
           
           
           
           $read_status = 0;
           if($text == ""){
               errors::exc(errors::errorIncorrectInput, "text is empty"); 
           }

           $title = substr($title, 0, 100);
           $text = substr($text, 0, 200);
 
           $aMail = array('date'         => SConfig::$time, 
                          'user_id_out'  => $user_from,
                          'user_id_in'   => $user_to,
                          'title'        => $title,
                          'text'         => $text,
                          'read_status'  => $read_status );
                          
           $oMail =  Model::factory('mail')->create( $aMail );
           $aMail =  $oMail->get();
           $mail_id = $aMail["id"];
        
           return $mail_id;
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "mailModel", "sendMail", $user_from);
            throw new Exception ($e->getMessage(), $e->getCode());
        } 
    } 
    
    /**
    * Изменяет статс письма с "непрочитано" на "прочитано"
    * @param bigint $user_id    номер игрока из соц сети
    * @param int    $mail_id    номер письма из табл. mail
    * result bool
    */ 
    public function changeMailReadStatus($user_id, $mail_id){
        try{
    
            if(0){
                if(!Model::factory('user', $user_id)->exist()){
                    errors::exc(errors::errorIncorrectInput, "user id not exist");
                }
                if(!Model::factory('mail', $mail_id)->exist()){
                    errors::exc(errors::errorIncorrectInput, "mail id not exist");
                }
            }
            
            $listMail = Model::factory('mail')->getList(array('id' => $mail_id), array('id','read_status'));  
            $aMail = $listMail[0];
            $aMail['read_status'] = 1;
       
            Model::factory('mail')->create($aMail);

            return 1;
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "mailModel", "changeMailReadStatus", $user_id);
            throw new Exception ($e->getMessage(), $e->getCode());
        } 
        
    }
    
    /**
    * Удаляет письмо. Письмо может удалить только отправляющий или принимающий пользователи
    * @param bigint $user_id    номер игрока из соц сети
    * @param int    $mail_id    номер письма из табл. mail
    * result bool
    */
    public function deleteMail($user_id, $mail_id){
        try{
            
            if(0){
                if(!Model::factory('user', $user_id)->exist()){
                    errors::exc(errors::errorIncorrectInput, "user id not exist");
                }
                if(!Model::factory('mail', $mail_id)->exist()){
                    errors::exc(errors::errorIncorrectInput, "mail id not exist");
                }
                
                $aMail = Model::factory('mail', $mail_id)->get();
                if($user_id != $aMail['user_id_in'] && $user_id != $aMail['user_id_out'] ){
                    errors::exc(errors::errorIncorrectInput, "mail can delete only user how send mail and user how get mail");
                }
            }
            
            //или Model::factory('mail')->delete( array('id' => $mail_id));
            Model::factory('mail', $mail_id)->delete();
            return 1;
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "mailModel", "deleteMail", $user_id);
            throw new Exception ($e->getMessage(), $e->getCode());
        }  
    }
    
    /**
    * Возвращает все входящую почту
    * @param bigint $user_id    номер игрока из соц сети
    * result array
    */
    public function getUserMailIn($user_id){
        try{

            if(0){
                if(!Model::factory('user', $user_id)->exist()){
                    errors::exc(errors::errorIncorrectInput, "user id not exist");
                }
            }
   
            $listMailIn = $this->getList(array('user_id_in' => $user_id));
            
            $count_listMailIn = count($listMailIn);
            $messages_in_max = Model::factory ( 'var' )->loadByKey ( 'messages_in_max' )->value;
            
            $aMailIn = array();
            foreach($listMailIn as $mail){
                
                if($count_listMailIn > $messages_in_max){
                    $this->deleteMail($user_id, $mail["id"]);
                    $count_listMailIn--;
                }
                
                //$mail["title"] = iconv('utf-8','cp1251',$mail["title"]);
                //$mail["text"]  = iconv('utf-8','cp1251',$mail["text"]);

                $aMailIn[]     = $mail;
            }

            // return array("result" => 1, "mail_out" => $mailOut, "mail_in" => $mailIn);
            return array("result" => 1, "mail_in" => $aMailIn);   
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "mailModel", "getAllUserMail", $user_id);
            throw new Exception ($e->getMessage(), $e->getCode());
        }  
    }
    
    
    /**
    * Возвращает все входящую почту
    * @param bigint $user_id    номер игрока из соц сети
    * result array
    */
    public function getUserMailAll($user_id){
        try{

            if(0){
                if(!Model::factory('user', $user_id)->exist()){
                    errors::exc(errors::errorIncorrectInput, "user id not exist");
                }
            }
    
            $listMailIn  = $this->getList(array('user_id_in'  => $user_id));
            $listMailOut = $this->getList(array('user_id_out' => $user_id));

            $count_listMailIn = count($listMailIn);
            $count_listMailOut = count($listMailOut);
            
            $messages_in_max  = Model::factory ( 'var' )->loadByKey ( 'messages_in_max' )->value;
            $messages_out_max = Model::factory ( 'var' )->loadByKey ( 'messages_out_max' )->value;
            
            $aMailAll = array();

            foreach($listMailIn as $mail){
                
                if($count_listMailIn > $messages_in_max){
                    $this->deleteMail($user_id, $mail["id"]);
                    $count_listMailIn--;
                }
                
                //$mail["title"] = iconv('utf-8','cp1251',$mail["title"]);
                //$mail["text"]  = iconv('utf-8','cp1251',$mail["text"]);

                $aMail[]     = $mail;
            }
            
            foreach($listMailOut as $mail){
                
                if($count_listMailOut > $messages_out_max){
                    $this->deleteMail($user_id, $mail["id"]);
                    $count_listMailOut--;
                }
                
                //$mail["title"] = iconv('utf-8','cp1251',$mail["title"]);
                //$mail["text"]  = iconv('utf-8','cp1251',$mail["text"]);
 
                $aMail[]     = $mail;
            }

            // return array("result" => 1, "mail_out" => $mailOut, "mail_in" => $mailIn);
               return array("result" => 1, "mail" => $aMail);   
        } catch(Exception $e) {
            
            LOG_CRASH::add($e->getCode(), $e->getMessage(), "mailModel", "getAllUserMail", $user_id);
            throw new Exception ($e->getMessage(), $e->getCode());
        }  
    }  
}

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

<?php
/**
 * 
 */
class task_statModel extends Model {
    
    protected $_tableName = 'task_stat';
 
    public function addTask($playlist_id, $str_task_word){
        try{
            $listTask =  $this->getList(array("playlist_id" => $playlist_id, "question" => $str_task_word));
            if(0 == isset($listTask) || 0 == count($listTask)){
                $this->create(array("playlist_id" => $playlist_id, "question" => $str_task_word));
                $this->save();
                return 1; //добавлено
            } else {
                return 0; //не добавлено
            }
        //--------------------------------------------------------------------------
        return -1;
        } catch(Exception $e) {
            
        LOG_CRASH::add($e->getCode(), $e->getMessage(), "task_statModel", "addTask");
        throw new Exception ($e->getMessage(), $e->getCode());
        }       
    }
    
    public function deleteTaskById($task_id){
        try{
            
            $listTask =  Model::factory("task_stat")->getList(array("id" => $task_id), array("id"));
            if(0 == isset($listTask) || 0 == count($listTask)){
                return 0;
            } else {
                foreach($listTask as $task){
                    Model::factory("task_stat", $task["id"])->delete();    
                }
                
                //$this->delete(array("id" => $listTask[0]["id"]));
                //$this->save();
                return 1;
            }
        //--------------------------------------------------------------------------
        return -1;
        } catch(Exception $e) {
            
        LOG_CRASH::add($e->getCode(), $e->getMessage(), "task_statModel", "deleteTaskById");
        throw new Exception ($e->getMessage(), $e->getCode());
        }       
    }
    
    
     public function getListTask($playlist_id){
         try{
            return $this->getList(array("playlist_id" => $playlist_id));
            //return $this->getList(array("playlist_id" => $playlist_id), array("id", "text"));
         } catch(Exception $e) {
            
        LOG_CRASH::add($e->getCode(), $e->getMessage(), "task_statModel", "getListTask");
        throw new Exception ($e->getMessage(), $e->getCode());
        } 
     }
}

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

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

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

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

    //protected $_tableName = 'mail';
    
    
    /**
    * как 
    * @param bigint $user_id    номер игрока из соц сети
    * result array
    */
    public function get($user_id){
        try{

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

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

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

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

<?php
/**
 * Абстрактная модель
 *
 */
class Model {
    public static $saveOnDestruct = true;
    protected $_data = array ();
    protected $_dataUpdate = array ();
    protected $_tableName = '';
    protected $_idName = 'id';
    protected $_belongs_to = array ();
    protected static $_store = array ();
    
    /**
     * @param string $name
     * @param int $id
     * @param boolean $forceNew
     * @return Model
     */
    public static function factory($name, $id = NULL, $forceNew = false, $needAfterConstruct = true) {
        $name .= 'Model';
        if (is_null ( $id ) || $forceNew) {
            $new = new $name ( $id, $forceNew );
            $new->_after_construct ();
            return $new;
        } else {
            if (! isset ( self::$_store [$name] ))
                self::$_store [$name] = array ();
            if (! isset ( self::$_store [$name] [$id] )) {
                self::$_store [$name] [$id] = new $name ( $id );
                if ($needAfterConstruct)
                    self::$_store [$name] [$id]->_after_construct ();
            }
            return self::$_store [$name] [$id];
        }
    }
    
    /**
     * Выполняется один раз после загрузки
     */
    protected function _after_construct() {
    
    }
    
    /**
     * @param number $id
     */
    public function __construct($id = NULL, $forceNew = false) {
        if ($forceNew || ! $this->loadFromCache ( $id ))
            $this->loadFromDb ( $id );
    }
    
    public function __destruct() {
        if (self::$saveOnDestruct) {
            $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 );
        }
        $result = ( boolean ) $this->_data;
        if (! $result)
            $this->_data = array ();
        return $result;
    }
    
    /**
     * Загрузка данных в класс из базы
     */
    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->loadFromArray ( $result [0], true );
                $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, 43200 + mt_rand ( 0, 43200 ) );
        } else
            return false;
    }
    
    /**
    * !!!!!! убираем в первой проверке  
    * //if (count ( $this->_dataUpdate ) && isset ( $this->_data [$this->_idName] ) && $this->_data [$this->_idName]) {
    * условие: && $this->_data [$this->_idName].
    * оставляем:
    * 
    */

    public function save() {
       //if (count ( $this->_dataUpdate ) && isset ( $this->_data [$this->_idName] ) && $this->_data [$this->_idName]) {
       if (count ( $this->_dataUpdate ) && isset ( $this->_data [$this->_idName] )) {
            try {
                $result = ( boolean ) DBAccess::update ( $this->_tableName, $this->_dataUpdate, array ($this->_idName => $this->_data [$this->_idName] ) );
            } catch ( Exception $e ) {
                return false;
            }
            if ($result) {
                foreach ( $this->_dataUpdate as $key => $value ) {
                    $this->_data [$key] = $value;
                }
                $this->saveToCache ();
                $this->resetCacheListTag ();
                $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;
    }
    
    protected function _prepareListOutput($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'] ))
