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.

346 lines
11KB

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