public function beforeAction($action)
    {
        //Load user's knight data
        if (!Yii::app()->user->isGuest) {
            $this->user_data['knights'] = Knights::model()->with('knightsCard', 'knightsStats')->find('id=:id', array(':id' => Yii::app()->user->knights_id));
            $this->user_data['knights_card'] =& $this->user_data['knights']->knightsCard;
            //Load stats of knight
            $this->user_data['knights_stats'] =& $this->user_data['knights']->knightsStats;
            //Load if user has new friendship request
            $sql = 'SELECT friends.id as id, k1.name as name, k1.avatars_id as avatars_id FROM friends
					INNER JOIN users ON users.id = friends.from_user
					INNER JOIN knights as k1 ON k1.users_id = users.id
					WHERE friends.status = :status AND to_user = :users_knights_id1
					ORDER BY start_date DESC';
            $command = Yii::app()->db->createCommand($sql);
            $command->bindValue(':status', Friends::STATUS_ONWAITING, PDO::PARAM_INT);
            $command->bindValue(':users_knights_id1', $this->user_data['knights']->id, PDO::PARAM_INT);
            $this->user_data['knights_new_friends'] = $command->queryAll();
            //Load last messages
            $this->user_data['new_messages'] = Messages::getNewMessages(Yii::app()->user->users_id);
            //Load all attributes name attributes
            $this->app_data['attribute_list'] = Constants::model()->findAll('type=:type', array(':type' => Constants::KNIGHTS_ATTRIBUTES));
            //Load settings
            $this->user_data['knight_settings'] = KnightsSettings::model()->findByPk(Yii::app()->user->knights_id);
            $this->user_data['user'] = Users::model()->findByPk(Yii::app()->user->users_id);
        } else {
            $this->redirect('/');
        }
        return true;
    }
    /**
     * Make a combat  with initial status.
     */
    public function actionSendChallenge()
    {
        //Check session is enable
        if (!Yii::app()->user->isGuest) {
            //Check if user is a cheater
            if ($this->user_data['knights']->name != $this->knight->name) {
                //Check if user has not a previous challenger enable
                $conditionParams = array(':status1' => Combats::STATUS_PENDING, ':status2' => Combats::STATUS_ENABLE, ':me1' => Yii::app()->user->users_id, ':me2' => Yii::app()->user->users_id, ':rival1' => $this->knight->id, ':rival2' => $this->knight->id);
                //Check if knights have a pending or enable combat
                if (!Combats::model()->exists('status != :status AND (from_knight = :knight1 AND to_knight = :rival1) OR (from_knight = :rival2 AND from_knight = :knight2)', array(':knight1' => Yii::app()->user->knights_id, ':rival1' => $this->knight->id, ':knight2' => Yii::app()->user->knights_id, ':rival2' => $this->knight->id, ':status' => Combats::STATUS_FINISHED))) {
                    //Insert a new combat
                    $combat = new Combats();
                    $combat->attributes = array('from_knight' => Yii::app()->user->knights_id, 'to_knight' => $this->knight->id, 'date' => date("Y-m-d H:i:s"), 'type' => Combats::TYPE_FRIENDLY, 'status' => Combats::STATUS_PENDING);
                    if ($combat->save()) {
                        //Insert a new combat knight event of both knights
                        $knightEventMe = new KnightsEvents();
                        $knightEventMe->attributes = array('knights_id' => Yii::app()->user->knights_id, 'type' => KnightsEvents::TYPE_COMBAT, 'identificator' => $combat->id);
                        if ($knightEventMe->save()) {
                            $knightEventRival = new KnightsEvents();
                            $knightEventRival->attributes = array('knights_id' => $this->knight->id, 'type' => KnightsEvents::TYPE_COMBAT, 'identificator' => $combat->id);
                            if ($knightEventRival->save()) {
                                //Update rows from knight events last
                                $sql = "UPDATE\n\t\t\t\t\t\t\t\t\t\tknights_events_last as k\n\t\t\t\t\t\t\t\t\t\tSET\n\t\t\t\t\t\t\t\t\t\tk.type = " . KnightsEvents::TYPE_COMBAT . ",\n\t\t\t\t\t\t\t\t\t\t\t\tk.identificator = " . $combat->id . ",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tk.date = '" . date('Y-m-d H:i:s') . "'\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tk.id IN (\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSELECT id FROM (\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSELECT\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tid\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tFROM\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tknights_events_last\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tknights_id = " . Yii::app()->user->knights_id . "\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tORDER BY date ASC\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tLIMIT 1\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t) as trick\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t)";
                                //echo $sql;	die();
                                $command = Yii::app()->db->createCommand($sql);
                                //$command->bindValue( ':user_knights_id', Yii::app()->user->knights_id );
                                if ($command->query()) {
                                    $sql = "UPDATE\n\t\t\t\t\t\t\t\t\t\t\tknights_events_last\n\t\t\t\t\t\t\t\t\t\t\tSET\n\t\t\t\t\t\t\t\t\t\t\ttype = " . KnightsEvents::TYPE_COMBAT . ",\n\t\t\t\t\t\t\t\t\t\t\t\t\tidentificator = " . $combat->id . ",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttype = " . KnightsEvents::TYPE_COMBAT . ",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdate = '" . date('Y-m-d H:i:s') . "'\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tid IN (\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSELECT id FROM (\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSELECT\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tid\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tFROM\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tknights_events_last\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tknights_id = " . $this->knight->id . "\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tORDER BY date ASC\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tLIMIT 1\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t) as trick\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t)";
                                    $command = Yii::app()->db->createCommand($sql);
                                    //$command->bindValue( ':knight_id', $this->knight->id );
                                    if ($command->execute()) {
                                        Yii::trace('[CHARACTER][sendChallenge] CHECK email');
                                        //Check email of challenge
                                        if ($knight_setting = KnightsSettings::model()->findByPk($this->knight->id)) {
                                            if ($knight_setting->emailToSendChallenge) {
                                                Yii::trace('[CHARACTER][sendChallenge] Send email');
                                                if ($knight_user = Users::model()->findByPk($this->knight->users_id)) {
                                                    Yii::trace('[CHARACTER][sendChallenge] Rival email' . $knight_user->email);
                                                    //cargamos la plantilla
                                                    $message = Yii::app()->controller->renderFile(Yii::app()->basePath . Yii::app()->params['email_templates_path'] . 'sendNewChallenge.tpl', array(), true);
                                                    // To send HTML mail, the Content-type header must be set
                                                    $headers = 'MIME-Version: 1.0' . "\r\n";
                                                    $headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
                                                    // Additional headers
                                                    $headers .= 'To: ' . $knight_user->email . "\r\n";
                                                    $headers .= 'From: <noreply@' . Yii::app()->params->url_domain . '>' . "\r\n";
                                                    $email = new Emails();
                                                    $email->attributes = array('destination' => $knight_user->email, 'headers' => $headers, 'title' => Yii::app()->name . ': tienes un reto pendiente.', 'body' => $message, 'status' => Emails::STATUS_PENDING, 'date' => date('Y-m-d H:i:s'));
                                                    if (!$email->save()) {
                                                        Yii::trace('[CHARACTER][actionSendChallenge] No se ha podido guardar el email');
                                                    }
                                                } else {
                                                    Yii::trace('[CHARACTER][actionSendChallenge] No se ha encontrado usuario del caballero ' . $this->knight->id, 'error');
                                                }
                                            }
                                        } else {
                                            Yii::trace('[CHARACTER][actionSendChallenge] No se ha encontrado setting del caballero ' . $this->knight->id, 'error');
                                        }
                                        echo '<p>El guantazo resuena por toda la sala.</p><p>Una multitud mirando y una mejilla con 5 dedos marcados no dejan lugar a dudas. El desafio ha sido lanzado</p>
												<p>La reacción del adversario no debería hacerse esperar...</p>';
                                    } else {
                                        echo '<p>Se ha producido un error al guardar el evento rival del combate en la cache.</p>';
                                    }
                                } else {
                                    echo '<p>Se ha producido un error al guardar el evento del combate en la cache.</p>';
                                }
                                //Update events
                                /*
                                $knightEventLastMe = new KnightsEventsLast();
                                $knightEventLastMe->attributes = array(
                                		'knights_id' => Yii::app()->user->knights_id,
                                		'type' => KnightsEvents::TYPE_COMBAT,
                                		'identificator' => $combat->id,
                                		'date' => $combat->date
                                );
                                
                                $criteria = new CDbCriteria();
                                $criteria->condition = 'knights_id = :knights_id';
                                $criteria->condition = 'knights_id = :knights_id';
                                $knightEventMe = KnightsEvents::model()->find(  );
                                
                                
                                if( $knightEventLastMe->save() ){
                                $knightEventLastMe = new KnightsEventsLast();
                                $knightEventLastMe->attributes = array(
                                		'knights_id' => $this->knight->id,
                                		'type' => KnightsEvents::TYPE_COMBAT,
                                		'identificator' => $combat->id,
                                		'date' => $combat->date
                                );
                                if( $knightEventLastMe->save() ){
                                echo '<p>El guantazo resuena por toda la sala.</p><p>Una multitud mirando y una mejilla con 5 dedos marcados no dejan lugar a dudas. El desafio ha sido lanzado</p>
                                <p>La reacción del adversario no debería hacerse esperar...</p>';
                                }else{
                                echo '<p>Se ha producido un error al guardar el evento rival en la caché .</p>' ;
                                }
                                }else{
                                echo '<p>Se ha producido un error al guardar el evento en la caché .</p>' ;
                                }
                                
                                
                                //Update table caché knights events las
                                $knightEventLastMe = KnightsEventsLast::model()->find( 'knights_id :knights_id' );
                                */
                            } else {
                                echo '<p>Se ha producido un error al guardar el evento rival del combate .</p>';
                            }
                        } else {
                            echo '<p>Se ha producido un error al guardar el evento del combate.</p>';
                        }
                    } else {
                        echo '<p>Se ha producido un error al guardar el desafio.</p>';
                    }
                } else {
                    //There is a combat pending or enable
                    echo '<p>No se puede desafiar a alguien con el que tienes un desafio pendiente o en curso.</p>';
                }
            } else {
                echo '<p>¿Cómo has llegado a retarte a ti mismo? En este momento no te parece tan buena idea.</p>';
            }
        } else {
            echo '<p>Tu sesión ha expirado. Tienes que volver a hacer login.</p>';
        }
    }
 /**
  * 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);
 }
 public function actionTest()
 {
     var_dump(KnightsSettings::model()->findByPk(3));
 }