您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

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