public function actionIndex() { Yii::trace('[JOBS][actionIndex] Show jobs page'); //Initial $data = array('knight' => &$this->user_data['knights'], 'spearsMaterial' => SpearsMaterials::model()->findAll(array('index' => 'id')), 'app_rules_level' => AppRulesLevel::model()->findAll(array('index' => 'level')), 'job' => Jobs::model()->find('knights_id=:knights_id AND status = :status', array(':knights_id' => Yii::app()->user->knights_id, ':status' => Jobs::STATUS_WORKING))); //Check if user is not at job and user wants one and his status is enable. if (!$data['job'] && ($this->user_data['knights']->status == Knights::STATUS_ENABLE || $this->user_data['knights']->status == Knights::STATUS_WITHOUT_EQUIPMENT) && isset($_POST['hours']) && is_numeric($_POST['hours']) && $_POST['hours'] > 0 && $_POST['hours'] < 9) { Yii::trace('[JOBS][actionIndex] Inserting a new job'); $data['job'] = new Jobs(); $data['job']->attributes = array('knights_id' => Yii::app()->user->knights_id, 'knight_level' => $this->user_data['knights']->level, 'date' => date("Y-m-d H:i:s", strtotime(date("Y-m-d H:i:s") . ' +' . $_POST['hours'] . ' hour' . ($_POST['hours'] > 1 ? 's' : ''))), 'hours' => $_POST['hours'], 'status' => Jobs::STATUS_WORKING); //Insert new job if ($data['job']->save()) { //Change status of knight $this->user_data['knights']->status = Knights::STATUS_AT_WORK; if (!$this->user_data['knights']->save()) { Yii::trace('[JOBS][index] No se ha podido poner al caballero en estado trabajando'); } } else { //Upss fail job Yii::trace('[JOBS][index] Jobs save is fail'); $data['job'] = null; } } else { if (isset($_POST['hours'])) { if ($data['job']) { Yii::app()->user->setFlash('error', 'Ya tienes un trabajo. No puedes hacer como los políticos de trabajar en otra cosa mientras estás contratado.'); } if ($this->user_data['knights']->status != Knights::STATUS_ENABLE && $this->user_data['knights']->status != Knights::STATUS_WITHOUT_EQUIPMENT) { Yii::app()->user->setFlash('error', 'No puedes trabajar si ya estás trabajando o en mitad de un combate.'); } if (!is_numeric($_POST['hours']) || $_POST['hours'] <= 0 || $_POST['hours'] > 8) { Yii::app()->user->setFlash('error', 'El número de horas es confuso. ¿Que estás haciendo?' . $_POST['hours']); } } } $this->render('index', $data); }
/** * Accept or rejec a challenge. */ public function actionResponseChallenge() { $output = array('errno' => 1, 'html' => ''); //Check session is enable if (!Yii::app()->user->isGuest) { //Check input if (isset($_GET['action']) && ($_GET['action'] == 'accept' || $_GET['action'] == 'reject') && isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0) { //Check if combat exit $arrayWith = array(array('fromKnight' => array('knightsCard')), array('toKnight' => array('knightsCard')), 'combatsPrecombat'); $combat = Combats::model()->with($arrayWith)->findByPk($_GET['id']); //ECHO $combat->fromKnight->knightsCard->act;DIE(); if ($combat) { //Check if combat is in status if ($combat->status == Combats::STATUS_PENDING) { //Check if knights are free to combat if ($combat->fromKnight->status == Knights::STATUS_ENABLE && $combat->toKnight->status == Knights::STATUS_ENABLE) { //Check if user is in combat if ($combat->toKnight->id == Yii::app()->user->knights_id) { //check if rival is connected //if( Sessions::model()->exists( 'users_id = :users_id AND expire > :expire', array(':users_id'=>$combat->fromKnight->users_id,':expire'=>time())) ){ if (Yii::app()->cache->get(Yii::app()->params['cacheKeys']['knight_connected'] . $combat->fromKnight->id)) { //Update combat if ($_GET['action'] == 'accept') { $combat->status = Combats::STATUS_ENABLE; } else { $combat->status = Combats::STATUS_FINISHED; $combat->result = Combats::RESULT_REJECT; $output['html'] = '<p>¡COMBATE RECHAZADO!</p><p>Sales de la sala lo más dignamente posible antes de que las lágrimas broten de tus ojos. Este acto de cobardía te perseguirá toda tu vida.</p>'; } if ($combat->save()) { //Update cache combat Yii::app()->cache->set(Yii::app()->params['cacheKeys']['combat'] . $combat->id, $combat, Yii::app()->params['cachetime']['combat']); if ($_GET['action'] == 'accept') { /* * Create PRECOMBAT */ //For random srand(); $from_knight_fans_throw = rand(1, 10); $to_knight_fans_throw = rand(1, 10); //Get cache of knights depending of his fame $from_knight_fame = floor(($combat->fromKnight->knightsCard->charisma + $combat->fromKnight->knightsCard->act) / 2); $to_knight_fame = floor(($combat->toKnight->knightsCard->charisma + $combat->toKnight->knightsCard->act) / 2); $from_knight_appRulesLevel = AppRulesLevel::model()->find('level=:level', array(':level' => $from_knight_fame)); $to_knight_appRulesLevel = AppRulesLevel::model()->find('level=:level', array(':level' => $to_knight_fame)); //Calculate gate $from_knight_prize_by_entrance = round($from_knight_appRulesLevel->cache / ($from_knight_fame + 11 / 2), 2); $to_knight_prize_by_entrance = round($to_knight_appRulesLevel->cache / ($to_knight_fame + 11 / 2), 2); $from_knight_gate = round(($from_knight_fame + $from_knight_fans_throw) * $from_knight_prize_by_entrance, 2); $to_knight_gate = round(($to_knight_fame + $from_knight_fans_throw) * $to_knight_prize_by_entrance, 2); $precombat = new CombatsPrecombat(); $precombat->attributes = array('combats_id' => $combat->id, 'from_knight_cache' => $from_knight_appRulesLevel->cache, 'from_knight_fame' => $combat->fromKnight->knightsCard->charisma + $combat->fromKnight->knightsCard->act, 'from_knight_fans_throw' => $from_knight_fans_throw, 'to_knight_cache' => $to_knight_appRulesLevel->cache, 'to_knight_fame' => $combat->toKnight->knightsCard->charisma + $combat->toKnight->knightsCard->act, 'to_knight_fans_throw' => $to_knight_fans_throw, 'from_knight_gate' => $from_knight_gate, 'to_knight_gate' => $to_knight_gate); if ($precombat->save()) { //Make first round $roundOne = new Rounds(); $roundOne->attributes = array('combats_id' => $combat->id, 'number' => 1, 'status' => Rounds::STATUS_PENDING); if ($roundOne->save()) { //Change status of knights in combat mode $combat->fromKnight->status = Knights::STATUS_AT_COMBAT; if (!$combat->fromKnight->save()) { Yii::trace('[CHARACTER][actionResponseChallenge] No se ha podido actualizar el caballero from con status en combate'); } //Update caches Yii::app()->cache->set(Yii::app()->params['cacheKeys']['knights'] . $combat->fromKnight->id, $combat->fromKnight, Yii::app()->params['cachetime']['knight']); Yii::app()->cache->set(Yii::app()->params['cacheKeys']['knights_by_name'] . $combat->fromKnight->name, $combat->fromKnight, Yii::app()->params['cachetime']['knight']); $combat->toKnight->status = Knights::STATUS_AT_COMBAT; if (!$combat->toKnight->save()) { Yii::trace('[CHARACTER][actionResponseChallenge] No se ha podido actualizar el caballero to knight con status en combate'); } Yii::app()->cache->set(Yii::app()->params['cacheKeys']['knights'] . $combat->toKnight->id, $combat->toKnight, Yii::app()->params['cachetime']['knight']); Yii::app()->cache->set(Yii::app()->params['cacheKeys']['knights_by_name'] . $combat->toKnight->name, $combat->toKnight, Yii::app()->params['cachetime']['knight']); /* * Check stats vs */ $from_knight_stats_vs = KnightsStatsVs::model()->find('knights_id = :knights_id AND opponent = :opponent', array(':knights_id' => $combat->fromKnight->id, ':opponent' => $combat->toKnight->id)); //If not exist we make a new if (!$from_knight_stats_vs) { $from_knight_stats_vs = new KnightsStatsVs(); $from_knight_stats_vs->attributes = array('knights_id' => $combat->fromKnight->id, 'opponent' => $combat->toKnight->id, 'money_total_earned' => 0); $from_knight_stats_vs->save(); } $to_knight_stats_vs = KnightsStatsVs::model()->find('knights_id = :knights_id AND opponent = :opponent', array(':knights_id' => $combat->toKnight->id, ':opponent' => $combat->fromKnight->id)); if (!$to_knight_stats_vs) { $to_knight_stats_vs = new KnightsStatsVs(); $to_knight_stats_vs->attributes = array('knights_id' => $combat->toKnight->id, 'opponent' => $combat->fromKnight->id, 'money_total_earned' => 0); $to_knight_stats_vs->save(); } /* * Check stats by day */ $from_knight_stats_by_day = KnightsStatsByDate::model()->find('knights_id = :knights_id AND date = :date', array(':knights_id' => $combat->fromKnight->id, ':date' => substr($combat->date, 0, 10))); if (!$from_knight_stats_by_day) { $from_knight_stats_by_day = new KnightsStatsByDate(); $from_knight_stats_by_day->attributes = array('knights_id' => $combat->fromKnight->id, 'date' => substr($combat->date, 0, 10)); if (!$from_knight_stats_by_day->save()) { Yii::trace('[CHARACTER][actionResponseChallenge] No se ha podido crear la nueva columna de stats por dia del caballero from knight.', 'error'); } } $to_knight_stats_by_day = KnightsStatsByDate::model()->find('knights_id = :knights_id AND date = :date', array(':knights_id' => $combat->toKnight->id, ':date' => substr($combat->date, 0, 10))); if (!$to_knight_stats_by_day) { $to_knight_stats_by_day = new KnightsStatsByDate(); $to_knight_stats_by_day->attributes = array('knights_id' => $combat->toKnight->id, 'date' => substr($combat->date, 0, 10)); if (!$to_knight_stats_by_day->save()) { Yii::trace('[CHARACTER][actionResponseChallenge] No se ha podido crear la nueva columna de stats por dia del caballero to knight.', 'error'); } } //Update gained coins /* $from_knight_stats = KnightsStats::model()->findByPk( $combat->fromKnight->id ); $from_knight_stats->money_total_earned += $precombat->from_knight_gate; $from_knight_stats_vs->money_total_earned += $precombat->from_knight_gate; if( $precombat->from_knight_gate > $from_knight_stats->money_maximum_earned_combat ) $from_knight_stats->money_maximum_earned_combat = $precombat->from_knight_gate; if( $precombat->from_knight_gate > $from_knight_stats_vs->money_maximum_earned_combat ) $from_knight_stats_vs->money_maximum_earned_combat = $precombat->from_knight_gate; if( $from_knight_stats->save() ) Yii::trace( '[CHARACTER][actionResponseChallenge] No se ha podido actualizar las stats de from knight', 'error' ); if( $from_knight_stats_vs->save() ) Yii::trace( '[CHARACTER][actionResponseChallenge] No se ha podido actualizar las stats vs de from knight', 'error' ); unset( $from_knight_stats ); unset( $from_knight_stats_vs ); $to_knight_stats = KnightsStats::model()->findByPk( $combat->toKnight->id ); $to_knight_stats->money_total_earned += $precombat->to_knight_gate; $to_knight_stats_vs->money_total_earned += $precombat->to_knight_gate; if( $precombat->to_knight_gate > $to_knight_stats->money_maximum_earned_combat ) $to_knight_stats->money_maximum_earned_combat = $precombat->to_knight_gate; if( $precombat->to_knight_gate > $to_knight_stats_vs->money_maximum_earned_combat ) $to_knight_stats_vs->money_maximum_earned_combat = $precombat->to_knight_gate; if( $to_knight_stats->save() ) Yii::trace( '[CHARACTER][actionResponseChallenge] No se ha podido actualizar las stats de to knight', 'error' ); if( $to_knight_stats_vs->save() ) Yii::trace( '[CHARACTER][actionResponseChallenge] No se ha podido actualizar las stats vs de to knight', 'error' ); unset( $to_knight_stats ); unset( $to_knight_stats_vs ); */ //return precombat $combat->combatsPrecombat = $precombat; $output['errno'] = 0; $output['html'] = $this->renderFile(Yii::app()->basePath . '/views/character/dialog_pre_combat.php', array('combat' => $combat), true); } else { $output['html'] = '<p>Se ha producido un error al registrar la primera ronda.</p>'; //REturn status of combat $combat->status = Combats::STATUS_PENDING; $combat->save(); $precombat->delete(); } } else { $combat->status = Combats::STATUS_PENDING; $combat->save(); $output['html'] = '<p>Se ha producido un error al registrar el precombate.</p>'; } } } else { $output['html'] = '<p>Se ha producido un error al registrar la respuesta.</p>'; } } else { $output['html'] = '<p>¡Sir ' . $combat->fromKnight->name . ' ya no está conectado!</p><p>Tendrás que esperar a que se conecte para poder machacarle...</p>'; //echo '('.Yii::app()->cache->get( Yii::app()->params['cachekey']['knight_connected'].$this->knight->id ).' - ('.Yii::app()->cache->get( Yii::app()->params['cacheKey']['knight_connected'].$combat->fromKnight->users_id ).')'; } } else { $output['html'] = '<p>No te corresponde a ti aceptar o rechazar este combate.</p>'; } } else { $output['html'] = '<p>Algún caballero o ya está combatiendo o está trabajando.</p>'; } } else { $output['html'] = '<p>El combate no está pendiente de aceptar o rechazar.</p>'; } } else { $output['html'] = '<p>El identificador no es válido.</p>'; } } else { //Input no ovalid $output['html'] = '<p>Los datos recibidos no son válidos.</p>'; } } else { $output['html'] = '<p>Tu sesión ha expirado. Tienes que volver a hacer login.</p>'; } echo CJSON::encode($output); }
/** * This function pay for all jobs in working and date is expired. * This function is a cronjob. Only use for cron * Identificator job: 1 */ public function actionPayJobs() { $controlCronJobId = 1; //Find all jobs for to pay Yii::trace('[JOBS][actionPayJobs] Pay jobs finished before' . date("Y-m-d H:i:s")); $jobs_list = Jobs::model()->findAll('status = :status AND date <= :date', array(':status' => Jobs::STATUS_WORKING, 'date' => date("Y-m-d H:i:s"))); Yii::trace('[JOBS][actionPayJobs] Pay jobs (' . count($jobs_list) . ')'); if (count($jobs_list) > 0) { //Load cache of knights $app_rule_level = AppRulesLevel::model()->findAll(array('index' => 'level')); foreach ($jobs_list as $job) { //Update Knight $knight = Knights::model()->findByPk($job->knights_id); $knight->coins += $job->hours * $app_rule_level[$job->knight_level]->cache; //Check status of knight if (Inventory::checkIfPrimaryEquipmentIsCompleted($knight->id)) { $knight->status = Knights::STATUS_ENABLE; } else { $knight->status = Knights::STATUS_WITHOUT_EQUIPMENT; } if (!$knight->save()) { Yii::trace('[JOBS][actionPayJobs] No se ha podido actualizar el caballero con sus rupias nuevas.'); } //Update job $job->status = Jobs::STATUS_PAYED; if (!$job->save()) { Yii::trace('[JOBS][actionPayJobs] No se ha podido actualizar el trabajo con el status "pagado".'); } //Create event for knight $event = new KnightsEvents(); $event->attributes = array('knights_id' => $job->knights_id, 'type' => KnightsEvents::TYPE_JOB, 'identificator' => $job->id); if (!$event->save()) { Yii::trace('[JOBS][actionPayJobs] No se ha podido guardar un evento nuevo.', 'error'); } //Update old event $lastEvent = KnightsEventsLast::getOldLastEvent($job->knights_id); $lastEvent->type = KnightsEvents::TYPE_JOB; $lastEvent->identificator = $job->id; $lastEvent->date = date('Y-m-d H:i:s'); if (!$lastEvent->save()) { Yii::trace('[JOBS][actionPayJobs] No se ha podido actualizar el último evento más viejo.', 'error'); } //Update stats and stats by day with coins earned. $knight_stats = KnightsStats::model()->findByPk($job->knights_id); if ($knight_stats) { $knight_stats->money_total_earned += $job->hours * $app_rule_level[$job->knight_level]->cache; if (!$knight_stats->save()) { Yii::trace('[JOBS][actionPayJobs] No se han podido actualizar las estadisticas del caballero', 'error'); } } else { Yii::trace('[JOBS][actionPayJobs] No hay stats del caballero', 'error'); } $knight_stats_by_date = KnightsStatsByDate::model()->find('knights_id = :knights_id AND date = :date', array(':knights_id' => $job->knights_id, 'date' => substr($job->date, 0, 10))); if (!$knight_stats) { $knight_stats_by_date = new KnightsStatsByDate(); $knight_stats_by_date->attributes = array('knights_id' => $job->knights_id, 'date' => substr($job->date, 0, 10)); } $knight_stats_by->money_total_earned += $job->hours * $app_rule_level[$job->knight_level]->cache; if (!$knight_stats_by_date->save()) { Yii::trace('[JOBS][actionPayJobs] No se han podido actualizar las estadisticas por día del caballero', 'error'); } } } }