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.

360 lines
12KB

  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')
  139. ->innerJoin('user_etablissement','user.id = user_etablissement.id_user AND user_etablissement.actif = 1 AND user_etablissement.id_etablissement = :id_etablissement', [':id_etablissement' => $params['id_etablissement']])
  140. ;
  141. if(isset($params['id_point_vente']) && $params['id_point_vente']) {
  142. $point_vente = PointVente::findOne(['id' => $params['id_point_vente']]) ;
  143. if($point_vente->acces_restreint) {
  144. $query->innerJoin('point_vente_user','user.id = point_vente_user.id_user AND point_vente_user.id_point_vente = :id_point_vente',[':id_point_vente' => $params['id_point_vente']]) ;
  145. }
  146. else {
  147. $query->innerJoin(
  148. 'commande',
  149. 'user.id = commande.id_user AND commande.id_point_vente = :id_point_vente',
  150. [':id_point_vente' => $params['id_point_vente']]
  151. )->groupBy('user.id') ;
  152. }
  153. }
  154. if (isset($params['nom']))
  155. $query->andFilterWhere(['like', 'nom', $params['nom']]);
  156. if (isset($params['prenom']))
  157. $query->andFilterWhere(['like', 'prenom', $params['prenom']]);
  158. if (isset($params['email']))
  159. $query->andFilterWhere(['like', 'email', $params['email']]);
  160. if (isset($params['telephone']))
  161. $query->andFilterWhere(['like', 'telephone', $params['telephone']]);
  162. return $query;
  163. }
  164. /**
  165. * Finds out if password reset token is valid
  166. *
  167. * @param string $token password reset token
  168. * @return boolean
  169. */
  170. public static function isPasswordResetTokenValid($token) {
  171. if (empty($token)) {
  172. return false;
  173. }
  174. $expire = Yii::$app->params['user.passwordResetTokenExpire'];
  175. $parts = explode('_', $token);
  176. $timestamp = (int) end($parts);
  177. return $timestamp + $expire >= time();
  178. }
  179. /**
  180. * @inheritdoc
  181. */
  182. public function getId() {
  183. return $this->getPrimaryKey();
  184. }
  185. /**
  186. * @inheritdoc
  187. */
  188. public function getAuthKey() {
  189. return $this->auth_key;
  190. }
  191. /**
  192. * @inheritdoc
  193. */
  194. public function validateAuthKey($authKey) {
  195. return $this->getAuthKey() === $authKey;
  196. }
  197. /**
  198. * Validates password
  199. *
  200. * @param string $password password to validate
  201. * @return boolean if password provided is valid for current user
  202. */
  203. public function validatePassword($password) {
  204. return Yii::$app->security->validatePassword($password, $this->password_hash);
  205. }
  206. /**
  207. * Generates password hash from password and sets it to the model
  208. *
  209. * @param string $password
  210. */
  211. public function setPassword($password) {
  212. $this->password_hash = Yii::$app->security->generatePasswordHash($password);
  213. }
  214. /**
  215. * Generates "remember me" authentication key
  216. */
  217. public function generateAuthKey() {
  218. $this->auth_key = Yii::$app->security->generateRandomString();
  219. }
  220. /**
  221. * Generates new password reset token
  222. */
  223. public function generatePasswordResetToken() {
  224. $this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
  225. }
  226. /**
  227. * Removes password reset token
  228. */
  229. public function removePasswordResetToken() {
  230. $this->password_reset_token = null;
  231. }
  232. public function attributeLabels() {
  233. return [
  234. 'id' => 'ID',
  235. 'username' => 'Identifiant',
  236. 'password' => 'Mot de passe',
  237. 'rememberMe' => 'Se souvenir de moi',
  238. 'confiance' => 'De confiance',
  239. 'no_mail' => 'Ne pas recevoir d\'email de la part du Chat des Noisettes',
  240. 'mail_prod_lundi' => 'Lundi',
  241. 'mail_prod_mardi' => 'Mardi',
  242. 'mail_prod_mercredi' => 'Mercredi',
  243. 'mail_prod_jeudi' => 'Jeudi',
  244. 'mail_prod_vendredi' => 'Vendredi',
  245. 'mail_prod_samedi' => 'Samedi',
  246. 'mail_prod_dimanche' => 'Dimanche',
  247. 'password_old' => 'Ancien mot de passe',
  248. 'password_new' => 'Nouveau mot de passe',
  249. 'password_new_confirm' => 'Confirmation du nouveau mot de passe',
  250. 'prix_libre' => 'Prix libre',
  251. ];
  252. }
  253. public function isBoulanger() {
  254. return ($this->status == User::STATUS_ADMIN || $this->status == User::STATUS_BOULANGER) && $this->id_etablissement;
  255. }
  256. public function getNomMagasin() {
  257. $etablissement = Etablissement::findOne($this->id_etablissement);
  258. return $etablissement->nom;
  259. }
  260. public function getEtablissementsFavoris() {
  261. $etabs = (new \yii\db\Query())
  262. ->select('*')
  263. ->from(['user_etablissement', 'etablissement'])
  264. ->where('user_etablissement.id_etablissement = etablissement.id')
  265. ->andWhere(['user_etablissement.id_user' => $this->id])
  266. ->andWhere(['user_etablissement.actif' => 1])
  267. ->all();
  268. return $etabs;
  269. }
  270. public function etatPaiementEtablissement() {
  271. $etablissement = Etablissement::findOne($this->id_etablissement);
  272. if ($etablissement) {
  273. return $etablissement->etatPaiement();
  274. }
  275. }
  276. public function periodeEssai() {
  277. $etablissement = Etablissement::findOne($this->id_etablissement);
  278. if ($etablissement) {
  279. $date_limite = strtotime($etablissement->date_creation) + 30 * 24 * 60 * 60;
  280. $date = time();
  281. if ($date < $date_limite) {
  282. $date = $date_limite - $date;
  283. return (int) ($date / (24 * 60 * 60));
  284. } else {
  285. return 0;
  286. }
  287. }
  288. }
  289. public function getCredit($id_etablissement) {
  290. $user_etablissement = UserEtablissement::find()
  291. ->where([
  292. 'id_user' => $this->id,
  293. 'id_etablissement' => $id_etablissement
  294. ])
  295. ->one();
  296. if ($user_etablissement) {
  297. return $user_etablissement->credit;
  298. }
  299. return 0;
  300. }
  301. public function updateDerniereConnexion() {
  302. $this->date_derniere_connexion = date('Y-m-d H:i:s');
  303. $this->save();
  304. }
  305. }