Blame view

common/models/User.php 27.9 KB
b0f143c3   Yarik   first commit
1
  <?php
b95371cf   Yarik   test
2
      namespace common\models;
b0f143c3   Yarik   first commit
3
  
4ed1f788   Yarik   test
4
      use common\modules\comment\models\Comment;
32ed90fd   Yarik   test
5
      use common\modules\comment\models\CommentProject;
4ed1f788   Yarik   test
6
      use common\modules\comment\models\Rating;
b95371cf   Yarik   test
7
      use Yii;
4ed1f788   Yarik   test
8
      use yii\base\InvalidConfigException;
b95371cf   Yarik   test
9
10
      use yii\base\NotSupportedException;
      use yii\behaviors\TimestampBehavior;
e8236f44   Yarik   test
11
      use yii\db\ActiveQuery;
b95371cf   Yarik   test
12
      use yii\db\ActiveRecord;
be662d1f   Yarik   test
13
      use yii\helpers\Url;
e8236f44   Yarik   test
14
15
      use yii\rbac\ManagerInterface;
      use yii\rbac\Role;
b95371cf   Yarik   test
16
17
      use yii\web\IdentityInterface;
      use developeruz\db_rbac\interfaces\UserRbacInterface;
b0f143c3   Yarik   first commit
18
19
  
      /**
b95371cf   Yarik   test
20
       * User model
5077a0ec   Yarik   test
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
       * @property integer              $id
       * @property string               $username
       * @property string               $password_hash
       * @property string               $password_reset_token
       * @property string               $email
       * @property string               $auth_key
       * @property integer              $status
       * @property integer              $created_at
       * @property integer              $updated_at
       * @property string               $password write-only password
       * @property string               $type
       * @property UserInfo             $userInfo
       * @property string               $userName
       * @property array[]              $roles
       * @property CompanyInfo          $companyInfo
       * @property array[]              $phones
       * @property array[]              $site
       * @property string               $address
       * @property string               $liveTime
       * @property Payment[]            $payments
       * @property integer[]            $paymentInput
       * @property Specialization[]     $specializations
       * @property integer[]            $specializationInput
       * @property Blog[]               $blog
       * @property Job[]                $jobs
       * @property Job                  $currentJob
       * @property Portfolio[]          $portfolios
       * @property Project[]            $projects
       * @property Team[]               $teams
       * @property Vacancy[]            $vacancies
       * @property Gallery[]            $galleries
be662d1f   Yarik   test
52
       * @property UserInfo|CompanyInfo $owner
5077a0ec   Yarik   test
53
54
55
56
57
58
       * @property string               $name
       * @property Comment[]            $comments
       * @property Rating[]             $commentRating
       * @property int                  $ratingPG
       * @property string               $lastVisit
       * @property string               $link
38ffb9db   Yarik   test
59
60
       * @method string minImg( string $dir, $width, $height = NULL ) Resizes image
       * @method array ShowGallery( string $array ) Splits string to image paths array
b0f143c3   Yarik   first commit
61
       */
b95371cf   Yarik   test
62
      class User extends ActiveRecord implements IdentityInterface, UserRbacInterface
b0f143c3   Yarik   first commit
63
      {
4c9663e0   Yarik   test
64
  
b95371cf   Yarik   test
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
          const STATUS_DELETED = 0;
          const STATUS_ACTIVE = 10;
  
          public $profile;
  
          public $old_password;
  
          public $new_password;
  
          public $password_reply;
  
          /**
           * @inheritdoc
           */
          public static function tableName()
          {
              return '{{%user}}';
          }
  
b95371cf   Yarik   test
84
85
86
87
88
89
          /**
           * @inheritdoc
           */
          public function behaviors()
          {
              return [
35b03e57   Administrator   add yii jquery
90
                  [
be662d1f   Yarik   test
91
                      'class' => 'common\behaviors\ShowImage',
35b03e57   Administrator   add yii jquery
92
                  ],
b95371cf   Yarik   test
93
94
95
96
                  TimestampBehavior::className(),
              ];
          }
  
b95371cf   Yarik   test
97
98
99
100
101
102
103
          /**
           * @inheritdoc
           */
          public function rules()
          {
              return [
                  [
236a608c   Yarik   test
104
                      [ 'firstname' ],
239b3249   Yarik   test
105
106
107
                      'required',
                  ],
                  [
b95371cf   Yarik   test
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
                      'status',
                      'default',
                      'value' => self::STATUS_ACTIVE,
                  ],
                  [
                      'status',
                      'in',
                      'range' => [
                          self::STATUS_ACTIVE,
                          self::STATUS_DELETED,
                      ],
                  ],
                  [
                      [
                          'username',
                          'lastname',
                          'firstname',
                          'middlename',
                      ],
                      'string',
                      'max' => 255,
                  ],
                  [
b95371cf   Yarik   test
131
132
133
                      [
                          'specializationInput',
                          'paymentInput',
4ed1f788   Yarik   test
134
                          'type',
b95371cf   Yarik   test
135
136
137
                      ],
                      'safe',
                  ],
658a5f37   Yarik   test
138
139
140
141
                  [
                      'type',
                      'default',
                      'value' => 1,
4ed1f788   Yarik   test
142
                  ],
38a6e1dd   Yarik   test
143
144
145
146
147
148
149
150
                  [
                      [
                          'specializationInput',
                          'paymentInput',
                      ],
                      'default',
                      'value' => [ ],
                  ],
b95371cf   Yarik   test
151
152
153
154
155
156
              ];
          }
  
          /**
           * @inheritdoc
           */
3e86d3d1   Yarik   test
157
158
159
          public function attributeLabels()
          {
              return [
06ec2844   Administrator   28.03.16
160
161
162
                  'firstname' => Yii::t('app', 'firstname'),
                  'lastname'  => Yii::t('app', 'lastname'),
                  'email'     => Yii::t('app', 'email'),
3e86d3d1   Yarik   test
163
164
165
166
167
168
              ];
          }
  
          /**
           * @inheritdoc
           */
b95371cf   Yarik   test
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
          public static function findIdentity($id)
          {
              if(Yii::$app->getSession()
                          ->has('user-' . $id)
              ) {
                  if(Yii::$app->getSession()
                              ->has('user-' . $id)
                  ) {
                      return new self(Yii::$app->getSession()
                                               ->get('user-' . $id));
                  } else {
                      return isset( self::$users[ $id ] ) ? new self(self::$users[ $id ]) : NULL;
                  }
              } else {
                  return static::findOne([
                      'id'     => $id,
                      'status' => self::STATUS_ACTIVE,
                  ]);
b0f143c3   Yarik   first commit
187
              }
b95371cf   Yarik   test
188
  
b0f143c3   Yarik   first commit
189
          }
b95371cf   Yarik   test
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
  
          /**
           * @param \nodge\eauth\ServiceBase $service
           *
           * @return User
           * @throws ErrorException
           */
          public static function findByEAuth($service)
          {
              if(!$service->getIsAuthenticated()) {
                  throw new ErrorException('EAuth user should be authenticated before creating identity.');
              }
              $id = $service->getServiceName() . '-' . $service->getId();
              $attributes = [
                  'id'       => $id,
                  'username' => $service->getAttribute('name'),
                  'authKey'  => md5($id),
                  'profile'  => $service->getAttributes(),
              ];
              $attributes[ 'profile' ][ 'service' ] = $service->getServiceName();
              Yii::$app->getSession()
                       ->set('user-' . $id, $attributes);
              return new self($attributes);
b0f143c3   Yarik   first commit
213
          }
b0f143c3   Yarik   first commit
214
  
b95371cf   Yarik   test
215
          public $authKey;
b0f143c3   Yarik   first commit
216
  
b95371cf   Yarik   test
217
218
219
220
221
222
223
          /**
           * @inheritdoc
           */
          public static function findIdentityByAccessToken($token, $type = NULL)
          {
              throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
          }
b0f143c3   Yarik   first commit
224
  
b95371cf   Yarik   test
225
226
227
228
229
230
231
232
233
234
235
236
237
238
          /**
           * Finds user by username
           *
           * @param string $username
           *
           * @return static|null
           */
          public static function findByUsername($username)
          {
              return static::findOne([
                  'username' => $username,
                  'status'   => self::STATUS_ACTIVE,
              ]);
          }
b0f143c3   Yarik   first commit
239
  
b95371cf   Yarik   test
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
          /**
           * Finds user by password reset token
           *
           * @param string $token password reset token
           *
           * @return static|null
           */
          public static function findByPasswordResetToken($token)
          {
              if(!static::isPasswordResetTokenValid($token)) {
                  return NULL;
              }
  
              return static::findOne([
                  'password_reset_token' => $token,
                  'status'               => self::STATUS_ACTIVE,
              ]);
b0f143c3   Yarik   first commit
257
258
          }
  
b95371cf   Yarik   test
259
260
261
262
263
264
265
266
267
268
269
270
          /**
           * Finds out if password reset token is valid
           *
           * @param string $token password reset token
           *
           * @return boolean
           */
          public static function isPasswordResetTokenValid($token)
          {
              if(empty( $token )) {
                  return false;
              }
b0f143c3   Yarik   first commit
271
  
b95371cf   Yarik   test
272
273
274
              $timestamp = (int) substr($token, strrpos($token, '_') + 1);
              $expire = Yii::$app->params[ 'user.passwordResetTokenExpire' ];
              return $timestamp + $expire >= time();
b0f143c3   Yarik   first commit
275
276
          }
  
b95371cf   Yarik   test
277
278
279
280
281
282
283
          /**
           * @inheritdoc
           */
          public function getId()
          {
              return $this->getPrimaryKey();
          }
b0f143c3   Yarik   first commit
284
  
b95371cf   Yarik   test
285
286
287
288
289
290
291
          /**
           * @inheritdoc
           */
          public function getAuthKey()
          {
              return $this->auth_key;
          }
b0f143c3   Yarik   first commit
292
  
b95371cf   Yarik   test
293
294
295
296
297
298
299
          /**
           * @inheritdoc
           */
          public function validateAuthKey($authKey)
          {
              return $this->getAuthKey() === $authKey;
          }
b0f143c3   Yarik   first commit
300
  
b95371cf   Yarik   test
301
302
303
304
305
306
307
308
309
310
311
          /**
           * Validates password
           *
           * @param string $password password to validate
           *
           * @return boolean if password provided is valid for current user
           */
          public function validatePassword($password)
          {
              return Yii::$app->security->validatePassword($password, $this->password_hash);
          }
b0f143c3   Yarik   first commit
312
  
b95371cf   Yarik   test
313
314
315
316
317
318
319
320
321
          /**
           * Generates password hash from password and sets it to the model
           *
           * @param string $password
           */
          public function setPassword($password)
          {
              $this->password_hash = Yii::$app->security->generatePasswordHash($password);
          }
b0f143c3   Yarik   first commit
322
  
b95371cf   Yarik   test
323
324
325
326
327
328
329
          /**
           * Generates "remember me" authentication key
           */
          public function generateAuthKey()
          {
              $this->auth_key = Yii::$app->security->generateRandomString();
          }
b0f143c3   Yarik   first commit
330
  
b95371cf   Yarik   test
331
332
333
334
335
336
337
          /**
           * Generates new password reset token
           */
          public function generatePasswordResetToken()
          {
              $this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
          }
b0f143c3   Yarik   first commit
338
  
b95371cf   Yarik   test
339
340
341
342
343
344
345
          /**
           * Removes password reset token
           */
          public function removePasswordResetToken()
          {
              $this->password_reset_token = NULL;
          }
b0f143c3   Yarik   first commit
346
  
e8236f44   Yarik   test
347
348
          /**
           * Returns name of the User
e8236f44   Yarik   test
349
350
           * @return string
           */
b95371cf   Yarik   test
351
352
353
354
          public function getUserName()
          {
              return $this->username;
          }
b0f143c3   Yarik   first commit
355
  
e8236f44   Yarik   test
356
357
          /**
           * Return array of all User's roles
e8236f44   Yarik   test
358
359
           * @return array
           */
b95371cf   Yarik   test
360
361
362
363
364
365
          public function getRoles()
          {
              $auth = \Yii::$app->authManager;
              $roles = $this->getRoleChildrenRecursive($auth->getRolesByUser($this->id), $auth);
              return $roles;
          }
b0f143c3   Yarik   first commit
366
  
e8236f44   Yarik   test
367
          /**
4c9663e0   Yarik   test
368
369
370
371
           * @param       Role[]           $roles User roles returned by
           *                                      [ManagerInterface]->[getRolesByUser($id)]
           * @param       ManagerInterface $auth  Auth manager
           * @param array                  $result
e8236f44   Yarik   test
372
373
374
           *
           * @return array
           */
b95371cf   Yarik   test
375
          protected function getRoleChildrenRecursive($roles, $auth, $result = [ ])
b0f143c3   Yarik   first commit
376
          {
b95371cf   Yarik   test
377
378
379
380
381
382
383
              if(is_array($roles) && !empty( $roles )) {
                  foreach($roles as $role => $item) {
                      if(!( $item instanceof \yii\rbac\Role )) {
                          continue;
                      }
                      $result[] = $role;
                      $result = self::getRoleChildrenRecursive($auth->getChildren($role), $auth, $result);
b0f143c3   Yarik   first commit
384
                  }
b95371cf   Yarik   test
385
386
387
                  return $result;
              } else {
                  return $result;
b0f143c3   Yarik   first commit
388
              }
b0f143c3   Yarik   first commit
389
          }
cd6bd007   Yarik   test
390
  
e8236f44   Yarik   test
391
392
          /**
           * Return UserInfo for this User
e8236f44   Yarik   test
393
394
           * @return \yii\db\ActiveQuery
           */
b95371cf   Yarik   test
395
396
          public function getUserInfo()
          {
4ed1f788   Yarik   test
397
398
              return $this->hasOne(UserInfo::className(), [ 'user_id' => 'id' ])
                          ->inverseOf('user');
b95371cf   Yarik   test
399
          }
51e0a262   Yarik   test
400
  
e8236f44   Yarik   test
401
402
          /**
           * Check if User is Performer
e8236f44   Yarik   test
403
           * <i>currently in development mode</i>
e8236f44   Yarik   test
404
405
           * @return bool
           */
b95371cf   Yarik   test
406
407
408
409
          public function getIsPerformer()
          {
              return true;
          }
033f9331   Administrator   09.02.16
410
  
e8236f44   Yarik   test
411
412
          /**
           * Return CompanyInfo for this User
e8236f44   Yarik   test
413
414
           * @return \yii\db\ActiveQuery
           */
47559a4b   Yarik   test
415
416
417
418
          public function getCompanyInfo()
          {
              return $this->hasOne(CompanyInfo::className(), [ 'user_id' => 'id' ]);
          }
658d13d4   Administrator   09.02.16
419
  
e8236f44   Yarik   test
420
421
          /**
           * Return array of User's phones
e8236f44   Yarik   test
422
423
           * @return array
           */
a02e2fdb   Yarik   test
424
425
426
          public function getPhones()
          {
              return Fields::getData($this->id, self::className(), 'phone');
f6ea8941   Administrator   09.02.16
427
428
          }
  
e8236f44   Yarik   test
429
430
          /**
           * Return array of User's site
e8236f44   Yarik   test
431
432
           * @return array
           */
a02e2fdb   Yarik   test
433
434
435
          public function getSite()
          {
              return Fields::getData($this->id, self::className(), 'site');
f6ea8941   Administrator   09.02.16
436
437
          }
  
e8236f44   Yarik   test
438
439
          /**
           * Return full address of User in view like:
e8236f44   Yarik   test
440
441
442
           * <code>{country}, {city}, {street}, {house}</code>
           * @return string
           */
a02e2fdb   Yarik   test
443
444
          public function getAddress()
          {
0eb4e7fc   Yarik   test
445
              $address = $this->userInfo->city;
38ffb9db   Yarik   test
446
447
              if(!empty( $this->userInfo->country )) {
                  $address = $this->userInfo->country . ', ' . $address;
0eb4e7fc   Yarik   test
448
449
              }
              if($this->type == 2) {
38ffb9db   Yarik   test
450
451
                  if(!empty( $this->companyInfo->street )) {
                      $address .= ', ' . $this->companyInfo->street;
0eb4e7fc   Yarik   test
452
                  }
38ffb9db   Yarik   test
453
454
                  if(!empty( $this->companyInfo->house )) {
                      $address .= ', ' . $this->companyInfo->house;
0eb4e7fc   Yarik   test
455
456
457
                  }
              }
              return $address;
f6ea8941   Administrator   09.02.16
458
459
          }
  
e8236f44   Yarik   test
460
461
          /**
           * Return relative interval of time from User registration date until now.
e8236f44   Yarik   test
462
463
           * @return string
           */
47559a4b   Yarik   test
464
465
          public function getLiveTime()
          {
47559a4b   Yarik   test
466
467
              $now = new \DateTime('now');
              $date1 = new \DateTime(date('Y-m-d H:i:s', $this->created_at));
eb7e82fb   Administrator   29.02.16
468
469
              $result = explode(',', \Yii::$app->formatter->asDuration($date1->diff($now)));
  
4ed1f788   Yarik   test
470
              if($result >= 4) {
eb7e82fb   Administrator   29.02.16
471
472
473
                  array_splice($result, 2);
              }
  
cefc2aa6   Yarik   test
474
              return implode('', $result);
47559a4b   Yarik   test
475
          }
b95371cf   Yarik   test
476
  
e8236f44   Yarik   test
477
478
          /**
           * Check if User is Customer
e8236f44   Yarik   test
479
           * <i>currently in development</i>
e8236f44   Yarik   test
480
481
           * @return bool
           */
b95371cf   Yarik   test
482
483
484
485
486
          public function getIsCustomer()
          {
              return true;
          }
  
e8236f44   Yarik   test
487
488
          /**
           * Return array of payments types accepted by the user.
e8236f44   Yarik   test
489
490
           * @return ActiveQuery
           */
b95371cf   Yarik   test
491
492
493
494
495
496
          public function getPayments()
          {
              return $this->hasMany(Payment::className(), [ 'payment_id' => 'payment_id' ])
                          ->viaTable('user_payment', [ 'user_id' => 'id' ]);
          }
  
e8236f44   Yarik   test
497
498
          /**
           * Return array of Payment IDs, accepted by the user.
e8236f44   Yarik   test
499
500
           * @return integer[]
           */
b95371cf   Yarik   test
501
502
503
504
505
506
507
          public function getPaymentInput()
          {
              return $this->getPayments()
                          ->asArray()
                          ->column();
          }
  
e8236f44   Yarik   test
508
509
510
511
512
          /**
           * Setter which allow to set User's payment ID's for further saving to the DB.
           *
           * @param integer[] $value
           */
b95371cf   Yarik   test
513
514
515
516
517
          public function setPaymentInput($value)
          {
              $this->paymentInput = $value;
          }
  
e8236f44   Yarik   test
518
519
          /**
           * Return array of Specializations in which the User works.
e8236f44   Yarik   test
520
521
           * @return ActiveQuery
           */
b95371cf   Yarik   test
522
523
524
525
526
527
          public function getSpecializations()
          {
              return $this->hasMany(Specialization::className(), [ 'specialization_id' => 'specialization_id' ])
                          ->viaTable('user_specialization', [ 'user_id' => 'id' ]);
          }
  
e8236f44   Yarik   test
528
529
          /**
           * Return array of User's blogs
e8236f44   Yarik   test
530
531
           * @return ActiveQuery
           */
376a557b   Administrator   09.02.16
532
533
534
535
536
          public function getBlog()
          {
              return $this->hasMany(Blog::className(), [ 'user_id' => 'id' ]);
          }
  
e8236f44   Yarik   test
537
538
          /**
           * Return array of User's jobs.
e8236f44   Yarik   test
539
540
           * @return ActiveQuery
           */
f6ea8941   Administrator   09.02.16
541
542
          public function getJobs()
          {
32ed90fd   Yarik   test
543
              return $this->hasMany(Job::className(), [ 'user_id' => 'id' ])
38ffb9db   Yarik   test
544
545
546
547
                          ->orderBy([
                              'current'    => SORT_DESC,
                              'date_start' => SORT_DESC,
                          ]);
f6ea8941   Administrator   09.02.16
548
549
          }
  
e8236f44   Yarik   test
550
551
          /**
           * Return ActiveRecord of current User's place of work.
e8236f44   Yarik   test
552
553
554
555
           * @return ActiveQuery
           */
          public function getCurrentJob()
          {
4c9663e0   Yarik   test
556
557
              return $this->hasOne(Job::className(), [ 'user_id' => 'id' ])
                          ->where([ 'current' => 1 ]);
e8236f44   Yarik   test
558
559
560
561
          }
  
          /**
           * Return array of User's specialization IDs
e8236f44   Yarik   test
562
563
           * @return integer[]
           */
b95371cf   Yarik   test
564
565
566
567
          public function getSpecializationInput()
          {
              return $this->getSpecializations()
                          ->asArray()
4c9663e0   Yarik   test
568
                          ->indexBy('specialization_id')
b95371cf   Yarik   test
569
570
571
                          ->column();
          }
  
e8236f44   Yarik   test
572
573
574
575
576
          /**
           * Setter which allow to set User's specializations for further saving to the DB.
           *
           * @param integer[] $value
           */
b95371cf   Yarik   test
577
578
579
580
          public function setSpecializationInput($value)
          {
              $this->specializationInput = $value;
          }
51e0a262   Yarik   test
581
  
e8236f44   Yarik   test
582
583
          /**
           * Return array of User's portfolios.
e8236f44   Yarik   test
584
585
           * @return ActiveQuery
           */
a02e2fdb   Yarik   test
586
587
588
589
590
          public function getPortfolios()
          {
              return $this->hasMany(Portfolio::className(), [ 'user_id' => 'id' ]);
          }
  
e8236f44   Yarik   test
591
592
          /**
           * Return array of User's projects.
e8236f44   Yarik   test
593
594
           * @return ActiveQuery
           */
a02e2fdb   Yarik   test
595
596
597
598
599
          public function getProjects()
          {
              return $this->hasMany(Project::className(), [ 'user_id' => 'id' ]);
          }
  
e8236f44   Yarik   test
600
601
          /**
           * Return array of company's Team members.
e8236f44   Yarik   test
602
603
           * @return ActiveQuery
           */
a02e2fdb   Yarik   test
604
605
606
607
608
          public function getTeams()
          {
              return $this->hasMany(Team::className(), [ 'user_id' => 'id' ]);
          }
  
e8236f44   Yarik   test
609
610
          /**
           * Return array of company's Vacancies.
e8236f44   Yarik   test
611
612
           * @return ActiveQuery
           */
a02e2fdb   Yarik   test
613
614
          public function getVacancies()
          {
4ed1f788   Yarik   test
615
616
              return $this->hasMany(Vacancy::className(), [ 'user_id' => 'id' ])
                          ->inverseOf('user');
a02e2fdb   Yarik   test
617
618
          }
  
be662d1f   Yarik   test
619
620
          /**
           * Return all user's galleries
be662d1f   Yarik   test
621
622
           * @return ActiveQuery
           */
2e35d6bd   Yarik   test
623
624
          public function getGalleries()
          {
38ffb9db   Yarik   test
625
626
627
628
629
630
631
632
633
634
              $portfolio_galleries = PortfolioGallery::find()
                                                     ->select('gallery_id')
                                                     ->asArray()
                                                     ->where([ 'user_id' => $this->id ])
                                                     ->column();
              return $this->hasMany(Gallery::className(), [ 'user_id' => 'id' ])
                          ->andWhere([
                              'not',
                              [ 'gallery_id' => $portfolio_galleries ],
                          ]);
2e35d6bd   Yarik   test
635
636
          }
  
be662d1f   Yarik   test
637
638
          /**
           * Return company info or user info according to user type
be662d1f   Yarik   test
639
640
           * @return ActiveQuery
           */
3dc20ff7   Administrator   24.02.16
641
642
          public function getOwner()
          {
4ed1f788   Yarik   test
643
              if($this->type == 2) {
3dc20ff7   Administrator   24.02.16
644
                  return $this->hasOne(CompanyInfo::className(), [ 'user_id' => 'id' ]);
4ed1f788   Yarik   test
645
646
              } else {
                  return $this->hasOne(UserInfo::className(), [ 'user_id' => 'id' ]);
3dc20ff7   Administrator   24.02.16
647
              }
3dc20ff7   Administrator   24.02.16
648
649
          }
  
be662d1f   Yarik   test
650
651
          /**
           * Return company name or user firstname and lastname according to user type
be662d1f   Yarik   test
652
653
           * @return string
           */
4ed1f788   Yarik   test
654
655
656
          public function getName()
          {
              if($this->type == 2) {
3ea37908   Administrator   01.03.16
657
                  return $this->companyInfo->name;
4ed1f788   Yarik   test
658
659
              } else {
                  return $this->firstname . ' ' . $this->lastname;
3ea37908   Administrator   01.03.16
660
              }
4ed1f788   Yarik   test
661
          }
3ea37908   Administrator   01.03.16
662
  
2fd40ee7   Yarik   test
663
          /**
be662d1f   Yarik   test
664
           * Return all comments to user
2fd40ee7   Yarik   test
665
666
           * @return ActiveQuery
           */
4ed1f788   Yarik   test
667
668
          public function getComments()
          {
2fd40ee7   Yarik   test
669
670
671
672
673
              return $this->hasMany(Comment::className(), [
                  'model_id' => 'id',
              ])
                          ->andWhere([
                              'comment.model' => $this->className(),
38ffb9db   Yarik   test
674
675
                          ])
                          ->orderBy([ 'date_update' => SORT_DESC ]);
2fd40ee7   Yarik   test
676
677
678
          }
  
          /**
be662d1f   Yarik   test
679
           * Return all ratings to user
2fd40ee7   Yarik   test
680
681
682
683
684
685
686
687
688
           * @return ActiveQuery
           */
          public function getCommentRating()
          {
              return $this->hasMany(Rating::className(), [ 'model_id' => 'comment_id' ])
                          ->via('comments')
                          ->andWhere([
                              'rating.model' => Comment::className(),
                          ]);
3dc20ff7   Administrator   24.02.16
689
690
          }
  
be662d1f   Yarik   test
691
692
693
          /**
           * Return user's rating<br>
           * <b>Available only for PostgreSQL</b>
be662d1f   Yarik   test
694
695
696
           * @return int
           * @throws InvalidConfigException
           */
4ed1f788   Yarik   test
697
698
699
700
701
          public function getRatingPG()
          {
              if(\Yii::$app->db->driverName != 'pgsql') {
                  throw new InvalidConfigException('This method is available only in PostgreSQL');
              }
2fd40ee7   Yarik   test
702
              return $this->getCommentRating()
5077a0ec   Yarik   test
703
                          ->select([ 'rating' => 'ROUND(SUM("rating"."value")/COUNT("rating"."rating_id")::numeric, 2)' ])
2fd40ee7   Yarik   test
704
705
706
707
708
709
710
                          ->andWhere([
                              'not',
                              [ 'rating.value' => NULL ],
                          ])
                          ->scalar();
          }
  
be662d1f   Yarik   test
711
712
          /**
           * Recalculate rating and write it to db.
be662d1f   Yarik   test
713
           * <b>Only for PostgreSQL</b>
be662d1f   Yarik   test
714
           * @see \common\models\User::getRatingPG()
be662d1f   Yarik   test
715
716
           * @throws InvalidConfigException
           */
2fd40ee7   Yarik   test
717
718
719
720
721
722
          public function updateRating()
          {
              if($rating = $this->getRatingPG()) {
                  $this->userInfo->rating = $rating;
                  $this->userInfo->save();
              }
4ed1f788   Yarik   test
723
          }
3dc20ff7   Administrator   24.02.16
724
  
be662d1f   Yarik   test
725
726
727
728
729
730
731
          public function getLastVisit()
          {
              return \Yii::$app->formatter->asRelativeTime($this->userInfo->date_visit);
          }
  
          /**
           * Return link to user personal page according to user type
be662d1f   Yarik   test
732
733
734
735
736
           * @return string
           */
          public function getLink($page = 'common')
          {
              if($this->type == 2) {
5077a0ec   Yarik   test
737
738
739
740
                  return Url::to([
                      'company/' . $page,
                      'company_id' => $this->id,
                  ]);
be662d1f   Yarik   test
741
              } else {
5077a0ec   Yarik   test
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
                  return Url::to([
                      'performer/' . $page,
                      'performer_id' => $this->id,
                  ]);
              }
          }
  
          public function getIsBookmarked($type = Bookmark::TYPE_PERFORMER)
          {
              if(!empty( \Yii::$app->user->identity )) {
                  if(!empty( $this->hasOne(Bookmark::className(), [ 'model_id' => 'id' ])
                                  ->andWhere([
                                      'model'   => $this->className(),
                                      'user_id' => \Yii::$app->user->getId(),
                                      'type'    => $type,
                                  ])
                                  ->one() )
                  ) {
                      return true;
                  } else {
                      return false;
                  }
              } else {
                  return false;
be662d1f   Yarik   test
766
767
768
              }
          }
  
3c618303   Yarik   test
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
          public function getBookmarks()
          {
              return $this->hasMany(Bookmark::className(), [ 'user_id' => 'id' ]);
          }
  
          public function getBookmarksPerformers()
          {
              return $this->hasMany(User::className(), [ 'id' => 'model_id' ])
                          ->viaTable('{{%bookmark}}', [ 'user_id' => 'id' ], function($query) {
                              /**
                               * @var ActiveQuery $query
                               */
                              $query->andWhere([
                                  'model' => User::className(),
                                  'type'  => Bookmark::TYPE_PERFORMER,
                              ]);
                          });
          }
  
          public function getBookmarksCustomers()
          {
              return $this->hasMany(User::className(), [ 'id' => 'model_id' ])
                          ->viaTable('{{%bookmark}}', [ 'user_id' => 'id' ], function($query) {
                              /**
                               * @var ActiveQuery $query
                               */
                              $query->andWhere([
                                  'model' => User::className(),
                                  'type'  => Bookmark::TYPE_CUSTOMER,
                              ]);
                          });
          }
  
          public function getBookmarksProjects()
          {
              return $this->hasMany(Project::className(), [ 'project_id' => 'model_id' ])
                          ->viaTable('{{%bookmark}}', [ 'user_id' => 'id' ], function($query) {
                              /**
                               * @var ActiveQuery $query
                               */
                              $query->andWhere([
                                  'model' => Project::className(),
                                  'type'  => Bookmark::TYPE_PROJECT,
                              ]);
                          });
          }
38a6e1dd   Yarik   test
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
  
          public function getBookmarksVacancies()
          {
              return $this->hasMany(Vacancy::className(), [ 'vacancy_id' => 'model_id' ])
                          ->viaTable('{{%bookmark}}', [ 'user_id' => 'id' ], function($query) {
                              /**
                               * @var ActiveQuery $query
                               */
                              $query->andWhere([
                                  'model' => Vacancy::className(),
                                  'type'  => Bookmark::TYPE_VACANCY,
                              ]);
                          });
          }
  
          public function getChatCount()
          {
              return Chat::find()
                         ->select('COUNT(*)')
                         ->where([
                             'or',
                             [ 'from_user' => $this->id ],
                             [ 'to_user' => $this->id ],
                         ])
                         ->scalar();
          }
32ed90fd   Yarik   test
841
  
236a608c   Yarik   test
842
843
844
845
846
847
848
849
850
851
852
853
854
          public function getNewMessagesCount()
          {
              $chats = Chat::find()
                           ->select([ 'chat_id' ])
                           ->where([
                               'or',
                               [ 'from_user' => $this->id ],
                               [ 'to_user' => $this->id ],
                           ])
                           ->column();
              return Message::find()->select(['chat_id'])->distinct()->where(['chat_id' => $chats, 'status' => Message::NEW_MESSAGE])->andWhere(['not', ['user_id' => $this->id]])->count();
          }
  
32ed90fd   Yarik   test
855
856
857
858
859
          public function getCommentProjects()
          {
              return $this->hasMany(CommentProject::className(), [ 'user_id' => 'id' ]);
          }
  
236a608c   Yarik   test
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
          public function getCommentProjectsActive()
          {
              return $this->getCommentProjects()
                          ->where([
                              'between',
                              'state',
                              CommentProject::STATE_NEW,
                              CommentProject::STATE_PERFORMER,
                          ])
                          ->andWhere([
                              'status' => [
                                  CommentProject::STATUS_ACTIVE,
                                  CommentProject::STATUS_ANONYMOUS,
                                  CommentProject::STATUS_PERSONAL,
                              ],
                          ]);
          }
  
32ed90fd   Yarik   test
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
          public function getChat($user_id)
          {
              return Chat::find()
                         ->where([
                             'or',
                             [ 'from_user' => $user_id, ],
                             [ 'to_user' => $user_id, ],
                         ])
                         ->andWhere([
                             'or',
                             [ 'from_user' => $this->id, ],
                             [ 'to_user' => $this->id, ],
                         ])
                         ->with('messages.user');
          }
76f36646   Yarik   test
893
894
895
  
          public function getIsOnline()
          {
38ffb9db   Yarik   test
896
              if(( time() - \Yii::$app->formatter->asTimestamp($this->userInfo->date_visit) ) < 1800) {
76f36646   Yarik   test
897
898
899
900
901
                  return true;
              } else {
                  return false;
              }
          }
51e0a262   Yarik   test
902
      }