No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

382 líneas
13KB

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