You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

349 lines
11KB

  1. <?php
  2. namespace common\models;
  3. use Yii;
  4. use yii\base\NotSupportedException;
  5. use yii\behaviors\TimestampBehavior;
  6. use yii\db\ActiveRecord;
  7. use yii\db\CDbCriteria;
  8. use yii\web\IdentityInterface;
  9. /**
  10. * User model
  11. *
  12. * @property integer $id
  13. * @property string $username
  14. * @property string $password_hash
  15. * @property string $password_reset_token
  16. * @property string $email
  17. * @property string $auth_key
  18. * @property integer $status
  19. * @property integer $created_at
  20. * @property integer $updated_at
  21. * @property string $password write-only password
  22. * @property boolean $confiance
  23. */
  24. class User extends ActiveRecord implements IdentityInterface {
  25. const STATUS_DELETED = 0;
  26. const STATUS_ACTIVE = 10;
  27. const STATUS_BOULANGER = 11;
  28. const STATUS_ADMIN = 13;
  29. var $password_old;
  30. var $password_new;
  31. var $password_new_confirm;
  32. /**
  33. * @inheritdoc
  34. */
  35. public static function tableName() {
  36. return '{{%user}}';
  37. }
  38. /**
  39. * @inheritdoc
  40. */
  41. public function behaviors() {
  42. return [
  43. TimestampBehavior::className(),
  44. ];
  45. }
  46. /**
  47. * @inheritdoc
  48. */
  49. public function rules() {
  50. return [
  51. ['confiance', 'default', 'value' => 1],
  52. [['no_mail', 'mail_prod_lundi', 'mail_prod_mardi', 'mail_prod_mercredi', 'mail_prod_jeudi', 'mail_prod_vendredi', 'mail_prod_samedi', 'mail_prod_dimanche'], 'boolean'],
  53. [['nom', 'prenom', 'telephone', 'adresse'], 'string'],
  54. [['nom', 'prenom'], 'required', 'message' => 'Ce champs ne peut être vide'],
  55. ['email', 'email', 'message' => 'Cette adresse email n\'est pas valide'],
  56. ['email', 'verifyEmail'],
  57. ['status', 'default', 'value' => self::STATUS_ACTIVE],
  58. ['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_DELETED, self::STATUS_ADMIN, self::STATUS_BOULANGER]],
  59. ['password_old', 'verifyPasswordOld'],
  60. ['password_new', 'verifyPasswordNew'],
  61. ['password_new_confirm', 'verifyPasswordNewConfirm'],
  62. [['date_derniere_connexion', 'password_old', 'password_new', 'password_new_confirm', 'password_hash'], 'safe'],
  63. ];
  64. }
  65. public function verifyPasswordOld($attribute, $params) {
  66. if (strlen($this->password_old)) {
  67. if (!$this->validatePassword($this->password_old)) {
  68. $this->addError($attribute, 'Mot de passe invalide.');
  69. }
  70. }
  71. if (!strlen($this->password_old) && (strlen($this->password_new) || strlen($this->password_new_confirm))) {
  72. $this->addError($attribute, 'Ce champs ne peut être vide');
  73. }
  74. if (!strlen($this->password_new) && (strlen($this->password_old) || strlen($this->password_new_confirm))) {
  75. $this->addError('password_new', 'Ce champs ne peut être vide');
  76. }
  77. if (!strlen($this->password_new_confirm) && (strlen($this->password_old) || strlen($this->password_new))) {
  78. $this->addError('password_new_confirm', 'Ce champs ne peut être vide');
  79. }
  80. }
  81. public function verifyPasswordNew($attribute, $params) {
  82. if (strlen($this->password_new) < 6) {
  83. $this->addError($attribute, 'Votre mot de passe doit comporter au moins 6 caractères.');
  84. }
  85. }
  86. public function verifyPasswordNewConfirm($attribute, $params) {
  87. if ($this->password_new != $this->password_new_confirm) {
  88. $this->addError($attribute, 'Les deux mots de passe doivent être identiques');
  89. }
  90. }
  91. public function verifyEmail($attribute, $params) {
  92. $user = User::find()->where("email LIKE :email AND id != :id")->params(array(':email' => '%' . $this->email . '%', ':id' => $this->id))->one();
  93. if ($user)
  94. $this->addError($attribute, 'Cette adresse email est déjà utilisée par un autre utilisateur ');
  95. }
  96. public function getUserEtablissement() {
  97. return $this->hasMany(UserEtablissement::className(), ['id_user' => 'id']);
  98. }
  99. /**
  100. * @inheritdoc
  101. */
  102. public static function findIdentity($id) {
  103. return static::findOne(['id' => $id/* , 'status' => self::STATUS_ACTIVE */]);
  104. }
  105. /**
  106. * @inheritdoc
  107. */
  108. public static function findIdentityByAccessToken($token, $type = null) {
  109. throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
  110. }
  111. /**
  112. * Finds user by username
  113. *
  114. * @param string $username
  115. * @return static|null
  116. */
  117. public static function findByUsername($username) {
  118. return static::findOne(['username' => $username/* , 'status' => self::STATUS_ACTIVE */]);
  119. }
  120. public static function findByEmail($email) {
  121. return static::findOne(['email' => $email /* , 'status' => self::STATUS_ACTIVE */]);
  122. }
  123. /**
  124. * Finds user by password reset token
  125. *
  126. * @param string $token password reset token
  127. * @return static|null
  128. */
  129. public static function findByPasswordResetToken($token) {
  130. if (!static::isPasswordResetTokenValid($token)) {
  131. return null;
  132. }
  133. return static::findOne([
  134. 'password_reset_token' => $token,
  135. ]);
  136. }
  137. public static function findBy($params = []) {
  138. if (!isset($params['id_etablissement']))
  139. $params['id_etablissement'] = Yii::$app->user->identity->id_etablissement;
  140. $query = (new \yii\db\Query())
  141. ->select(['user.id AS user_id', 'user.prenom', 'user.nom', 'user.telephone', 'user.email', 'user.created_at', 'user.date_derniere_connexion', 'user_etablissement.*'])
  142. ->from('user, user_etablissement')
  143. ->where('user.id = user_etablissement.id_user')
  144. ->andWhere('user_etablissement.actif = 1')
  145. ->andWhere('user_etablissement.id_etablissement = ' . $params['id_etablissement']);
  146. if (isset($params['nom']))
  147. $query->andFilterWhere(['like', 'nom', $params['nom']]);
  148. if (isset($params['prenom']))
  149. $query->andFilterWhere(['like', 'prenom', $params['prenom']]);
  150. if (isset($params['email']))
  151. $query->andFilterWhere(['like', 'email', $params['email']]);
  152. if (isset($params['telephone']))
  153. $query->andFilterWhere(['like', 'telephone', $params['telephone']]);
  154. return $query;
  155. }
  156. /**
  157. * Finds out if password reset token is valid
  158. *
  159. * @param string $token password reset token
  160. * @return boolean
  161. */
  162. public static function isPasswordResetTokenValid($token) {
  163. if (empty($token)) {
  164. return false;
  165. }
  166. $expire = Yii::$app->params['user.passwordResetTokenExpire'];
  167. $parts = explode('_', $token);
  168. $timestamp = (int) end($parts);
  169. return $timestamp + $expire >= time();
  170. }
  171. /**
  172. * @inheritdoc
  173. */
  174. public function getId() {
  175. return $this->getPrimaryKey();
  176. }
  177. /**
  178. * @inheritdoc
  179. */
  180. public function getAuthKey() {
  181. return $this->auth_key;
  182. }
  183. /**
  184. * @inheritdoc
  185. */
  186. public function validateAuthKey($authKey) {
  187. return $this->getAuthKey() === $authKey;
  188. }
  189. /**
  190. * Validates password
  191. *
  192. * @param string $password password to validate
  193. * @return boolean if password provided is valid for current user
  194. */
  195. public function validatePassword($password) {
  196. return Yii::$app->security->validatePassword($password, $this->password_hash);
  197. }
  198. /**
  199. * Generates password hash from password and sets it to the model
  200. *
  201. * @param string $password
  202. */
  203. public function setPassword($password) {
  204. $this->password_hash = Yii::$app->security->generatePasswordHash($password);
  205. }
  206. /**
  207. * Generates "remember me" authentication key
  208. */
  209. public function generateAuthKey() {
  210. $this->auth_key = Yii::$app->security->generateRandomString();
  211. }
  212. /**
  213. * Generates new password reset token
  214. */
  215. public function generatePasswordResetToken() {
  216. $this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
  217. }
  218. /**
  219. * Removes password reset token
  220. */
  221. public function removePasswordResetToken() {
  222. $this->password_reset_token = null;
  223. }
  224. public function attributeLabels() {
  225. return [
  226. 'id' => 'ID',
  227. 'username' => 'Identifiant',
  228. 'password' => 'Mot de passe',
  229. 'rememberMe' => 'Se souvenir de moi',
  230. 'confiance' => 'De confiance',
  231. 'no_mail' => 'Ne pas recevoir d\'email de la part du Chat des Noisettes',
  232. 'mail_prod_lundi' => 'Lundi',
  233. 'mail_prod_mardi' => 'Mardi',
  234. 'mail_prod_mercredi' => 'Mercredi',
  235. 'mail_prod_jeudi' => 'Jeudi',
  236. 'mail_prod_vendredi' => 'Vendredi',
  237. 'mail_prod_samedi' => 'Samedi',
  238. 'mail_prod_dimanche' => 'Dimanche',
  239. 'password_old' => 'Ancien mot de passe',
  240. 'password_new' => 'Nouveau mot de passe',
  241. 'password_new_confirm' => 'Confirmation du nouveau mot de passe',
  242. 'prix_libre' => 'Prix libre',
  243. ];
  244. }
  245. public function isBoulanger() {
  246. return ($this->status == User::STATUS_ADMIN || $this->status == User::STATUS_BOULANGER) && $this->id_etablissement;
  247. }
  248. public function getNomMagasin() {
  249. $etablissement = Etablissement::findOne($this->id_etablissement);
  250. return $etablissement->nom;
  251. }
  252. public function getEtablissementsFavoris() {
  253. $etabs = (new \yii\db\Query())
  254. ->select('*')
  255. ->from(['user_etablissement', 'etablissement'])
  256. ->where('user_etablissement.id_etablissement = etablissement.id')
  257. ->andWhere(['user_etablissement.id_user' => $this->id])
  258. ->andWhere(['user_etablissement.actif' => 1])
  259. ->all();
  260. return $etabs;
  261. }
  262. public function etatPaiementEtablissement() {
  263. $etablissement = Etablissement::findOne($this->id_etablissement);
  264. if ($etablissement) {
  265. return $etablissement->etatPaiement();
  266. }
  267. }
  268. public function periodeEssai() {
  269. $etablissement = Etablissement::findOne($this->id_etablissement);
  270. if ($etablissement) {
  271. $date_limite = strtotime($etablissement->date_creation) + 30 * 24 * 60 * 60;
  272. $date = time();
  273. if ($date < $date_limite) {
  274. $date = $date_limite - $date;
  275. return (int) ($date / (24 * 60 * 60));
  276. } else {
  277. return 0;
  278. }
  279. }
  280. }
  281. public function getCredit($id_etablissement) {
  282. $user_etablissement = UserEtablissement::find()
  283. ->where([
  284. 'id_user' => $this->id,
  285. 'id_etablissement' => $id_etablissement
  286. ])
  287. ->one();
  288. if ($user_etablissement) {
  289. return $user_etablissement->credit;
  290. }
  291. return 0;
  292. }
  293. public function updateDerniereConnexion() {
  294. $this->date_derniere_connexion = date('Y-m-d H:i:s');
  295. $this->save();
  296. }
  297. }