Incam_PROFIND_Web/www/protected/models/Usuario.php

264 lines
8.2 KiB
PHP

<?php
/**
* Modelo del usuario
*
* Propiedades
* @property integer $id
* @property integer $id_empresa
* @property string $estado
* @property string $email
* @property string $nombre
* @property string $apellidos
* @property string $password
* @property string $tipo
* @property string $titulo
* @property string $localidad
* @property string $telefono
* @property datetime $last_login_time
* @property datetime $created_time
* @property datetime $deleted_time
* @property string $clave_seguridad
* @property string $descripcion
* @property string $ficheroFotografia
* @property FotografiaPerfil $fotografia
*
* Relaciones
* @property Empresa $empresa
*/
class Usuario extends CActiveRecord {
const ESTADO_NOACTIVO = 0;
const ESTADO_ACTIVO = 1;
const ESTADO_BORRADO = 2;
const ESTADO_DENEGADO = 3;
const TIPO_USUARIO_COORDINADOR = 'C';
const TIPO_USUARIO_AGENTE = 'A';
public $ficheroFotografia;
public $fotografia;
public function getEstaActivo() {
return ($this->estado == self::ESTADO_ACTIVO);
}
/**
* Returns the static model of the specified AR class.
* @param string $className active record class name.
* @return Usuario the static model class
*/
public static function model($className = __CLASS__) {
return parent::model($className);
}
/**
* @return string the associated database table name
*/
public function tableName() {
return 'tbl_usuarios';
}
/**
* @return array validation rules for model attributes.
*/
public function rules() {
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('email, password', 'required'),
array('email, nombre, apellidos, password, tipo, titulo, localidad', 'length', 'max' => 255),
array('estado', 'length', 'max' => 1),
array('email', 'email'),
array('email', 'unique'),
array('descripcion', 'safe'),
array('telefono', 'length', 'max' => 13),
array('telefono', 'match', 'pattern'=>'/^([+]?[0-9 ]+)$/'),
array('tipo', 'default', 'value' => self::TIPO_USUARIO_COORDINADOR),
array('ficheroFotografia', 'file',
'types' => 'jpg',
'maxSize' => 1024 * 1024 * 1, // 1MB como máximo
'tooLarge' => Yii::t('profind', 'La imagen es demasiado pesada. Elija otra fotografía más pequeña.'),
'wrongType' => Yii::t('profind', 'Sólo se permiten imágenes en formato JPG.'),
'allowEmpty' => 'true',
),
array('id, id_empresa, estado, email, nombre, apellidos, tipo, titulo, localidad, telefono, descripcion', 'safe', 'on' => 'search'),
);
}
/**
* @return array relational rules.
*/
public function relations() {
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'empresa' => array(self::BELONGS_TO, 'Empresa', 'id_empresa'),
);
}
public function scopes() {
return array(
'equipo' => array(
'condition' => 'id_empresa = :id_empresa and id <> :id',
'params' => array(
'id_empresa' => Yii::app()->user->id_empresa,
'id' => Yii::app()->user->id
)
)
);
}
/**
* @return array customized attribute labels (name=>label)
*/
public function attributeLabels() {
return array(
'id' => 'ID',
'ficheroFotografia' => 'Fotografía',
'estado' => 'Estado',
'email' => 'Email',
'nombre' => 'Nombre',
'apellidos' => 'Apellidos',
'password' => 'Password',
'tipo' => 'Tipo',
'titulo' => 'Título',
'localidad' => 'Localidad',
'telefono' => 'Teléfono',
'descripcion' => 'Descripción',
);
}
/**
* Retrieves a list of models based on the current search/filter conditions.
* @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
*/
public function search() {
$criteria = new CDbCriteria;
$criteria->compare('id', $this->id);
$criteria->compare('id_empresa', $this->id_empresa);
$criteria->compare('estado', $this->estado, true);
$criteria->compare('email', $this->email, true);
$criteria->compare('nombre', $this->nombre, true);
$criteria->compare('apellidos', $this->apellidos, true);
$criteria->compare('tipo', $this->tipo, true);
$criteria->compare('titulo', $this->titulo, true);
$criteria->compare('localidad', $this->localidad, true);
$criteria->compare('telefono', $this->telefono, true);
$criteria->compare('descripcion', $this->descripcion, true);
return new CActiveDataProvider($this, array(
'criteria' => $criteria,
));
}
protected function beforeSave() {
if ($this->isNewRecord)
$this->created_time = date("Y-m-d H:i:s");
if (($this->estado === self::ESTADO_BORRADO) && ($this->deleted_time === NULL))
$this->deleted_time = date("Y-m-d H:i:s");
return parent::beforeSave();
}
protected function afterFind() {
parent::afterFind();
$this->fotografia = new FotografiaPerfil();
$this->fotografia->modelo = $this;
}
protected function afterConstruct() {
parent::afterConstruct();
$this->fotografia = new FotografiaPerfil();
$this->fotografia->modelo = $this;
}
protected function afterSave() {
parent::afterSave();
if ($this->isNewRecord)
$this->createUploadDir();
}
protected function afterDelete() {
parent::afterDelete();
$this->deleteUploadDir();
}
/*
* Devuelve la ruta con los ficheros del usuario.
* Incluye el separador de directorios al final de la ruta.
* @return string ruta
*/
public function getUploadPath() {
return Yii::getPathOfAlias('application.uploads.usuarios') . DIRECTORY_SEPARATOR . $this->id . DIRECTORY_SEPARATOR;
}
/*
* Devuelve el nombre del fichero por defecto cuando no se tiene imagen
* @return string ruta
*/
public function getImagenDefault() {
return 'user_photo.jpg';
}
/*
* Crea un directorio para almacenar ficheros del usuario
* @return boolean
*/
private function createUploadDir() {
$upload = $this->getUploadPath();
if(!is_dir($upload)) {
return mkdir($upload);
}
else return false;
}
/*
* Elimina el directorio del usuario y todos sus ficheros
* @return boolean
*/
private function deleteUploadDir() {
$upload = $this->getUploadPath();
if(is_dir($upload)) {
require_once( Yii::getPathOfAlias('application.helpers') . DIRECTORY_SEPARATOR . 'recursive_remove_directory.php');
return recursive_remove_directory($upload);
}
else return false;
}
public function getNombreCompleto() {
$cadena = $this->nombre;
if ($this->apellidos) $cadena .= ' ' . $this->apellidos;
return $cadena;
}
/*
* Función para cifrar la contraseña del usuario
* @return string contraseña cifrada
*/
public function encryptPassword($password) {
$ph = new PasswordHash(
Yii::app()->params['phpass']['iteration_count_log2'],
Yii::app()->params['phpass']['portable_hashes']
);
return $ph->HashPassword($password);
}
/*
* Función para cifrar la clave de seguridad del usuario
* @return string clave de seguridad cifrada
*/
public function encryptSecureKey($key) {
return md5($key);
}
}