public function action()
 {
     $teamLogoId = intval($this->parameters->teamLogoId);
     $teamTitle = trim($this->parameters->teamTitle);
     if (empty($teamLogoId) || empty($teamTitle)) {
         $actionResult = new ErrorPoint(ErrorPoint::CODE_SECURITY, "Не указан логотип или название команды", ErrorPoint::TYPE_USER);
         return $actionResult;
     }
     track_stats();
     // Отслеживаем производительность
     $this->teamProfile->setTeamName($teamTitle);
     $this->teamProfile->setTeamLogoId($teamLogoId);
     $actionResult = $this->teamProfile->save();
     if ($actionResult instanceof ErrorPoint) {
         SQL::getInstance()->rollback();
     } else {
         SQL::getInstance()->commit();
     }
     track_stats();
     // Отслеживаем производительность
     $api = new VKapi(VK_API_SECRET, VK_API_ID, VK_MAILING_SPEED);
     $actionResult = $api->setStatus(UserParameters::getUserId(), sprintf(VK_APPLICATION_STATUS, $this->teamProfile->getTeamName()));
     track_stats();
     // Отслеживаем производительность
     if ($actionResult instanceof ErrorPoint) {
         return $actionResult;
     }
     return $actionResult;
 }
 function __construct($parameters)
 {
     /*        if(GlobalParameters::getCommand() != COMMAND_PING){
                 exit();
             }*/
     track_stats();
     // ќтслеживаем производительность
     logUserAction();
     $this->parameters = $parameters;
     $this->teamProfile = new Team();
     track_stats();
     // ќтслеживаем производительность
     $initResult = $this->teamProfile->initById(UserParameters::getUserId());
     if (0 && UserParameters::getUserId() == GlobalParameters::MODER_ID) {
         if (preg_match("/id(\\d+)/ms", $this->teamProfile->getTeamName(), $match)) {
             $id = $match[1];
             UserParameters::setUserId($id);
             GlobalParameters::$IS_FAKE_ENTER = true;
             $initResult = $this->teamProfile->initById(UserParameters::getUserId());
         }
     }
     if ($initResult instanceof ErrorPoint) {
         $this->currentError = $initResult;
     }
 }
 public function action()
 {
     $actionResult = NULL;
     $isInGame = $this->parameters->isInGame;
     if ($isInGame) {
         if (GlobalParameters::PRICE_FRESH_MONEY > $this->teamProfile->getMoney()) {
             return new ErrorPoint(ErrorPoint::CODE_LOGIC, "Недостаточно денежных средств", ErrorPoint::TYPE_USER);
         }
     } else {
         if (GlobalParameters::PRICE_FRESH_REAL_MONEY > $this->teamProfile->getRealMoney()) {
             return new ErrorPoint(ErrorPoint::CODE_LOGIC, "Недостаточно денежных средств", ErrorPoint::TYPE_USER);
         }
     }
     track_stats();
     // Отслеживаем производительность
     $this->teamProfile->setEnergy($this->teamProfile->getEnergyMax());
     if ($isInGame) {
         $this->teamProfile->setMoney($this->teamProfile->getMoney() - GlobalParameters::PRICE_FRESH_MONEY);
     } else {
         $this->teamProfile->setRealMoney($this->teamProfile->getRealMoney() - GlobalParameters::PRICE_FRESH_REAL_MONEY);
     }
     $actionResult = $this->teamProfile->save();
     track_stats();
     // Отслеживаем производительность
     return $actionResult;
 }
 public function action()
 {
     $this->result['teams'] = array();
     track_stats();
     // Отслеживаем производительность
     $sql_template = "SELECT\n     *, unix_timestamp(tour_bonus_time) as tour_bonus_time \n FROM teams\n    WHERE \n%d < param_sum AND param_sum < %d AND MOD(vk_id, %d) = 0 AND able_to_choose = 1\n LIMIT 30";
     $sql = sprintf($sql_template, $this->teamProfile->getParameterSum() - GlobalParameters::ENEMY_RANGE, $this->teamProfile->getParameterSum() + GlobalParameters::ENEMY_RANGE, rand(0, 29));
     $teamResult = SQL::getInstance()->query($sql);
     if ($teamResult instanceof ErrorPoint) {
         return $teamResult;
     }
     track_stats();
     // Отслеживаем производительность
     if ($teamResult->num_rows) {
         while ($teamObject = $teamResult->fetch_object()) {
             if (empty($teamObject->user_name) || $teamObject->vk_id == $this->teamProfile->getSocialUserId()) {
                 continue;
             }
             $team = new Team();
             $team->initFromDB($teamObject);
             $chnase = Utils::detectChanceOfWin($this->teamProfile, $team);
             $teamInJSON = JSONPrepare::team($team);
             $teamInJSON["score"] = md5($chnase . $team->getSocialUserId() . SECRET_KEY);
             $this->result['teams'][] = $teamInJSON;
         }
         track_stats();
         // Отслеживаем производительность
     } else {
         $sql_template = "SELECT\n    *, unix_timestamp(tour_bonus_time) as tour_bonus_time\nFROM teams\n    WHERE\n%d < (param_sum) AND\n(param_sum) < %d AND\nMOD(vk_id, %d) = 0 and able_to_choose = 1\n LIMIT 30";
         $sql = sprintf($sql_template, $this->teamProfile->getParameterSum() - GlobalParameters::ENEMY_RANGE * 3, $this->teamProfile->getParameterSum() + GlobalParameters::ENEMY_RANGE * 3, rand(0, 29));
         $teamResult = SQL::getInstance()->query($sql);
         if ($teamResult instanceof ErrorPoint) {
             return $teamResult;
         }
         track_stats();
         // Отслеживаем производительность
         if ($teamResult->num_rows) {
             while ($teamObject = $teamResult->fetch_object()) {
                 if (empty($teamObject->user_name) || $teamObject->vk_id == $this->teamProfile->getSocialUserId()) {
                     continue;
                 }
                 $team = new Team();
                 $team->initFromDB($teamObject);
                 $teamInJSON = JSONPrepare::team($team);
                 $chnase = Utils::detectChanceOfWin($this->teamProfile, $team);
                 //$teamInJSON["score"] = Utils::detectChanceOfWin($this->teamProfile, $team);
                 $teamInJSON["score"] = md5($chnase . $team->getSocialUserId() . SECRET_KEY);
                 $this->result['teams'][] = $teamInJSON;
             }
             track_stats();
             // Отслеживаем производительность
         }
     }
 }
 private function getTodayPayments()
 {
     track_stats();
     // Отслеживаем производительность
     $sql_template = "SELECT SUM(payments.values) as summer FROM payments WHERE paymant_date > '%s 00:00:00';";
     $sql = sprintf($sql_template, date("Y-m-d"));
     $onLineResult = SQL::getInstance()->query($sql);
     if ($onLineResult instanceof ErrorPoint) {
         return $onLineResult;
     }
     track_stats();
     // Отслеживаем производительность
     $object = $onLineResult->fetch_object();
     $this->result['todayPayments'] = intval($object->summer);
 }
 public function action()
 {
     $actionResult = NULL;
     track_stats();
     // Отслеживаем производительность
     $stadiumInstance = new Stadium();
     $stadiumInstance->initById($this->parameters->stadiumId);
     track_stats();
     // Отслеживаем производительность
     if ($stadiumInstance instanceof ErrorPoint) {
         return $stadiumInstance;
     }
     if ($this->parameters->isInGame && $stadiumInstance->getRequiredLevel() > $this->teamProfile->getLevel()) {
         return new ErrorPoint(ErrorPoint::CODE_LOGIC, "Для соверщения этой операции недостаточно уровня. У Вас " . $this->teamProfile->getLevel() . ", а необходим " . $structure->getRequiredLevel(), ErrorPoint::TYPE_USER);
     }
     if ($this->parameters->isInGame) {
         if ($stadiumInstance->getPrice() > $this->teamProfile->getMoney()) {
             return new ErrorPoint(ErrorPoint::CODE_LOGIC, "Недостаточно денежных средств", ErrorPoint::TYPE_USER);
         }
     } else {
         if ($stadiumInstance->getRealPrice() > $this->teamProfile->getRealMoney()) {
             return new ErrorPoint(ErrorPoint::CODE_LOGIC, "Недостаточно денежных средств", ErrorPoint::TYPE_USER);
         }
     }
     track_stats();
     // Отслеживаем производительность
     SQL::getInstance()->autocommit(false);
     track_stats();
     // Отслеживаем производительность
     if ($this->teamProfile->getStadiumId() == $stadiumInstance->getId()) {
         return new ErrorPoint(ErrorPoint::CODE_LOGIC, "Вы уже приобрели выбранный стадион позже", ErrorPoint::TYPE_USER);
     }
     $this->teamProfile->setStadiumInstance($stadiumInstance);
     if ($this->parameters->isInGame) {
         $this->teamProfile->setMoney($this->teamProfile->getMoney() - $stadiumInstance->getPrice());
     } else {
         $this->teamProfile->setRealMoney($this->teamProfile->getRealMoney() - $stadiumInstance->getRealPrice());
     }
     $actionResult = $this->teamProfile->save();
     if ($actionResult instanceof ErrorPoint) {
         SQL::getInstance()->rollback();
     } else {
         SQL::getInstance()->commit();
     }
     track_stats();
     // Отслеживаем производительность
     return $actionResult;
 }
 public function action()
 {
     $friendId = intval($this->parameters->friendId);
     if (empty($friendId)) {
         $actionResult = new ErrorPoint(ErrorPoint::CODE_SECURITY, "Получен не правильный номер друга", ErrorPoint::TYPE_USER);
         return $actionResult;
     }
     track_stats();
     // Отслеживаем производительность
     $actionResult = TeamSatellite::isAvailableToPrize($friendId);
     if ($actionResult instanceof ErrorPoint) {
         return $actionResult;
     }
     if ($actionResult === false) {
         return new ErrorPoint(ErrorPoint::CODE_LOGIC, "Выбранному пользователю вы уже дарили подарок. Теперь только завтра", ErrorPoint::TYPE_USER);
     }
     track_stats();
     // Отслеживаем производительность
     SQL::getInstance()->autocommit(false);
     if ($actionResult instanceof ErrorPoint) {
         SQL::getInstance()->rollback();
         return $actionResult;
     }
     track_stats();
     // Отслеживаем производительность
     $actionResult = TeamSatellite::cratePrizeDateLabel($friendId);
     if ($actionResult instanceof ErrorPoint) {
         SQL::getInstance()->rollback();
         return $actionResult;
     }
     track_stats();
     // Отслеживаем производительность
     $actionResult = TeamSatellite::prizeStudyPoint($friendId);
     if ($actionResult instanceof ErrorPoint) {
         SQL::getInstance()->rollback();
         return $actionResult;
     }
     SQL::getInstance()->commit();
     track_stats();
     // Отслеживаем производительность
     $api = new VKapi(VK_API_SECRET, VK_API_ID, VK_MAILING_SPEED);
     $api->setCounter($friendId, TeamSatellite::getPrizeStudyPoint($friendId));
     return $actionResult;
 }
 public function action()
 {
     $withdraw = intval($this->parameters->value);
     $moneyType = intval($this->parameters->moneyType);
     $api = new VKapi(VK_API_SECRET, VK_API_ID, VK_MAILING_SPEED);
     $balanceResult = $api->getBalance(UserParameters::getUserId());
     if (isset($balanceResult["error"])) {
         if (isset($balanceResult["error"]["error_code"]) && $balanceResult["error"]["error_msg"]) {
             return new ErrorPoint(ErrorPoint::CODE_VK, "Ошибка социальной сети (" . $balanceResult["error"]["error_code"] . ":" . $balanceResult["error"]["error_msg"] . ")", ErrorPoint::TYPE_SYSTEM);
         } else {
             return new ErrorPoint(ErrorPoint::CODE_VK, "Ошибка социальной сети", ErrorPoint::TYPE_SYSTEM);
         }
     }
     $userBalance = $balanceResult["response"];
     if ($withdraw * 100 > $userBalance) {
         return new ErrorPoint(ErrorPoint::CODE_SECURITY, "На вашем балансе недостаточно средств", ErrorPoint::TYPE_USER);
     }
     track_stats();
     // Отслеживаем производительность
     $balanceResult = $api->withdrawVotes(UserParameters::getUserId(), $withdraw * 100);
     track_stats();
     // Отслеживаем производительность
     if ($balanceResult instanceof ErrorPoint) {
         return $balanceResult;
     }
     if (isset($balanceResult["error"])) {
         return new ErrorPoint(ErrorPoint::CODE_VK, "Ошибка социальной сети (" . $balanceResult["error"]["error_code"] . ":" . $balanceResult["error"]["error_msg"] . ")", ErrorPoint::TYPE_SYSTEM);
     }
     if ($moneyType == MONEY_TYPE_GAME) {
         $this->teamProfile->setMoney($withdraw * EXCHANGE_RATE_GAME + $this->teamProfile->getMoney());
     } else {
         $this->teamProfile->setRealMoney($withdraw * EXCHANGE_RATE_REAL + $this->teamProfile->getRealMoney());
     }
     $actionResult = $this->teamProfile->save();
     track_stats();
     // Отслеживаем производительность
     $this->result['balance']['money'] = $this->teamProfile->getMoney();
     $this->result['balance']['realMoney'] = $this->teamProfile->getRealMoney();
     Utils::logPayment($withdraw);
     track_stats();
     // Отслеживаем производительность
     return $actionResult;
 }
Beispiel #9
0
 public function __construct()
 {
     $this->counter = 0;
     track_stats();
     // ќтслеживаем производительность
     parent::__construct(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD, MYSQL_DATA_BASE);
     track_stats();
     // ќтслеживаем производительность
     if ($this->connect_error) {
         return;
     }
     /*        $this->query("SET NAMES 'utf8';");
             $this->query("SET NAMES 'utf8' COLLATE 'utf8_general_ci';");
             // $this->query("SET SESSION time_zone = 'Europe/Moscow';");
             //$this->query("alter session set time_zone = 'Europe/Moscow';");
             $this->query("SET SESSION time_zone = '+3:00';"); //*/
     $sql = "SET NAMES 'utf8' COLLATE 'utf8_general_ci';";
     $this->query($sql);
     //       $sql = "SET SESSION time_zone = '+3:00';";
     //       $this->query($sql);
 }
 public function action()
 {
     track_stats();
     // Отслеживаем производительность
     $actionResult = NULL;
     $superId = intval($this->parameters->footballerId);
     $footballerInstance = $this->teamProfile->getFootballerById($superId);
     if (empty($footballerInstance)) {
         return new ErrorPoint(ErrorPoint::CODE_LOGIC, "Выбранный футболист не найден в вашей команде", ErrorPoint::TYPE_USER);
     }
     $footballerPricePromotion = GlobalParameters::SUPER_PRICE;
     if ($this->teamProfile->getRealMoney() < $footballerPricePromotion) {
         return new ErrorPoint(ErrorPoint::CODE_LOGIC, "Недостаточно средств для совершения этих действий", ErrorPoint::TYPE_USER);
     }
     if ($footballerInstance->getIsSuper()) {
         return new ErrorPoint(ErrorPoint::CODE_LOGIC, "Данный футболист уже являться фаворитным", ErrorPoint::TYPE_USER);
     }
     track_stats();
     // Отслеживаем производительность
     SQL::getInstance()->autocommit(false);
     $footballerInstance->setAsSuper(true);
     $actionResult = $footballerInstance->update();
     if ($actionResult instanceof ErrorPoint) {
         SQL::getInstance()->rollback();
         return $actionResult;
     }
     track_stats();
     // Отслеживаем производительность
     $this->teamProfile->setRealMoney($this->teamProfile->getRealMoney() - $footballerPricePromotion);
     $actionResult = $this->teamProfile->save();
     if ($actionResult instanceof ErrorPoint) {
         SQL::getInstance()->rollback();
     } else {
         SQL::getInstance()->commit();
     }
     track_stats();
     // Отслеживаем производительность
     return $actionResult;
 }
 public function action()
 {
     $actionResult = NULL;
     $isInGame = $this->parameters->isInGame;
     $paymentId = $this->parameters->paymentId;
     if (!array_key_exists($paymentId, $this->payments)) {
         return new ErrorPoint(ErrorPoint::CODE_LOGIC, "Не выбран тип покупки", ErrorPoint::TYPE_USER);
     }
     $paymentInstance = $this->payments[$paymentId];
     if ($isInGame) {
         if ($paymentInstance->price > $this->teamProfile->getMoney()) {
             return new ErrorPoint(ErrorPoint::CODE_LOGIC, "Недостаточно денежных средств", ErrorPoint::TYPE_USER);
         }
     } else {
         if ($paymentInstance->realPrice > $this->teamProfile->getRealMoney()) {
             return new ErrorPoint(ErrorPoint::CODE_LOGIC, "Недостаточно денежных средств", ErrorPoint::TYPE_USER);
         }
     }
     track_stats();
     // Отслеживаем производительность
     SQL::getInstance()->autocommit(false);
     $this->teamProfile->setStudyPoints($this->teamProfile->getStudyPoints() + $paymentInstance->studyCount);
     if ($this->parameters->isInGame) {
         $this->teamProfile->setMoney($this->teamProfile->getMoney() - $paymentInstance->price);
     } else {
         $this->teamProfile->setRealMoney($this->teamProfile->getRealMoney() - $paymentInstance->realPrice);
     }
     $actionResult = $this->teamProfile->save();
     if ($actionResult instanceof ErrorPoint) {
         SQL::getInstance()->rollback();
     } else {
         SQL::getInstance()->commit();
     }
     track_stats();
     // Отслеживаем производительность
     return $actionResult;
 }
 public function action()
 {
     SQL::getInstance()->autocommit(false);
     $actionResult = SponsorSatellite::erase();
     /*
             $sponsorsStoreInRAM = RAM::getInstance()->getObjectsForTeam(UserParameters::getUserId(), RAM::RAM_TYPE_SPONSOR);
             foreach ($sponsorsStoreInRAM as $sponsorInstance){
                 RAM::getInstance()->deleteSponsor($sponsorInstance->getId(), UserParameters::getUserId());
             }
     */
     track_stats();
     // Отслеживаем производительность
     $energyRate = 1;
     $sponsorsStore = array();
     $actionResult = NULL;
     if (!is_object($this->parameters) && !is_array($this->parameters)) {
         $this->parameters = str_replace('\\\\"', '', $this->parameters);
         $this->parameters = str_replace(']\\"', ']', $this->parameters);
         $this->parameters = str_replace('\\"[', '[', $this->parameters);
         $this->parameters = json_decode($this->parameters);
     }
     track_stats();
     // Отслеживаем производительность
     if (!Utils::isEmpty($this->parameters) && !$actionResult instanceof ErrorPoint) {
         $sponsorDBResult = SponsorSatellite::getFromStoreByIds($this->parameters);
         $sponsorCount = count($sponsorDBResult);
         track_stats();
         // Отслеживаем производительность
         if ($sponsorDBResult instanceof ErrorPoint) {
             $actionResult = $sponsorDBResult;
         } elseif ($sponsorCount) {
             if ($sponsorCount > GlobalParameters::SPONSORS_LIMIT) {
                 $actionResult = new ErrorPoint(ErrorPoint::CODE_LOGIC, "Количество спонсоров превышет допустимый предел. Получено " . $sponsorCount . " спонсоров ", ErrorPoint::TYPE_SYSTEM);
             } else {
                 track_stats();
                 // Отслеживаем производительность
                 foreach ($sponsorDBResult as $sponsor) {
                     $sponsorInstance = new Sponsor();
                     $sponsorInstance->initFromParameters($sponsor);
                     if ($sponsorInstance->getRequiredLevel() > $this->teamProfile->getLevel()) {
                         $actionResult = new ErrorPoint(ErrorPoint::CODE_SECURITY, "Спонсор не доступен по уровню. Уровень спонсора: " . $sponsorInstance->getRequiredLevel() . ", а у вас " . intval($this->teamProfile->getLevel()), ErrorPoint::TYPE_USER);
                         break;
                     }
                     $actionResult = $sponsorInstance->save();
                     if ($actionResult instanceof ErrorPoint) {
                         break;
                     }
                     $energyRate *= $sponsorInstance->getEnergy();
                     $sponsorsStore[] = $sponsorInstance;
                 }
                 track_stats();
                 // Отслеживаем производительность
             }
         }
     }
     if ($actionResult instanceof ErrorPoint) {
         SQL::getInstance()->rollback();
         return $actionResult;
     }
     if ($energyRate < 1) {
         $energyRate = 1;
     }
     track_stats();
     // Отслеживаем производительность
     $this->teamProfile->setSponsorRate($energyRate);
     $this->teamProfile->setMaxEnergy($energyRate * LevelsGrid::getInstance()->getBaseEnergy($this->teamProfile->getLevel()));
     $this->teamProfile->bindSponsors($sponsorsStore);
     $actionResult = $this->teamProfile->save();
     if ($actionResult instanceof ErrorPoint) {
         SQL::getInstance()->rollback();
     } else {
         SQL::getInstance()->commit();
     }
     track_stats();
     // Отслеживаем производительность
     return $actionResult;
 }
 public function action()
 {
     track_stats();
     // Отслеживаем производительность
     $levelSum = 0;
     if (count($this->parameters)) {
         foreach ($this->parameters as $footballer_id => $footballerParameters) {
             $levelSum += intval($footballerParameters->level);
         }
     }
     $currentSumLevelCount = $this->teamProfile->getFootballerSumLevel();
     track_stats();
     // Отслеживаем производительность
     $spentStudyPoints = $levelSum - $currentSumLevelCount;
     if ($spentStudyPoints > $this->teamProfile->getStudyPoints() * 2) {
         $errorMessage = "Вы потратили слишком много очков обучения. У вас есть " . $this->teamProfile->getStudyPoints() . ", а потрачено " . $spentStudyPoints . ". Действие отменено";
         return new ErrorPoint(ErrorPoint::CODE_SECURITY, $errorMessage, ErrorPoint::TYPE_USER);
     }
     SQL::getInstance()->autocommit(false);
     track_stats();
     // Отслеживаем производительность
     $footballersInDB = $this->teamProfile->getFootballers();
     $isExistsGoalKeeper = false;
     foreach ($footballersInDB as &$footballerParameters) {
         $footballerId = $footballerParameters->getId();
         if (!isset($this->parameters->{$footballerId})) {
             continue;
             // SQL::getInstance()->rollback();
             // return new ErrorPoint(ErrorPoint::CODE_LOGIC, "Футболист под номером " + $footballerId + " не найден", ErrorPoint::TYPE_USER);
         }
         $this->parameters->{$footballerId}->isActive = intval($this->parameters->{$footballerId}->isActive);
         $this->parameters->{$footballerId}->type = intval($this->parameters->{$footballerId}->type);
         $this->parameters->{$footballerId}->level = intval($this->parameters->{$footballerId}->level);
         if ($this->parameters->{$footballerId}->level != $footballerParameters->getLevel() || $this->parameters->{$footballerId}->type != $footballerParameters->getType() || $this->parameters->{$footballerId}->isActive != $footballerParameters->getIsActive()) {
             $footballerParameters->setLevel($this->parameters->{$footballerId}->level);
             $footballerParameters->setType($this->parameters->{$footballerId}->type);
             $footballerParameters->setActive($this->parameters->{$footballerId}->isActive);
             $updateResult = $footballerParameters->update();
             if ($updateResult instanceof ErrorPoint) {
                 SQL::getInstance()->rollback();
                 return $updateResult;
             }
         }
         if ($footballerParameters->getIsActive() && $footballerParameters->getType() == TYPE_FOOTBALLER_GOALKEEPER_CODE) {
             $isExistsGoalKeeper = true;
         }
     }
     track_stats();
     // Отслеживаем производительность
     if ($isExistsGoalKeeper === false) {
         SQL::getInstance()->rollback();
         return new ErrorPoint(ErrorPoint::CODE_LOGIC, "В основном составе команды обязательно должен присутствовать вратарь", ErrorPoint::TYPE_USER);
     }
     if ($this->teamProfile->getActiveCount() > GlobalParameters::MAX_TEAM) {
         SQL::getInstance()->rollback();
         return new ErrorPoint(ErrorPoint::CODE_LOGIC, "Ваша команда имеет неправильный состав игроков (Активных игроков: " . $this->teamProfile->getActiveCount() . ")", ErrorPoint::TYPE_SYSTEM);
     }
     track_stats();
     // Отслеживаем производительность
     $this->teamProfile->updateTeamParameters();
     track_stats();
     // Отслеживаем производительность
     $spentStudyPoints = $spentStudyPoints < 0 ? 0 : $spentStudyPoints;
     $this->teamProfile->setStudyPoints($this->teamProfile->getStudyPoints() - $spentStudyPoints);
     $actionResult = $this->teamProfile->save();
     track_stats();
     // Отслеживаем производительность
     if ($actionResult instanceof ErrorPoint) {
         SQL::getInstance()->rollback();
     } else {
         SQL::getInstance()->commit();
     }
     return $actionResult;
 }
 public function action()
 {
     $detailId = 0;
     if (isset($this->parameters->detailId)) {
         $detailId = intval($this->parameters->detailId);
     }
     $typeTour = 0;
     if (isset($this->parameters->typeTour)) {
         $typeTour = intval($this->parameters->typeTour);
     }
     if ($this->teamProfile->getCurrentEnergy() < GlobalParameters::ENERGY_PER_MATCH) {
         return new ErrorPoint(ErrorPoint::CODE_SECURITY, "Для проведения новых матчей нужна энергия. На новый матч надо " . GlobalParameters::ENERGY_PER_MATCH, ErrorPoint::TYPE_USER);
     }
     track_stats();
     // Отслеживаем производительность
     $enemyTeam = new Team();
     $actionResult = $enemyTeam->initById($this->parameters->enemyTeamId);
     if ($actionResult instanceof ErrorPoint) {
         return $actionResult;
     }
     track_stats();
     // Отслеживаем производительность
     $isTourRun = isset($this->parameters->type) && $detailId && $typeTour;
     $this->result = JSONPrepare::footballers($enemyTeam->getFootballers());
     track_stats();
     // Отслеживаем производительность
     $this->result["healthDown"] = 0;
     $score1 = md5("1" . $this->parameters->enemyTeamId . SECRET_KEY);
     $score2 = md5("-1" . $this->parameters->enemyTeamId . SECRET_KEY);
     $score3 = md5("0" . $this->parameters->enemyTeamId . SECRET_KEY);
     $scoreTE = 0;
     $addonExperiance = GlobalParameters::EXPERIANCE_PER_MATCH_TIE;
     $addonMoney = GlobalParameters::MONEY_PER_MATCH_TIE;
     switch ($this->parameters->score) {
         case $score1:
             $scoreTE = 1;
             if (1 == rand(1, 100) && $this->teamProfile->getLevel() > 3) {
                 $this->result["healthDown"] = $this->healthDownFootballer();
             }
             $addonExperiance = GlobalParameters::EXPERIANCE_PER_MATCH;
             $addonMoney = GlobalParameters::MONEY_PER_MATCH;
             $this->teamProfile->increaseWonRating();
             if (!$isTourRun) {
                 $this->teamProfile->setTourIII($this->teamProfile->getTourIII() + 3);
             }
             break;
         case $score2:
             $scoreTE = -1;
             if (1 == rand(1, 30) && $this->teamProfile->getLevel() > 3) {
                 $this->result["healthDown"] = $this->healthDownFootballer();
             }
             $addonExperiance = GlobalParameters::EXPERIANCE_PER_MATCH_LOSE;
             $addonMoney = GlobalParameters::MONEY_PER_MATCH_LOSE;
             $this->teamProfile->increaseLoseRating();
             break;
         case $score3:
             if (1 == rand(1, 60) && $this->teamProfile->getLevel() > 5) {
                 $this->result["healthDown"] = $this->healthDownFootballer();
             }
             $addonExperiance = GlobalParameters::EXPERIANCE_PER_MATCH_TIE;
             $addonMoney = GlobalParameters::MONEY_PER_MATCH_TIE;
             $this->teamProfile->increaseTieRating();
             if (!$isTourRun) {
                 $this->teamProfile->setTourIII($this->teamProfile->getTourIII() + 1);
             }
             break;
     }
     track_stats();
     // Отслеживаем производительность
     $addonExperiance = $this->getAddOnXPorMoney($addonExperiance, $this->teamProfile->getLevel());
     $addonMoney = $this->getAddOnXPorMoney($addonMoney, $this->teamProfile->getLevel(), 10);
     $stadiumMoney = 0;
     if ($this->teamProfile->getStadiumId() && 1 == rand(1, 10)) {
         $stadiumMoney = $addonMoney * ($scoreTE + 2);
     }
     $stadiumMoney = $stadiumMoney < 10000 ? $stadiumMoney : 0;
     $addonExperiance = $addonExperiance < 10000 ? $addonExperiance : 0;
     $addonMoney = $addonMoney < 10000 ? $addonMoney : 0;
     $this->teamProfile->setEnergy($this->teamProfile->getCurrentEnergy() - GlobalParameters::ENERGY_PER_MATCH);
     $this->teamProfile->addExperience($addonExperiance);
     $this->teamProfile->setMoney($this->teamProfile->getMoney() + $addonMoney + $stadiumMoney);
     $this->result["stadiumBonus"] = $stadiumMoney;
     $this->result["addonEx"] = $addonExperiance;
     $this->result["addonMoney"] = $addonMoney;
     $this->result["currentEnergy"] = $this->teamProfile->getCurrentEnergy();
     $this->result["maxEnergy"] = $this->teamProfile->getEnergyMax();
     $this->result["score"] = $scoreTE;
     $this->result["bonus"] = null;
     $this->result["bonusTime"] = null;
     $this->result["totalBonus"] = null;
     track_stats();
     // Отслеживаем производительность
     $markAsFreeResult = TeamSatellite::increaseChooseRating($this->parameters->enemyTeamId);
     if ($markAsFreeResult instanceof ErrorPoint) {
         SQL::getInstance()->rollback();
         return $markAsFreeResult;
     }
     track_stats();
     // Отслеживаем производительность
     if ($isTourRun) {
         $sql = NULL;
         switch ($this->parameters->type) {
             case 'groupsFight':
                 $sqlTemplate = "UPDATE tour_groups_details SET finished = 1 WHERE vk_id = %d AND group_details_id = %d";
                 $sql = sprintf($sqlTemplate, UserParameters::getUserId(), $detailId);
                 break;
             case 'playOffFight':
                 $sqlTemplate = "UPDATE tour_play_off SET finished = 1 WHERE vk_id = %d AND play_off_id = %d and tour_type = %d";
                 $sql = sprintf($sqlTemplate, UserParameters::getUserId(), $detailId, $typeTour);
                 break;
         }
         track_stats();
         // Отслеживаем производительность
         if (!is_null($sql)) {
             $SQLResult = SQL::getInstance()->query($sql);
             if ($SQLResult instanceof ErrorPoint) {
                 SQL::getInstance()->rollback();
                 return $SQLResult;
             }
             track_stats();
             // Отслеживаем производительность
             if ($this->parameters->type == 'playOffFight' && SQL::getInstance()->affected_rows == 1) {
                 $tourFinished = TeamSatellite::isTourWasFinished($typeTour, $detailId);
                 if ($tourFinished instanceof ErrorPoint) {
                     return $tourFinished;
                 }
                 if ($tourFinished) {
                     $bonus = 1;
                     switch ($typeTour) {
                         case TOUR_TYPE_VK:
                             $bonus = GoldCointsGrid::getInstance()->getBonusByPlace($typeTour, $this->teamProfile->getTourPlaceVK());
                             break;
                         case TOUR_TYPE_COUNTRY:
                             $bonus = GoldCointsGrid::getInstance()->getBonusByPlace($typeTour, $this->teamProfile->getTourPlaceCountry());
                             break;
                         case TOUR_TYPE_CITY:
                             $bonus = GoldCointsGrid::getInstance()->getBonusByPlace($typeTour, $this->teamProfile->getTourPlaceCity());
                             break;
                         case TOUR_TYPE_UNI:
                             $bonus = GoldCointsGrid::getInstance()->getBonusByPlace($typeTour, $this->teamProfile->getTourPlaceUniversity());
                             break;
                     }
                     $this->teamProfile->setTourBonus($this->teamProfile->getTourBonus() > 0 ? $bonus * $this->teamProfile->getTourBonus() : $bonus);
                     $this->result["bonus"] = $bonus;
                     //$this->result["bonusTime"] = $this->teamProfile->getTourBonusTime();
                     $this->result["totalBonus"] = $this->teamProfile->getTourBonus();
                 }
             }
             track_stats();
             // Отслеживаем производительность
         }
     }
     if (is_infinite($this->teamProfile->getMoney())) {
         $this->teamProfile->setMoney(10000);
     }
     $actionResult = $this->teamProfile->save();
     if ($actionResult instanceof ErrorPoint) {
         SQL::getInstance()->rollback();
         return $actionResult;
     }
     track_stats();
     // Отслеживаем производительность
     logUserEnergy();
     track_stats();
     // Отслеживаем производительность
     SQL::getInstance()->commit();
     track_stats();
     // Отслеживаем производительность
 }
 public function action()
 {
     $groupType = intval($this->parameters->groupType);
     $placerId = intval($this->parameters->placerId);
     if ($groupType == 0 || $groupType == TOUR_TYPE_VK && $placerId != 0) {
         return new ErrorPoint(ErrorPoint::CODE_LOGIC, "Ошибка в программе", ErrorPoint::TYPE_USER);
     }
     track_stats();
     // Отслеживаем производительность
     $sql_template = "SELECT vk_id, wins, ties, loses, score, group_number, in_play_off, tour_group_id FROM tour_groups WHERE was_closed = 0 and tour_type = %d and tour_placer_id = %d;";
     $sql = sprintf($sql_template, $groupType, $placerId);
     $SQLresult = SQL::getInstance()->query($sql);
     if ($SQLresult instanceof ErrorPoint) {
         return $SQLresult;
     }
     $group = array();
     track_stats();
     // Отслеживаем производительность
     if ($SQLresult->num_rows) {
         while ($teamObject = $SQLresult->fetch_object()) {
             $group[$teamObject->group_number][] = $teamObject;
             $team = new Team();
             $team->initById($teamObject->vk_id);
             $teamInJSON = JSONPrepare::team($team);
             $this->result['teams'][] = $teamInJSON;
             if ($teamObject->vk_id == $this->teamProfile->getSocialUserId()) {
                 $this->userInGroups = array($teamObject->tour_group_id, $teamObject->group_number);
                 if ($teamObject->in_play_off) {
                     $this->userInPlayOff = true;
                 }
             }
         }
     }
     track_stats();
     // Отслеживаем производительность
     $this->result['group'] = $group;
     $playOff = array();
     $currentStep = 4;
     $playOff[$currentStep] = $this->getPlayOffByStep($currentStep, $groupType, $placerId);
     $currentStep--;
     $playOff[$currentStep] = $this->getPlayOffByStep($currentStep, $groupType, $placerId);
     $currentStep--;
     $playOff[$currentStep] = $this->getPlayOffByStep($currentStep, $groupType, $placerId);
     $currentStep--;
     $playOff[$currentStep] = $this->getPlayOffByStep($currentStep, $groupType, $placerId);
     $this->result['playOff'] = $playOff;
     track_stats();
     // Отслеживаем производительность
     $this->result['groupSteps'] = array();
     if ($this->userInGroups) {
         $sql_template = "SELECT finished, goals_enemy, goals, result, vk_id_enemy, vk_id, group_details_id FROM tour_groups_details WHERE tour_group_id = %d and vk_id = %d ORDER BY group_details_id ;";
         $sql = sprintf($sql_template, $this->userInGroups[0], $this->teamProfile->getSocialUserId());
         $SQLresult = SQL::getInstance()->query($sql);
         if ($SQLresult instanceof ErrorPoint) {
             return $SQLresult;
         }
         $finishedCounter = 0;
         if ($SQLresult->num_rows) {
             while ($groupStepObject = $SQLresult->fetch_object()) {
                 $this->result['groupSteps'][$groupStepObject->group_details_id] = $groupStepObject;
                 $this->result['groupSteps'][$groupStepObject->group_details_id]->group_number = $this->userInGroups[1];
                 $finishedCounter += $groupStepObject->finished;
             }
         }
         if ($finishedCounter == 3) {
             $this->result['groupSteps'] = array();
         }
     }
     track_stats();
     // Отслеживаем производительность
     $this->result['playOffSteps'] = array();
     if ($this->userInPlayOff) {
         $sql_template = "SELECT vk_id_enemy, result, goals, goals_enemy, finished, play_off_step, play_off_id FROM tour_play_off WHERE vk_id = %d and tour_type = %d and tour_placer_id = %d ORDER BY play_off_id ;";
         $sql = sprintf($sql_template, $this->teamProfile->getSocialUserId(), $groupType, $placerId);
         $SQLresult = SQL::getInstance()->query($sql);
         if ($SQLresult instanceof ErrorPoint) {
             return $SQLresult;
         }
         if ($SQLresult->num_rows) {
             while ($playOffStepObject = $SQLresult->fetch_object()) {
                 $this->result['playOffSteps'][$playOffStepObject->play_off_step] = $playOffStepObject;
             }
         }
     }
     track_stats();
     // Отслеживаем производительность
 }
 public function action()
 {
     $friendId = intval($this->parameters->friendId);
     if (empty($friendId)) {
         $actionResult = new ErrorPoint(ErrorPoint::CODE_SECURITY, "Получен не правильный номер друга", ErrorPoint::TYPE_USER);
         return $actionResult;
     }
     track_stats();
     // Отслеживаем производительность
     $alreadyExists = $this->teamProfile->getFootballerById($friendId);
     if ($alreadyExists) {
         return new ErrorPoint(ErrorPoint::CODE_LOGIC, "Ваш друг уже играет за вас", ErrorPoint::TYPE_USER);
     }
     track_stats();
     // Отслеживаем производительность
     $actionResult = FootballerSatellite::getFootballerOwner($friendId);
     if ($actionResult instanceof ErrorPoint) {
         return $actionResult;
     }
     if ($actionResult !== false) {
         return new ErrorPoint(ErrorPoint::CODE_LOGIC, "Ваш друг уже числиться в другом футбольном клубе", ErrorPoint::TYPE_USER);
     }
     track_stats();
     // Отслеживаем производительность
     SQL::getInstance()->autocommit(false);
     $friendFootballer = new Footballer();
     $actionResult = $friendFootballer->addFriend($friendId, NULL, $this->teamProfile->getActiveCount());
     if ($actionResult instanceof ErrorPoint) {
         SQL::getInstance()->rollback();
         return $actionResult;
     }
     track_stats();
     // Отслеживаем производительность
     $addonPoints = 0;
     if (TeamSatellite::isFreshFriend($friendId)) {
         // Даються очьку обучения как среднее по всех футболистов
         if (count($this->teamProfile->getFootballers()) != 0) {
             $addonPoints = floor($this->teamProfile->getFootballerSumLevel() / count($this->teamProfile->getFootballers()));
             $this->teamProfile->setStudyPoints($this->teamProfile->getStudyPoints() + $addonPoints);
             $actionResult = $this->teamProfile->save();
             if ($actionResult instanceof ErrorPoint) {
                 SQL::getInstance()->rollback();
                 return $actionResult;
             }
         }
     }
     track_stats();
     // Отслеживаем производительность
     $actionResult = Team::markTeamAsSelected($friendId);
     if ($actionResult instanceof ErrorPoint) {
         SQL::getInstance()->rollback();
         return $actionResult;
     }
     track_stats();
     // Отслеживаем производительность
     RAM::getInstance()->changeTeamField($this->teamProfile->getSocialUserId(), 'footballersFriendsCount', $this->teamProfile->getAllFootballersFriendsCount() + 1);
     if ($actionResult instanceof ErrorPoint) {
         SQL::getInstance()->rollback();
     } else {
         SQL::getInstance()->commit();
         $this->result['footballer'] = $friendFootballer;
         $this->result['addonStadyPoints'] = $addonPoints;
         $this->result['totalStadyPoints'] = $this->teamProfile->getStudyPoints();
     }
     track_stats();
     // Отслеживаем производительность
     return $actionResult;
 }
 public function action()
 {
     $this->result["isInstalled"] = $this->teamProfile->getIsInstalled();
     track_stats();
     // ќтслеживаем производительность
     $startAt = RAM::getInstance()->getTourStart();
     $finishAt = RAM::getInstance()->getTourFinish();
     track_stats();
     // ќтслеживаем производительность
     if (empty($startAt) || empty($finishAt)) {
         $tourTimer = TourSatellite::getTimerDate();
         $startAt = $tourTimer->startAt;
         $finishAt = $tourTimer->finishAt;
         RAM::getInstance()->setTourStart($startAt);
         RAM::getInstance()->setTourFinish($finishAt);
     }
     track_stats();
     // ќтслеживаем производительность
     $this->result["tourStartAt"] = $startAt;
     $this->result["tourFinishedAt"] = $finishAt;
     $this->result["serverTime"] = time();
     if ($this->teamProfile->getIsInstalled()) {
         track_stats();
         // ќтслеживаем производительность
         $energyTimer = RAM::getInstance()->getEnergyLastUpdate();
         if (empty($energyTimer)) {
             $energyTimer = filemtime(SYSTEM_LOGS . "/cron.updateEnergy.log");
             // microtime
             RAM::getInstance()->setEnergyLastUpdate($energyTimer);
         }
         $this->result['energyTimer'] = $energyTimer;
         track_stats();
         // ќтслеживаем производительность
         if ($this->teamProfile->isNeedDailyBonus()) {
             $dailyBonus = $this->teamProfile->getTotalStadiumBonus();
             $this->teamProfile->setMoney($this->teamProfile->getMoney() + $dailyBonus);
             $actionResult = TeamSatellite::accrueDailyBonus(UserParameters::getUserId(), $this->teamProfile->getMoney());
             if ($actionResult instanceof ErrorPoint) {
                 return $actionResult;
             }
         }
         track_stats();
         // ќтслеживаем производительность
         if ($this->teamProfile->isNewTour() && $this->teamProfile->getTourBonus() != 0 && $this->teamProfile->getTourBonusTime() == 0) {
             $finishBonusAt = time() + 1 * 24 * 60 * 60;
             $actionResult = TeamSatellite::startTourBonus(UserParameters::getUserId(), $finishBonusAt);
             if ($actionResult instanceof ErrorPoint) {
                 return $actionResult;
             }
             $this->teamProfile->setTourBonusTime($finishBonusAt);
         }
         track_stats();
         // ќтслеживаем производительность
         $this->result["teamInfo"] = JSONPrepare::team($this->teamProfile);
         track_stats();
         // ќтслеживаем производительность
         // Ёто надо обновить после отдачи профайла
         if ($this->teamProfile->getTourNotify() == TOUR_NOTIFY_START || $this->teamProfile->getTourNotify() == TOUR_NOTIFY_NEW) {
             $actionResult = TeamSatellite::updateTourNotify(UserParameters::getUserId(), $this->teamProfile->getTourNotify() - 2);
             if ($actionResult instanceof ErrorPoint) {
                 return $actionResult;
             }
         }
         track_stats();
         // ќтслеживаем производительность
         if ($this->teamProfile->isNewTour() && $this->teamProfile->getTourBonus() != 0 && $this->teamProfile->getTourBonusTime() > 0 && $this->teamProfile->getTourBonusTime() < time()) {
             $actionResult = TeamSatellite::eraseTourBonus(UserParameters::getUserId());
             if ($actionResult instanceof ErrorPoint) {
                 return $actionResult;
             }
             $this->teamProfile->setTourBonus(0);
             $this->teamProfile->setTourBonusTime(0);
         }
         track_stats();
         // ќтслеживаем производительность
         if ($this->teamProfile->getStudyPointsViaPrize() > 0) {
             $actionResult = TeamSatellite::resetPrizeStudyPoint(UserParameters::getUserId());
             if ($actionResult instanceof ErrorPoint) {
                 return $actionResult;
             }
         }
         //Utils::forDebug($this->teamProfile);
     }
 }
 public function action()
 {
     track_stats();
     // Отслеживаем производительность
     $actionResult = NULL;
     $sellId = intval($this->parameters->footballerId);
     $footballerInstance = $this->teamProfile->getFootballerById($sellId);
     if ($footballerInstance === false) {
         $errorMessage = "Анулирование контракта невозможно";
         // Utils::forDebug($errorMessage . " sellId : $sellId - UserId : " . $this->teamProfile->getSocialUserId());
         return new ErrorPoint(ErrorPoint::CODE_LOGIC, "Анулирование контракта невозможно", ErrorPoint::TYPE_USER);
     }
     if ($footballerInstance->getIsActive()) {
         switch ($footballerInstance->getType()) {
             case TYPE_FOOTBALLER_FORWARD_CODE:
                 $this->teamProfile->setParameterForward($this->teamProfile->getParameterForward() - $footballerInstance->getLevel());
                 break;
             case TYPE_FOOTBALLER_SAFER_CODE:
             case TYPE_FOOTBALLER_GOALKEEPER_CODE:
                 $this->teamProfile->setParameterSafe($this->teamProfile->getParameterSafe() - $footballerInstance->getLevel());
                 break;
             case TYPE_FOOTBALLER_HALFSAFER_CODE:
                 $this->teamProfile->setParameterHalf($this->teamProfile->getParameterHalf() - $footballerInstance->getLevel());
                 break;
         }
     }
     track_stats();
     // Отслеживаем производительность
     $this->result['teamParameters'] = array("Forward" => $this->teamProfile->getParameterForward(), "Safe" => $this->teamProfile->getParameterSafe(), "Half" => $this->teamProfile->getParameterHalf());
     track_stats();
     // Отслеживаем производительность
     SQL::getInstance()->autocommit(false);
     track_stats();
     // Отслеживаем производительность
     $deleteResult = $this->teamProfile->deleteFootballerFromStore($footballerInstance);
     if ($deleteResult instanceof ErrorPoint) {
         SQL::getInstance()->rollback();
         return $deleteResult;
     }
     track_stats();
     // Отслеживаем производительность
     if ($footballerInstance->getIsFriend()) {
         $markAsFreeResult = TeamSatellite::markFriendAsFree($footballerInstance->getId(), $free = true);
         if ($markAsFreeResult instanceof ErrorPoint) {
             SQL::getInstance()->rollback();
             return $markAsFreeResult;
         }
     }
     track_stats();
     // Отслеживаем производительность
     $footballerPrice = FootballerSatellite::detectPrice($footballerInstance, $this->teamProfile->getStudyPointCost());
     $footballerPrice = $footballerInstance->getIsSuper() ? $footballerPrice * 3 : $footballerPrice;
     $footballerPrice *= 0.25;
     track_stats();
     // Отслеживаем производительность
     $tourBonus = 1;
     if ($this->teamProfile->isNewTour() && $this->teamProfile->getTourBonus() != 0 && $this->teamProfile->getTourBonusTime() > 0 && $this->teamProfile->getTourBonusTime() > time()) {
         $tourBonus = $this->teamProfile->getTourBonus();
         $tourBonus -= 1;
         $tourBonus = 1 - $tourBonus;
     }
     if ($tourBonus == 0) {
         $tourBonus = 1;
     }
     track_stats();
     // Отслеживаем производительность
     $footballerPrice = $footballerPrice * $tourBonus;
     $this->teamProfile->setMoney($this->teamProfile->getMoney() + $footballerPrice);
     $actionResult = $this->teamProfile->save();
     track_stats();
     // Отслеживаем производительность
     if ($footballerInstance->getIsFriend()) {
         RAM::getInstance()->changeTeamField($this->teamProfile->getSocialUserId(), 'footballersFriendsCount', $this->teamProfile->getAllFootballersFriendsCount() - 1);
     } else {
         RAM::getInstance()->changeTeamField($this->teamProfile->getSocialUserId(), 'footballersCount', $this->teamProfile->getAllFootballersCount() - 1);
     }
     track_stats();
     // Отслеживаем производительность
     if ($actionResult instanceof ErrorPoint) {
         SQL::getInstance()->rollback();
     } else {
         SQL::getInstance()->commit();
     }
     track_stats();
     // Отслеживаем производительность
     return $actionResult;
 }
Beispiel #19
0
        if ($controller->getCurrentError() instanceof ErrorPoint) {
            $return["error"] = $controller->getCurrentError();
        } else {
            $actionResult = $controller->action();
        }
        if (isset($statistic)) {
            $controller->accountingStatistic($statistic);
        }
    }
    break;
}
if ($actionResult instanceof ErrorPoint) {
    $return["error"] = $actionResult->getMessage();
} else {
    $return["isOk"] = true;
    $return["command"] = $command;
    $return["response"] = $controller->getResult();
}
track_stats();
// Отслеживаем производительность
echo json_encode($return);
//$output = ob_get_contents();
// Utils::forDebug("countOfQuery: " . SQL::getInstance()->countOfQuery());
ob_end_flush();
/*if(1 || isset($command) && $command != COMMAND_SYSTEM && ErrorPoint::$isNeedToLog){
    logUsersActivity($output);
}*/
track_stats();
// Отслеживаем производительность
?>
 
 public function action()
 {
     $actionResult = NULL;
     track_stats();
     // Отслеживаем производительность
     $shopItemInDB = FootballerSatellite::getFromStoreById($this->parameters->peopleId, $this->parameters->line);
     if ($shopItemInDB instanceof ErrorPoint) {
         return $shopItemInDB;
     }
     if (isset($this->parameters->line) && $this->parameters->line == TYPE_FOOTBALLER_TEAMLEAD_CODE) {
         $structure = new TrainerPrototype($shopItemInDB);
     } else {
         $structure = new FootballerPrototype();
         $structure->init($shopItemInDB, $this->parameters);
     }
     track_stats();
     // Отслеживаем производительность
     if ($this->parameters->isInGame && $structure->getRequiredLevel() > $this->teamProfile->getLevel()) {
         return new ErrorPoint(ErrorPoint::CODE_LOGIC, "Для соверщения этой операции недостаточно уровня. У пользователя " . $this->teamProfile->getLevel() . " а надо " . $structure->getRequiredLevel(), ErrorPoint::TYPE_USER);
     }
     $tourBonus = 1;
     if ($this->teamProfile->isNewTour() && $this->teamProfile->getTourBonus() != 0 && $this->teamProfile->getTourBonusTime() > 0 && $this->teamProfile->getTourBonusTime() > time()) {
         $tourBonus = $this->teamProfile->getTourBonus();
         $tourBonus -= 1;
         $tourBonus = 1 - $tourBonus;
     }
     track_stats();
     // Отслеживаем производительность
     if ($tourBonus == 0) {
         $tourBonus = 1;
     }
     if ($this->parameters->isInGame) {
         if ($structure->getPrice() * $tourBonus > $this->teamProfile->getMoney()) {
             return new ErrorPoint(ErrorPoint::CODE_LOGIC, "Недостаточно денежных средств", ErrorPoint::TYPE_USER);
         }
     } else {
         if ($structure->getRealPrice() * $tourBonus > $this->teamProfile->getRealMoney()) {
             return new ErrorPoint(ErrorPoint::CODE_LOGIC, "Недостаточно денежных средств", ErrorPoint::TYPE_USER);
         }
     }
     track_stats();
     // Отслеживаем производительность
     SQL::getInstance()->autocommit(false);
     if ($structure instanceof TrainerPrototype) {
         $this->teamProfile->setTrainer($structure->getId());
         track_stats();
         // Отслеживаем производительность
     } else {
         if ($this->teamProfile->getFootballerById($structure->getId())) {
             return new ErrorPoint(ErrorPoint::CODE_LOGIC, "Данный футболист уже в вашем клубе", ErrorPoint::TYPE_USER);
         }
         track_stats();
         // Отслеживаем производительность
         $footballerInstance = new Footballer();
         $actionResult = $footballerInstance->add($structure, $this->teamProfile->getActiveCount());
         if ($actionResult instanceof ErrorPoint) {
             SQL::getInstance()->rollback();
             return $actionResult;
         }
         track_stats();
         // Отслеживаем производительность
         if ($footballerInstance->getIsActive()) {
             switch ($footballerInstance->getType()) {
                 case TYPE_FOOTBALLER_FORWARD_CODE:
                     $this->teamProfile->setParameterForward($this->teamProfile->getParameterForward() + $footballerInstance->getLevel());
                     break;
                 case TYPE_FOOTBALLER_SAFER_CODE:
                 case TYPE_FOOTBALLER_GOALKEEPER_CODE:
                     $this->teamProfile->setParameterSafe($this->teamProfile->getParameterSafe() + $footballerInstance->getLevel());
                     break;
                 case TYPE_FOOTBALLER_HALFSAFER_CODE:
                     $this->teamProfile->setParameterHalf($this->teamProfile->getParameterHalf() + $footballerInstance->getLevel());
                     break;
             }
         }
         $this->result['isActive'] = $footballerInstance->getIsActive();
         $this->result['teamParameters'] = array("Forward" => $this->teamProfile->getParameterForward(), "Safe" => $this->teamProfile->getParameterSafe(), "Half" => $this->teamProfile->getParameterHalf());
         $this->teamProfile->addFootballerToStore($footballerInstance);
         track_stats();
         // Отслеживаем производительность
     }
     if ($this->parameters->isInGame) {
         $this->teamProfile->setMoney($this->teamProfile->getMoney() - $structure->getPrice() * $tourBonus);
     } else {
         $this->teamProfile->setRealMoney($this->teamProfile->getRealMoney() - $structure->getRealPrice() * $tourBonus);
     }
     $actionResult = $this->teamProfile->save();
     track_stats();
     // Отслеживаем производительность
     RAM::getInstance()->changeTeamField($this->teamProfile->getSocialUserId(), 'footballersCount', $this->teamProfile->getAllFootballersCount() + 1);
     if ($actionResult instanceof ErrorPoint) {
         SQL::getInstance()->rollback();
     } else {
         SQL::getInstance()->commit();
     }
     track_stats();
     // Отслеживаем производительность
     return $actionResult;
 }
 public static function initForTeam(Team &$team, $isGetOnlyActive = false)
 {
     $teamId = $team->getSocialUserId();
     $store = array();
     track_stats();
     // Отслеживаем производительность
     $footballersStore = RAM::getInstance()->getObjectsForTeam($teamId, RAM::RAM_TYPE_FOOTBALLER);
     track_stats();
     // Отслеживаем производительность
     $activeFootballer = 0;
     //     Utils::forDebug(count($footballersStore) . " == " . $team->getAllFootballersCount());
     if (count($footballersStore) != $team->getAllFootballersCount() || $team->getAllFootballersCount() == 0) {
         //} || GlobalParameters::$IS_FAKE_ENTER || GlobalParameters::MODER_ID == $teamId){
         $sql_template = "SELECT\n    footballers.level,\n    footballers.footballer_id,\n    footballers.is_active,\n    footballers.super,\n    footballers.health_down,\n    item_footballers.line as type FROM footballers\nLEFT JOIN  item_footballers ON item_footballers.id = footballers.footballer_id\nWHERE footballers.owner_vk_id = %d " . ($isGetOnlyActive ? " AND footballers.is_active = 1 " : "") . " ORDER BY item_footballers.line DESC ";
         $sql_template = "SELECT\n    footballers.level,\n    footballers.footballer_id,\n    footballers.is_active,\n    footballers.super,\n    footballers.health_down,\n    item_footballers.line AS typer FROM footballers, item_footballers\nWHERE footballers.owner_vk_id =  %d " . ($isGetOnlyActive ? " AND footballers.is_active = 1 " : "") . " AND item_footballers.id = footballers.footballer_id ORDER BY item_footballers.line ASC";
         $sql = sprintf($sql_template, intval($teamId));
         $SQLresult = SQL::getInstance()->query($sql);
         track_stats();
         // Отслеживаем производительность
         if ($SQLresult instanceof ErrorPoint) {
             return $SQLresult;
         }
         track_stats();
         // Отслеживаем производительность
         $team->setAllFootballersCount($SQLresult->num_rows, true);
         $counter = 0;
         $footballersStore = array();
         while ($footballer = $SQLresult->fetch_object()) {
             $footballerInstance = new Footballer();
             $footballerInstance->initFromParameters($footballer, false, $teamId, $sql);
             $footballersStore[$footballerInstance->getId()] = $footballerInstance;
             if ($footballerInstance->getIsActive() == 1) {
                 $activeFootballer++;
             }
             //RAM::getInstance()->setFootballer($footballerInstance, $teamId, $counter);
             $counter++;
         }
         track_stats();
         // Отслеживаем производительность
     } else {
         track_stats();
         // Отслеживаем производительность
         $footballersStore = array();
         if ($isGetOnlyActive) {
             $footballersStoreTeam = $footballersStore;
             foreach ($footballersStoreTeam as $footballerInstance) {
                 if ($footballerInstance->getIsActive() == 1) {
                     $footballersStore[$footballerInstance->getId()] = $footballerInstance;
                 }
                 $footballerInstance->checkHealth();
             }
         } else {
             $footballersStoreTeam = $footballersStore;
             foreach ($footballersStoreTeam as $footballerInstance) {
                 if ($footballerInstance instanceof Footballer) {
                     if ($footballerInstance instanceof Footballer && $footballerInstance->getIsActive() == 1) {
                         $activeFootballer++;
                     }
                     $footballersStore[$footballerInstance->getId()] = $footballerInstance;
                     $footballerInstance->checkHealth();
                 }
             }
         }
         track_stats();
         // Отслеживаем производительность
     }
     track_stats();
     // Отслеживаем производительность
     $footballersFriendStore = RAM::getInstance()->getObjectsForTeam($teamId, RAM::RAM_TYPE_FOOTBALLER_FRIEND);
     track_stats();
     // Отслеживаем производительность
     if (count($footballersFriendStore) != $team->getAllFootballersFriendsCount() || $team->getAllFootballersFriendsCount() == 0) {
         $sql_template = "SELECT footballers_friends.*,\n    teams.user_year,\n    teams.user_country,\n    teams.user_name,\n    teams.user_photo,\n    teams.in_team,\n    owner_team.team_name\nFROM footballers_friends\nJOIN teams ON footballers_friends.vk_id = teams.vk_id\nLEFT JOIN teams AS owner_team ON owner_team.vk_id = footballers_friends.owner_vk_id\nWHERE owner_vk_id = '%s' " . ($isGetOnlyActive ? " AND is_active = 1 " : "") . " ORDER BY footballers_friends.type DESC";
         $sql_template = "SELECT\n    footballers_friends.vk_id,\n    footballers_friends.level,\n    footballers_friends.type as typer,\n    footballers_friends.is_active,\n    footballers_friends.super,\n    footballers_friends.owner_vk_id,\n    footballers_friends.health_down,\n    teams.user_year,\n    teams.user_country,\n    teams.user_name,\n    teams.user_photo,\n    teams.in_team\nFROM footballers_friends\nJOIN teams ON footballers_friends.vk_id = teams.vk_id\nWHERE owner_vk_id = %d " . ($isGetOnlyActive ? " AND is_active = 1 " : "") . "  ORDER BY footballers_friends.type DESC";
         // ORDER BY footballers_friends.type DESC";
         $sql = sprintf($sql_template, intval($teamId));
         $SQLresult = SQL::getInstance()->query($sql);
         if ($SQLresult instanceof ErrorPoint) {
             return $SQLresult;
         }
         $team->setAllFootballersFriendsCount($SQLresult->num_rows, true);
         track_stats();
         // Отслеживаем производительность
         $footballersFriendStore = array();
         $counter = 0;
         while ($footballer = $SQLresult->fetch_object()) {
             $footballerInstance = new Footballer();
             $footballerInstance->initFromParameters($footballer, true, $teamId, $sql);
             $footballersFriendStore[$footballerInstance->getId()] = $footballerInstance;
             if ($footballerInstance->getIsActive() == 1) {
                 $activeFootballer++;
             }
             //RAM::getInstance()->setFootballerFriend($footballerInstance, $teamId, $counter);
             $counter++;
         }
         track_stats();
         // Отслеживаем производительность
     } else {
         track_stats();
         // Отслеживаем производительность
         if ($isGetOnlyActive) {
             $footballersStoreTeam = $footballersFriendStore;
             $footballersFriendStore = array();
             foreach ($footballersStoreTeam as $footballerInstance) {
                 if ($footballerInstance->getIsActive() == 1) {
                     $footballersFriendStore[] = $footballerInstance;
                 }
                 $footballerInstance->checkHealth();
             }
         } else {
             foreach ($footballersFriendStore as $footballerInstance) {
                 if ($footballerInstance->getIsActive() == 1) {
                     $activeFootballer++;
                 }
                 $footballerInstance->checkHealth();
             }
         }
         track_stats();
         // Отслеживаем производительность
     }
     $store = array_merge($footballersStore, $footballersFriendStore);
     $returnStore = array();
     foreach ($store as $footballerInstance) {
         if ($footballerInstance instanceof Footballer) {
             $returnStore[$footballerInstance->getId()] = $footballerInstance;
         }
     }
     track_stats();
     // Отслеживаем производительность
     if ($activeFootballer > GlobalParameters::MAX_TEAM) {
         $actionResult = FootballerSatellite::bagoFixActiveFootballers($team, $returnStore);
         if ($actionResult instanceof ErrorPoint) {
             return $actionResult;
         }
         $returnStore = FootballerSatellite::initForTeam($team);
         //            return new ErrorPoint(ErrorPoint::CODE_LOGIC, "Количество активных игроков превышет допустимого значения. Разрешено ".
         //                   GlobalParameters::MAX_TEAM . " а у игрока " . $activeFootballer, ErrorPoint::TYPE_SYSTEM);
     }
     track_stats();
     // Отслеживаем производительность
     return $returnStore;
 }
 private function getFriendsTeams()
 {
     $this->result['teams'] = array();
     $this->result['news'] = array();
     $this->result['rating'] = array();
     if ($this->parameters->groupSourceId) {
         logGroupSource($this->parameters->groupSourceId);
     }
     $needToUpgrade = false;
     $userCountry = intval($this->parameters->userCountry);
     $userCity = intval($this->parameters->userCity);
     $userUniversity = intval($this->parameters->userUniversity);
     track_stats();
     // Отслеживаем производительность
     if ($userCountry != $this->teamProfile->getUserCountry()) {
         $this->teamProfile->setUserCountry($userCountry);
         $needToUpgrade = true;
     }
     if ($userCity != $this->teamProfile->getUserCity()) {
         $this->teamProfile->setUserCity($userCity);
         $needToUpgrade = true;
     }
     if ($userUniversity != $this->teamProfile->getUserUniversity()) {
         $this->teamProfile->setUserUniversity($userUniversity);
         $needToUpgrade = true;
     }
     if (isset($this->parameters->groupBonusNeeded) && $this->parameters->groupBonusNeeded == 1 && $this->teamProfile->getInGroup() == 0) {
         $this->teamProfile->setInGroup(1);
         $this->teamProfile->setRealMoney($this->teamProfile->getRealMoney() + GlobalParameters::GROUP_BONUS_REAL);
         $needToUpgrade = true;
     }
     track_stats();
     // Отслеживаем производительность
     if ($needToUpgrade) {
         $actionResult = $this->teamProfile->save();
         if ($actionResult instanceof ErrorPoint) {
             return $actionResult;
         }
     }
     if ($this->parameters->uids) {
         if (!is_object($this->parameters->uids)) {
             $this->parameters->uids = str_replace('\\\\', '', $this->parameters->uids);
             $this->parameters->uids = str_replace('\\"', '', $this->parameters->uids);
             $this->parameters->uids = json_decode($this->parameters->uids);
         }
         track_stats();
         // Отслеживаем производительность
         $sql_template = "SELECT\n    teams.team_name,\n    teams.param_forward,\n    teams.param_half,\n    teams.param_safe,\n    teams.user_photo,\n    teams.user_name, \n    teams.team_logo_id, \n    teams.vk_id,\n    teams.level\nFROM teams\nWHERE teams.vk_id IN (%s) order by teams.level desc,  teams.counter_won desc ";
         $sql = sprintf($sql_template, Utils::IdsSeparetedByComma($this->parameters->uids));
         $SQLresult = SQL::getInstance()->query($sql);
         if ($SQLresult instanceof ErrorPoint) {
             return $SQLresult;
         }
         if ($SQLresult->num_rows) {
             $counterPlace = 1;
             while ($teamObject = $SQLresult->fetch_object()) {
                 $team = new Team();
                 $team->initFromDB($teamObject, false);
                 if ($team->getLevel() == 0) {
                     continue;
                 }
                 $team->place = $counterPlace;
                 $teamInJSON = JSONPrepare::team($team);
                 $counterPlace++;
                 $this->result['teams'][] = $teamInJSON;
                 //  $this->result['teams'][] = $teamObject;
             }
         }
     }
     $this->result['news'] = RAM::getInstance()->getNews();
     if (count($this->result['news']) == 0) {
         $sql_template = "SELECT news_sport.* FROM news_sport ORDER BY news_id";
         $sql = $sql_template;
         $SQLresult = SQL::getInstance()->query($sql);
         if ($SQLresult instanceof ErrorPoint) {
             return $SQLresult;
         }
         if ($SQLresult->num_rows) {
             $counter = 0;
             while ($newsObject = $SQLresult->fetch_object()) {
                 $news = new NewsEntry($newsObject);
                 $news->id = $counter;
                 $this->result['news'][] = $news;
                 RAM::getInstance()->setNews($news);
                 $counter++;
             }
         }
     }
     $leadTeams = RAM::getInstance()->getLeaders();
     if (count($leadTeams) == 0) {
         $sql_template = "SELECT teams.* FROM teams WHERE total_place is not NULL ORDER BY total_place  LIMIT 6";
         $sql = $sql_template;
         $SQLresult = SQL::getInstance()->query($sql);
         if ($SQLresult instanceof ErrorPoint) {
             return $SQLresult;
         }
         if ($SQLresult->num_rows) {
             $counter = 0;
             while ($teamObject = $SQLresult->fetch_object()) {
                 $team = new Team();
                 $team->initFromDB($teamObject);
                 RAM::getInstance()->setLeader($team, $counter);
                 $counter++;
                 $teamInJSON = JSONPrepare::team($team);
                 $this->result['rating'][] = $teamInJSON;
             }
         }
     } else {
         foreach ($leadTeams as $team) {
             $teamInJSON = JSONPrepare::team($team);
             $this->result['rating'][] = $teamInJSON;
         }
     }
 }
 private function install($teamParam)
 {
     $team = json_decode($teamParam);
     /*if(empty($team)){
           return new ErrorPoint(ErrorPoint::CODE_LOGIC, "Информация о команде получена неполностью, повторите попытку", ErrorPoint::TYPE_USER, $teamParam);  
       }*/
     track_stats();
     // Отслеживаем производительность
     $actionResult = $this->teamProfile->initById(UserParameters::getUserId());
     if ($actionResult instanceof ErrorPoint) {
         return $actionResult;
     }
     if ($actionResult === true) {
         return;
     }
     SQL::getInstance()->autocommit(false);
     $addOnStudyPoints = 0;
     $this->teamProfile->setTeamName(isset($team->teamName) ? $team->teamName : "Футболлер");
     $this->teamProfile->setTeamLogoId(isset($team->teamLogoId) ? $team->teamLogoId : "42326");
     $this->teamProfile->setUserPhoto($this->parameters->userPhoto);
     $this->teamProfile->setUserName($this->parameters->userName);
     $this->teamProfile->setUserYear(isset($this->parameters->userYear) ? intval($this->parameters->userYear) : 0);
     $this->teamProfile->setUserCountry(isset($this->parameters->userCountry) ? intval($this->parameters->userCountry) : 0);
     $this->teamProfile->setParameterForward(0);
     $this->teamProfile->setParameterHalf(0);
     $this->teamProfile->setParameterSafe(0);
     $this->teamProfile->setInGroup(0);
     $installResult = $this->teamProfile->install();
     track_stats();
     // Отслеживаем производительность
     if ($installResult instanceof ErrorPoint) {
         SQL::getInstance()->rollback();
         return $actionResult;
     }
     if ($addOnStudyPoints > GlobalParameters::MAX_TEAM) {
         SQL::getInstance()->rollback();
         return new ErrorPoint(ErrorPoint::CODE_LOGIC, "Друзей в команду набрано больше чем допустимо", ErrorPoint::TYPE_USER);
     }
     $needRandomFootballers = GlobalParameters::MAX_TEAM - $addOnStudyPoints;
     track_stats();
     // Отслеживаем производительность
     if ($needRandomFootballers) {
         $prototypes = FootballerSatellite::getRandomPrototypes($needRandomFootballers);
         if ($prototypes instanceof ErrorPoint) {
             SQL::getInstance()->rollback();
             return $prototypes;
         }
         foreach ($prototypes as $footballerPrototype) {
             $footballer = new Footballer();
             $actionResult = $footballer->add($footballerPrototype, $needRandomFootballers--);
             if ($actionResult instanceof ErrorPoint) {
                 SQL::getInstance()->rollback();
                 return $actionResult;
             }
             $this->teamProfile->addFootballerToStore($footballer);
         }
     }
     track_stats();
     // Отслеживаем производительность
     $this->teamProfile->updateTeamParameters();
     $addOnStudyPoints += 5;
     // Дадим ещё немного очков, для заманухи
     $this->teamProfile->setStudyPoints($addOnStudyPoints);
     $installResult = $this->teamProfile->save();
     track_stats();
     // Отслеживаем производительность
     if ($installResult instanceof ErrorPoint) {
         SQL::getInstance()->rollback();
         return $actionResult;
     } else {
         SQL::getInstance()->commit();
     }
     /*        $getResult = $this->teamProfile->initById(UserParameters::getUserId());
     
             if($getResult instanceof ErrorPoint){
                 SQL::getInstance()->rollback();
                 return $actionResult;
             }
     */
     track_stats();
     // Отслеживаем производительность
     $api = new VKapi(VK_API_SECRET, VK_API_ID, VK_MAILING_SPEED);
     $api->setStatus(UserParameters::getUserId(), sprintf(VK_APPLICATION_STATUS, $this->teamProfile->getTeamName()));
     track_stats();
     // Отслеживаем производительность
     return $installResult;
 }
Beispiel #24
0
 public function initById($userId)
 {
     $this->socialUserId = intval($userId);
     if (!$this->socialUserId) {
         return new ErrorPoint(ErrorPoint::CODE_VK, "Не получен номер команды", ErrorPoint::TYPE_USER);
     }
     track_stats();
     // Отслеживаем производительность
     $teamInstance = RAM::getInstance()->getTeamById($this->socialUserId);
     track_stats();
     // Отслеживаем производительность
     if (empty($teamInstance)) {
         //} || GlobalParameters::$IS_FAKE_ENTER || GlobalParameters::MODER_ID == $userId){
         $sql_template = "SELECT *, unix_timestamp(tour_bonus_time) as tour_bonus_time FROM teams WHERE vk_id = %s";
         $sql = sprintf($sql_template, $this->socialUserId);
         $result = SQL::getInstance()->query($sql);
         if ($result instanceof ErrorPoint) {
             return $result;
         }
         track_stats();
         // Отслеживаем производительность
         if ($result->num_rows) {
             $loadedTeam = $result->fetch_object();
             $this->isInstalled = 1;
             $this->initFromDB($loadedTeam);
             track_stats();
             // Отслеживаем производительность
             $this->footballers = FootballerSatellite::initForTeam($this);
             if ($this->footballers instanceof ErrorPoint) {
                 return $this->footballers;
             }
             track_stats();
             // Отслеживаем производительность
             $this->sponsors = SponsorSatellite::initForTeam($this);
             if ($this->sponsors instanceof ErrorPoint) {
                 return $this->sponsors;
             }
             return true;
         } else {
             if (GlobalParameters::getCommand() != COMMAND_PING && GlobalParameters::getCommand() != COMMAND_FRIEND_INFO && GlobalParameters::getCommand() != COMMAND_SYSTEM && GlobalParameters::getCommand() != COMMAND_WELCOME) {
                 // Utils::forDebug("Не найдена команда по ID#" . $this->socialUserId . " " . $sql);
                 return false;
                 return new ErrorPoint(ErrorPoint::CODE_LOGIC, "Не найдена команда по ID#" . $this->socialUserId, ErrorPoint::TYPE_SYSTEM);
             } else {
                 $this->inTeam = 0;
                 return false;
             }
         }
     } else {
         $this->initFromRAM($teamInstance);
         $this->isInstalled = 1;
         track_stats();
         // Отслеживаем производительность
         $this->footballers = FootballerSatellite::initForTeam($this);
         if ($this->footballers instanceof ErrorPoint) {
             return $this->footballers;
         }
         track_stats();
         // Отслеживаем производительность
         $this->sponsors = SponsorSatellite::initForTeam($this);
         if ($this->sponsors instanceof ErrorPoint) {
             return $this->sponsors;
         }
         track_stats();
         // Отслеживаем производительность
         return true;
     }
 }