/**
  * Desqualify a rival. Knight win combat by desqualify
  */
 public function actionDesqualifyRival()
 {
     $output = array('errno' => 1, 'html' => '', 'isDesqualify' => false);
     //Check session is enable
     if (!Yii::app()->user->isGuest) {
         //Check input
         if (isset($_GET['combat']) && is_numeric($_GET['combat']) && $_GET['combat'] > 0) {
             //Check combat
             if ($combat = Combats::model()->with(array('combatsPrecombat', 'rounds', array('fromKnight' => array('with' => array('knightsCard'))), array('toKnight' => array('with' => 'knightsCard'))))->findByPk($_GET['combat'])) {
                 //Check if user is in combat
                 if ($combat->fromKnight->id == Yii::app()->user->knights_id || $combat->toKnight->id == Yii::app()->user->knights_id) {
                     //Check if combat is enable
                     if ($combat->status == Combats::STATUS_ENABLE) {
                         //Check last round
                         if ($round_data = RoundsData::model()->find('rounds_combats_id = :combats_id AND rounds_number = :rounds_id AND knights_id = :knights_id', array(':combats_id' => $combat->id, ':rounds_id' => count($combat->rounds), ':knights_id' => Yii::app()->user->knights_id))) {
                             //Check time of desqualify
                             $timeLimit = strtotime($round_data->date) + Yii::app()->params['desqualifyTime'];
                             $requestTime = strtotime('now');
                             Yii::trace('[CHARACTER][actionDesqualifyRival] Check limit time of desqualify request (' . $requestTime . ') > $timelimit (' . $timeLimit . ') ');
                             if ($requestTime >= $timeLimit) {
                                 //Finish combat
                                 Yii::trace('[CHARACTER][actionDesqualifyRival] FINISH COMBAT  ');
                                 $output['isDesqualified'] = true;
                                 $combat->status = Combats::STATUS_FINISHED;
                                 $combat->result_by = Combats::RESULT_BY_DESQUALIFY;
                                 //Load round and knights
                                 $round = Rounds::model()->find('combats_id=:combats_id AND number=:number', array(':combats_id' => $combat->id, ':number' => count($combat->rounds)));
                                 if (Yii::app()->user->knights_id == $combat->from_knight) {
                                     $combat->result = Combats::RESULT_FROM_KNIGHT_WIN;
                                     $round->status = Rounds::STATUS_FROM_KNIGHT_WIN;
                                     $fromKnight =& $this->user_data['knights'];
                                     $toKnight = Knights::model()->findByPk($combat->toKnight->id);
                                 } else {
                                     $combat->result = Combats::RESULT_TO_KNIGHT_WIN;
                                     $round->status = Rounds::STATUS_TO_KNIGHT_WIN;
                                     $fromKnight = Knights::model()->findByPk($combat->fromKnight->id);
                                     $toKnight =& $this->user_data['knights'];
                                 }
                                 /*
                                  * Update round and combat
                                  */
                                 Yii::trace('[CHARACTER][actionDesqualifyRival] update round and combat  ');
                                 if (!$round->save()) {
                                     Yii::trace('[CHARACTER][actionDesqualifyRival] No se ha podido salvar el round');
                                 }
                                 if ($combat->save()) {
                                     //Update combat cache
                                     Yii::app()->cache->set(Yii::app()->params['cacheKeys']['combat'] . $combat->id, $combat, Yii::app()->params['cachetime']['combat']);
                                 } else {
                                     Yii::trace('[CHARACTER][actionDesqualifyRival] No se ha podido salvar el combate');
                                 }
                                 /*
                                  * Update knights to ready to challenge 
                                  */
                                 $fromKnight->endurance = ($combat->fromKnight->knightsCard->will + $combat->fromKnight->knightsCard->constitution) * 3;
                                 $fromKnight->life = $combat->fromKnight->knightsCard->constitution * 2;
                                 $fromKnight->status = Knights::STATUS_ENABLE;
                                 $toKnight->endurance = ($combat->toKnight->knightsCard->will + $combat->toKnight->knightsCard->constitution) * 3;
                                 $toKnight->life = $combat->toKnight->knightsCard->constitution * 2;
                                 $toKnight->status = Knights::STATUS_ENABLE;
                                 /*
                                  *Calcula postcombat 
                                  */
                                 //Calculate experience
                                 Yii::trace('[CHARACTER][actionDesqualifyRival] CALCULATE EXPERIENCE');
                                 $precombat = $combat->combatsPrecombat;
                                 $postcombatData = CombatsPostcombat::calculateEarnedExperience($combat, $combat->fromKnight->level, $combat->toKnight->level);
                                 Yii::trace('[CHARACTER][actionDesqualifyRival] SAVE POSTCOMBATS');
                                 $from_knight_post_combat = new CombatsPostcombat();
                                 $from_knight_post_combat->attributes = array('combats_id' => $combat->id, 'knights_id' => $combat->fromKnight->id, 'knight_rival_level' => $combat->fromKnight->level, 'experience_generate' => $postcombatData['from_knight_experience_generate'], 'percent_by_result' => $postcombatData['from_knight_percent_by_result'], 'percent_by_injury' => $postcombatData['from_knight_percent_by_injury'], 'earned_experience' => $postcombatData['from_knight_earned_experience'], 'total_experience' => $combat->fromKnight->experiencie_earned + $postcombatData['from_knight_earned_experience'], 'total_coins' => $precombat->from_knight_gate + $combat->fromKnight->coins, 'earned_coins' => $precombat->from_knight_gate, 'injury_type' => null);
                                 if (!$from_knight_post_combat->save()) {
                                     Yii::trace('[CHARACTER][actionDesqualifyRival] se ha producido un error al salvar postcombate para from knight', 'error');
                                 }
                                 $to_knight_post_combat = new CombatsPostcombat();
                                 $to_knight_post_combat->attributes = array('combats_id' => $combat->id, 'knights_id' => $combat->toKnight->id, 'knight_rival_level' => $combat->toKnight->level, 'experience_generate' => $postcombatData['to_knight_experience_generate'], 'percent_by_result' => $postcombatData['to_knight_percent_by_result'], 'percent_by_injury' => $postcombatData['to_knight_percent_by_injury'], 'earned_experience' => $postcombatData['to_knight_earned_experience'], 'total_experience' => $combat->toKnight->experiencie_earned + $postcombatData['to_knight_earned_experience'], 'total_coins' => $precombat->to_knight_gate + $combat->toKnight->coins, 'earned_coins' => $precombat->to_knight_gate, 'injury_type' => null);
                                 if (!$to_knight_post_combat->save()) {
                                     Yii::trace('[CHARACTER][actionDesqualifyRival] se ha producido un error al salvar postcombate para to knight', 'error');
                                 }
                                 //Update experience of knights
                                 Yii::trace('[CHARACTER][actionSetCombatPoints] UPDATE EXPERIECE');
                                 $fromKknight->experiencie_earned = $from_knight_post_combat->total_experience;
                                 $toKnight->experiencie_earned = $to_knight_post_combat->total_experience;
                                 /*
                                  * Calculate repair prize equipment
                                  */
                                 Yii::trace('[CHARACTER][actionDesqualifyRival]CALCULATE REPAIR PRIZE');
                                 $from_knight_autorepair = CombatsPostcombat::autorepairObjectsEquipment($combat, $combat->fromKnight);
                                 if ($from_knight_autorepair['errno'] > 0) {
                                     Yii::trace('[CHARACTER][actionDesqualifyRival] FROM KNIGHT AUTOREPAIR FAIL', 'error');
                                 }
                                 $to_knight_autorepair = CombatsPostcombat::autorepairObjectsEquipment($combat, $combat->toKnight);
                                 if ($to_knight_autorepair['errno'] > 0) {
                                     Yii::trace('[CHARACTER][actionDesqualifyRival] TO KNIGHT AUTOREPAIR FAIL', 'error');
                                 }
                                 /*
                                  * Update coins of knights
                                  */
                                 Yii::trace('[CHARACTER][actionDesqualifyRival] UPDATE COINS OF KNIGHTS');
                                 Yii::trace('[CHARACTER][actionDesqualifyRival] FROM_KNIGHT earned coins: current coinds(' . $combat->fromKnight->coins . ') + gate coins (' . $precombat->from_knight_gate . ') - autorrepair coins (' . $from_knight_autorepair['repair_cost'] . ') ');
                                 $fromKnight->coins += $precombat->from_knight_gate - $from_knight_autorepair['repair_cost'];
                                 Yii::trace('[CHARACTER][actionDesqualifyRival] TO_KNIGHT earned coins: current coinds(' . $toKnight->coins . ') + gate coins (' . $precombat->to_knight_gate . ') - autorrepair coins (' . $to_knight_autorepair['repair_cost'] . ') ');
                                 $toKnight->coins += $precombat->to_knight_gate - $to_knight_autorepair['repair_cost'];
                                 /*
                                  * Update healings of knights
                                  */
                                 if ($combat->fromKnight->pain > 0) {
                                     Yii::trace('[CHARACTER][actionDesqualifyRival] Healing schule for from knigth');
                                     $healing = Healings::model()->findByPk($combat->fromKnight->id);
                                     $healing->next_healing_date = date('Y-m-d H:i:s', strtotime(date('Y-m-d H:i:s') . ' +' . Yii::app()->params['healingTime'] . ' seconds'));
                                     if (!$healing->save()) {
                                         Yii::trace('[CHARACTER][actionDesqualifyRival] Error to update from knight next healing date', 'error');
                                     }
                                 }
                                 if ($combat->toKnight->pain > 0) {
                                     Yii::trace('[CHARACTER][actionDesqualifyRival] Healing schule for to knigth');
                                     $healing = Healings::model()->findByPk($combat->toKnight->id);
                                     $healing->next_healing_date = date('Y-m-d H:i:s', strtotime(date('Y-m-d H:i:s') . ' +' . Yii::app()->params['healingTime'] . ' seconds'));
                                     if (!$healing->save()) {
                                         Yii::trace('[CHARACTER][actionDesqualifyRival] Error to update to knight next healing date', 'error');
                                     }
                                 }
                                 /*
                                  * STATS
                                  * Update stats of knights and platform
                                  */
                                 Yii::trace('[CHARACTER][actionDesqualifyRival] update stats');
                                 $from_knight_stats = KnightsStats::model()->findByPk($combat->fromKnight->id);
                                 $to_knight_stats = KnightsStats::model()->findByPk($combat->toKnight->id);
                                 $from_knight_stats_vs = KnightsStatsVs::model()->find('knights_id = :knights_id AND opponent = :opponent', array(':knights_id' => $fromKnight->id, ':opponent' => $toKnight->id));
                                 $to_knight_stats_vs = KnightsStatsVs::model()->find('knights_id = :knights_id AND opponent = :opponent', array(':knights_id' => $toKnight->id, ':opponent' => $fromKnight->id));
                                 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);
                                 }
                                 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);
                                 }
                                 $from_knight_stats_by_date = KnightsStatsByDate::model()->find('knights_id = :knights_id AND date = :date', array(':knights_id' => $fromKnight->id, ':date' => substr($combat->date, 0, 10)));
                                 $to_knight_stats_by_date = KnightsStatsByDate::model()->find('knights_id = :knights_id AND date = :date', array(':knights_id' => $toKnight->id, ':date' => substr($combat->date, 0, 10)));
                                 if (!$from_knight_stats_by_date) {
                                     $from_knight_stats_by_date = new KnightsStatsByDate();
                                     $from_knight_stats_by_date = array('knights_id' => $combat->fromKnight->id, 'date' => date('Y-m-d'));
                                 }
                                 if (!$to_knight_stats_by_date) {
                                     $to_knight_stats_by_date = new KnightsStatsByDate();
                                     $to_knight_stats_by_date = array('knights_id' => $combat->toKnight->id, 'date' => date('Y-m-d'));
                                 }
                                 if ($combat->result == Combats::RESULT_FROM_KNIGHT_WIN) {
                                     $from_knight_stats->combats_wins += 1;
                                     $from_knight_stats_vs->combats_wins += 1;
                                     $from_knight_stats_by_date->combats_wins += 1;
                                     $to_knight_stats->combats_loose += 1;
                                     $to_knight_stats_vs->combats_loose += 1;
                                     $to_knight_stats_by_date->combats_loose += 1;
                                 } else {
                                     if ($combat->result == Combats::RESULT_TO_KNIGHT_WIN) {
                                         $to_knight_stats->combats_wins += 1;
                                         $to_knight_stats_vs->combats_wins += 1;
                                         $to_knight_stats_by_date->combats_wins += 1;
                                         $from_knight_stats->combats_loose += 1;
                                         $from_knight_stats_vs->combats_loose += 1;
                                         $from_knight_stats_by_date->combats_loose += 1;
                                     } else {
                                         $to_knight_stats->combats_draw += 1;
                                         $to_knight_stats_vs->combats_draw += 1;
                                         $to_knight_stats_by_date->combats_draw += 1;
                                         $from_knight_stats->combats_draw += 1;
                                         $from_knight_stats_vs->combats_draw += 1;
                                         $from_knight_stats_by_date->combats_draw += 1;
                                     }
                                 }
                                 //stats desquality
                                 if (Yii::app()->user->knights_id == $combat->fromKnight->id) {
                                     $from_knight_stats->desquality_produced += 1;
                                     $to_knight_stats->desquality_received += 1;
                                 } else {
                                     $from_knight_stats->desquality_received += 1;
                                     $to_knight_stats->desquality_produced += 1;
                                 }
                                 //stats money
                                 $from_knight_stats->money_total_earned += $precombat->from_knight_gate;
                                 $to_knight_stats->money_total_earned += $precombat->to_knight_gate;
                                 Yii::trace('[CHARACTER][actionDesqualifyRival] UPDATE STATS ');
                                 if (!$from_knight_stats->save()) {
                                     trace('[CHARACTER][actionDesqualifyRival] No se puede salvar las estadística de from knight', 'error');
                                 }
                                 if (!$from_knight_stats_vs->save()) {
                                     trace('[CHARACTER][actionDesqualifyRival] No se puede salvar las estadística vs de from knight stats', 'error');
                                 }
                                 if (!$from_knight_stats_by_date->save()) {
                                     trace('[CHARACTER][actionDesqualifyRival] No se puede salvar las estadística por dia de from knight stats', 'error');
                                 }
                                 if (!$to_knight_stats->save()) {
                                     trace('[CHARACTER][actionDesqualifyRival] No se puede salvar las estadística de to knight', 'error');
                                 }
                                 if (!$to_knight_stats_vs->save()) {
                                     trace('[CHARACTER][actionDesqualifyRival] No se puede salvar las estadística vs de to knight', 'error');
                                 }
                                 if (!$to_knight_stats_by_date->save()) {
                                     trace('[CHARACTER][actionDesqualifyRival] No se puede salvar las estadística diarias de to knight', 'error');
                                 }
                                 //UPDATE knights
                                 Yii::trace('[CHARACTER][actionDesqualifyRival] update knights ');
                                 if (!$fromKnight->save()) {
                                     Yii::trace('[CHARACTER][actionDesqualifyRival] No se ha podido salvar el caballero from knight');
                                 } else {
                                     Yii::app()->cache->set(Yii::app()->params['cacheKeys']['knights'] . $fromKnight->id, $fromKnight, Yii::app()->params['cachetime']['knight']);
                                     Yii::app()->cache->set(Yii::app()->params['cacheKeys']['knights_by_name'] . $fromKnight->name, $fromKnight, Yii::app()->params['cachetime']['knight']);
                                 }
                                 if (!$toKnight->save()) {
                                     Yii::trace('[CHARACTER][actionDesqualifyRival] No se ha podido salvar el caballero to knight');
                                 } else {
                                     Yii::app()->cache->set(Yii::app()->params['cacheKeys']['knights'] . $fromKnight->id, $fromKnight, Yii::app()->params['cachetime']['knight']);
                                     Yii::app()->cache->set(Yii::app()->params['cacheKeys']['knights_by_name'] . $fromKnight, $fromKnight, Yii::app()->params['cachetime']['knight']);
                                 }
                                 //Show desqualify
                                 $desqualifyKnight = Yii::app()->user->knights_id == $combat->fromKnight->id ? $combat->fromKnight->name : $combat->toKnight->name;
                                 $output['html'] = $this->renderFile(Yii::app()->basePath . '/views/character/dialog_round_desqualified_by.php', array('desqualifiedKnight' => $desqualifyKnight), true);
                                 $output['errno'] = 0;
                             } else {
                                 $output['html'] = 'Todavía no ha pasado el tiempo para que le puedas descalificar. Faltan ' . ($timeLimit - $requestTime) . ' segundos.';
                             }
                         } else {
                             $output['html'] = 'No puedes descalificar a tu adversario si no has enviado los datos para la última ronda.';
                         }
                     } else {
                         $output['html'] = 'Este combate no está en curso.';
                     }
                 } else {
                     $output['html'] = 'No puedes toquetear combates que no son tuyos.';
                 }
             } else {
                 $output['html'] = 'No se ha encontrado el combate.';
             }
         } else {
             $output['html'] = 'El identificador del combate no es válido.';
         }
     } else {
         $output['html'] = 'La sesión ha expirado. Necesitas volver a hacer login.';
     }
     //Show output
     echo CJSON::encode($output);
 }
 /**
  * Activa una cuenta
  */
 public function actionAccountActivation()
 {
     //Initi
     $template = 'error';
     $data = array('message' => '', 'code' => 'en la activación.');
     //Validation input
     /*
     $user = new Users();
     $user->attributes = array(
     	'email'=>$_GET['email']				
     );
     */
     //Check email
     $validator = new CEmailValidator();
     if ($validator->validateValue($_GET['email'])) {
         //Check if user exist
         $user = Users::model()->find('email=:email', array(':email' => $_GET['email']));
         if ($user) {
             //User found
             if ($user->status == Users::STATUS_PENDING_ACTIVATION) {
                 //Load his knight
                 $knight = Knights::model()->find('users_id=:users_id', array('users_id' => $user->id));
                 //Check if code is the same
                 $codigo_activacion = md5($user->email . $knight->name . $user->password_md5 . $user->suscribe_date);
                 if ($_GET['code'] === $codigo_activacion) {
                     //ACTIVATED ACCOUNT
                     //1.- change status
                     $user->status = Users::STATUS_ENABLE;
                     $user->save();
                     $knight->status = Knights::STATUS_WITHOUT_EQUIPMENT;
                     $knight->save();
                     //2.- create card
                     $knight_card = new KnightsCard();
                     $knight_card->attributes = array('knights_id' => $knight->id);
                     $knight_card->save();
                     //3.- Create general stats
                     $knight_stats = new KnightsStats();
                     $knight_stats->attributes = array('knights_id' => $knight->id);
                     if (!$knight_stats->save()) {
                         Yii::trace('[Site][actionAccountActivation] No se puede salvar las stats del caballero', 'error');
                     }
                     //4.- set stats attack location
                     //load all location
                     /*
                     $locations = Constants::model()->findAll( 
                     	'type=:type',
                     	array( ':type'=> Constants::KNIGHTS_LOCATION)
                     );
                     
                     if( count($locations) > 0 ){
                     	//Foreach location set a value for attack location. Defense is depending of shield
                     	foreach( $locations as $location ){
                     		$knights_stats_attack_location = new KnightsStatsAttackLocation();
                     		$knights_stats_attack_location->attributes = array(
                     			'knights_id'=>$knight->id,
                     			'location'=>$location['id']
                     		);
                     		$knights_stats_attack_location->save();
                     	}
                     	
                     }else{
                     	$data['message'] .= 'No hay datos de localizaciones';
                     }
                     */
                     //Change for points of location. 48 is the maximun position number in the attack and defense points
                     for ($i = 1; $i <= 48; $i++) {
                         $knights_stats_attack_location = new KnightsStatsAttackLocation();
                         $knights_stats_attack_location->attributes = array('knights_id' => $knight->id, 'location' => $i);
                         $knights_stats_attack_location->save();
                     }
                     //6.- Set default equipment
                     //Set armours
                     foreach (Armours::getDefaultEquipment() as $key => $id) {
                         //Find armour
                         $armour = Armours::model()->findByPk($id);
                         if ($armour) {
                             //creamos nuevo objeto de la armadura
                             $armour_object = new ArmoursObjects();
                             $armour_object->attributes = array('armours_id' => $id, 'knights_id' => $knight->id, 'current_pde' => $armour->pde);
                             if (!$armour_object->save()) {
                                 //$data['message'] .= '<p>Armadura '.$id.' ('.$armour_object->attributes['armours_id'].') generada ('.var_dump( $armour_object->getErrors()).') ';
                                 Yii::trace('[SITE][actionAccountActivation] Error al salvar la armadura ' . $armour->name, 'error');
                             }
                             //Lo inventariamos. Como son los primeros objetos la posición que ocupa será empezando desde 1
                             $inventory = new Inventory();
                             //Sabemos que no hay objetos por lo que ocupamos las primeras posiciones, que concuerdan con el id
                             $inventory->attributes = array('knights_id' => $knight->id, 'type' => Inventory::EQUIPMENT_TYPE_ARMOUR, 'identificator' => $armour_object->id, 'position' => $key + 11);
                             $data['message'] .= 'e inventariada (' . $inventory->save() . ')</p>';
                         } else {
                             $data['message'] .= '<p>KAKUNA MATATA!!';
                         }
                     }
                     //Set spears
                     $position = 27;
                     $spear = Spears::model()->findByPk(1);
                     //Lanza de entrenamiento
                     foreach (Spears::getDefaultEquipment() as $key => $id) {
                         //Creamos el bojeto lanza
                         $spear_object = new SpearsObjects();
                         $spear_object->attributes = array('spears_id' => $spear->id, 'knights_id' => $knight->id, 'current_pde' => $spear->pde);
                         $spear_object->save();
                         $data['message'] .= '<p>Lanza ' . $id . ' generada</p>';
                         //La inventariamos
                         $inventory = new Inventory();
                         $inventory->attributes = array('knights_id' => $knight->id, 'type' => Inventory::EQUIPMENT_TYPE_SPEAR, 'identificator' => $spear_object->id, 'position' => $position++);
                         $data['message'] .= 'e inventariada (' . $inventory->save() . ')</p>';
                     }
                     //Creamos las eventos de knights_events_last
                     $sql = '';
                     for ($i = 0; $i < Yii::app()->params['events']['event_last']['maximum']; $i++) {
                         $sql .= 'INSERT INTO knights_events_last (knights_id, type, identificator, date) VALUES (' . $knight->id . ', ' . KnightsEvents::TYPE_VOID . ', 0, \'2012-01-01 00:00:' . ($i < 10 ? '0' . $i : $i) . '\' );';
                         /*
                         $event = new KnightsEventsLast();
                         $event->attributes = array(
                         	'knights_id'=>$knight->id,
                         	'type'=> KnightsEvents::TYPE_VOID,
                         	'identificator'=>0,
                         	'date'=>'2012-01-01 00:00:'.(($i<10)?'0'.$i:$i)//for update
                         );
                         $event->save();
                         */
                     }
                     $command = Yii::app()->db->createCommand($sql);
                     $command->execute();
                     Yii::app()->db->setActive(false);
                     //Create healing row
                     $healing = new Healings();
                     $healing->attributes = array('knights_id' => $knight->id, 'next_healing_date' => null);
                     if (!$healing->save()) {
                         Yii::trace('[SITE][actionAccountActivation] I can not insert healing row.', 'error');
                     }
                     //Create settings
                     $knights_settings = new KnightsSettings();
                     $knights_settings->attributes = array('knights_id' => $knight->id);
                     if (!$knights_settings->save()) {
                         Yii::trace('[SITE][actionAccountActivation] I can not insert setting row.', 'error');
                     }
                     unset($knights_settings);
                     //UPDATE YELLOW PAGES
                     $initial_character = substr($knight->name, 0, 1);
                     if (is_numeric($initial_character)) {
                         $initial_character = '[0-9]';
                     } else {
                         $initial_character = strtoupper($initial_character);
                     }
                     $yellow_pages_total = YellowPagesTotal::model()->with('letter0')->find('letter0.name = :letter', array(':letter' => $initial_character));
                     $yellow_pages_total->total += 1;
                     if (!$yellow_pages_total->save()) {
                         Yii::trace('[SITE][actionAccountActivation] No se ha podido actualizar yellow pages total', 'error');
                     }
                     $yellow_pages_total_by_letter = new YellowPagesTotalByLetter();
                     $yellow_pages_total_by_letter->attributes = array('letter' => $yellow_pages_total->letter, 'knights_id' => $knight->id);
                     if (!$yellow_pages_total_by_letter->save()) {
                         Yii::trace('[SITE][actionAccountActivation] No se ha podido crear yellow pages total by letter', 'error');
                     }
                     //Hacemos el login de alta
                     $model = new LoginForm();
                     $model->attributes = array('username' => $user->email, 'password' => 'nolosabemos');
                     //Check if all is ok
                     if ($model->loginFromValidation()) {
                         $template = 'accountActivation';
                     } else {
                         $data['message'] = 'Se ha producido un error al validar la cuenta. Escribenos un correo a ' . Yii::app()->params['adminEmail'];
                     }
                 } else {
                     $data['message'] = 'El usuario y el código de activación no son correctos.';
                 }
             } else {
                 //Message Error: user is not pending of activation
                 $data['message'] = 'El usuario no está pendiente de activación';
             }
         } else {
             //User not found
             $data['message'] = 'El usuario o código de activación no están relacionados.';
         }
     } else {
         //Input not valid
         $data['message'] = 'Los datos de entrada no son correctos.';
     }
     //Show Output
     $this->render($template, $data);
 }
 /**
  * Health knights. 
  * Search in healths table all knights with a expired date of healing. Knights recovery 'constitution / 2' points of pain. If pain is greather than 0 then update
  * the next healing date to next hour. If pain is 0 or less then next healing date is set null. 
  * TIME: every minute of all days.
  * identificator 3
  */
 public function actionHealings()
 {
     $controlCronJobId = 3;
     //Search all next healings
     $result = Healings::model()->with(array('knights' => array('knightsCard')))->findAll('next_healing_date IS NOT NULL AND next_healing_date < :date', array(':date' => date('Y:m:d H:i:s')));
     if (count($result) > 0) {
         foreach ($result as $healing) {
             //Calculate new pain
             $healing_points = floor($healing->knights->knightsCard->constitution / 2);
             $healing->knights->pain -= $healing_points > 0 ? $healing_points : 1;
             //All healings recovery one point of pain at least
             //Check next healing
             if ($healing->knights->pain > 0) {
                 $healing->next_healing_date = date("Y-m-d H:i:s", strtotime($healing->next_healing_date . ' +' . Yii::app()->params['healingTime'] . ' seconds'));
             } else {
                 $healing->knights->pain = 0;
                 $healing->next_healing_date = null;
             }
             //Update knights and healings
             if (!$healing->knights->save()) {
                 Yii::trace('[CRONJOB][actionHealings] No se puede actualizar el caballero.', 'error');
             }
             if (!$healing->save()) {
                 Yii::trace('[CRONJOB][actionHealings] No se puede actualizar la curación.', 'error');
             }
         }
     }
 }