Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

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