Completed
Push — master ( 7d233a...8ee6e7 )
by Dmitry
12:15
created

src/storage/Client.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
/**
3
 * HIAM module for MRDP database compatibility
4
 *
5
 * @link      https://github.com/hiqdev/hiam-mrdp
6
 * @package   hiam-mrdp
7
 * @license   BSD-3-Clause
8
 * @copyright Copyright (c) 2016, HiQDev (http://hiqdev.com/)
9
 */
10
11
namespace hiam\mrdp\storage;
12
13
use Yii;
14
use yii\base\InvalidConfigException;
15
use yii\db\Exception;
16
use yii\db\Expression;
17
18
/**
19
 * Client model.
20
 *
21
 * @property integer $obj_id PK
22
 * @property integer $id synced with obj_id
23
 * @property integer $seller_id
24
 * @property string $password
25
 * @property string $email
26
 */
27
class Client extends \yii\db\ActiveRecord
28
{
29
    public $type;
30
    public $state;
31
    public $roles;
32
    public $seller;
33
    public $username;
34
    public $last_name;
35
    public $first_name;
36
    public $send_me_news;
37
38
    public $email_confirmed;
39
    public $allowed_ips;
40
    public $totp_secret;
41
42
    public $password_hash;
43
44
    public static function tableName()
45
    {
46
        return '{{zclient}}';
47
    }
48
49
    public static function primaryKey()
50
    {
51
        return ['obj_id'];
52
    }
53
54
    public function rules()
55
    {
56
        return [
57
            [['username', 'email', 'password', 'first_name', 'last_name'], 'trim'],
58
            [['username', 'email'], 'filter', 'filter' => 'strtolower'],
59
            [['seller_id'], 'integer'],
60
            [['state'], 'trim'],
61
            [['email_confirmed', 'allowed_ips', 'totp_secret'], 'trim'],
62
            ['send_me_news', 'boolean'],
63
        ];
64
    }
65
66
    public function init()
67
    {
68
        parent::init();
69
        $this->on(static::EVENT_BEFORE_INSERT, [$this, 'onBeforeInsert']);
70
        $this->on(static::EVENT_BEFORE_UPDATE, [$this, 'onBeforeSave']);
71
        $this->on(static::EVENT_AFTER_INSERT,  [$this, 'onAfterSave']);
72
        $this->on(static::EVENT_AFTER_UPDATE,  [$this, 'onAfterSave']);
73
    }
74
75
    public function onBeforeInsert()
76
    {
77
        $seller = static::findOne(['username' => Yii::$app->params['user.seller']]);
78
        $this->login = $this->username ?: $this->email;
79
        $this->seller_id = $seller->id;
80
        $this->onBeforeSave();
81
    }
82
83
    public function onBeforeSave()
84
    {
85
        if (empty($this->password)) {
86
            unset($this->password);
87
        }
88
        if (!empty($this->state)) {
89
            $this->state_id = new Expression(
90
                "zref_id('state,client,{$this->state}')"
91
            );
92
        }
93
        if ($this->email_confirmed) {
94
            $double = static::findOne([ 'email' => $this->email_confirmed ]);
95
            if (empty($double) || $this->obj_id === $double->obj_id) {
96
                $this->email = $this->email_confirmed;
97
            }
98
            $this->saveValue('contact:email_new', '');
99
            $this->saveValue('contact:email_confirmed', $this->email_confirmed);
100
            $this->saveValue('contact:email_confirm_date', new Expression("date_trunc('second', now()::timestamp)::text"));
101
        }
102
    }
103
104
    public function onAfterSave()
105
    {
106
        $this->id = $this->id ?: $this->getAgain()->id;
107
        $this->type = $this->type ?: $this->getAgain()->type;
108
        $send_news = $this->send_me_news === '0' ? '' : 1;
109
110
        $contact = Contact::findOne($this->id);
111
        $contact->setAttributes($this->getAttributes($contact->safeAttributes()));
112
        $contact->save();
113
        $this->saveValue('client,access:totp_secret', $this->totp_secret);
114
        $this->saveValue('client,access:allowed_ips', $this->allowed_ips);
115
        $this->saveValue('login_ips:panel', $this->allowed_ips);
116
117
        $this->saveValue('contact:policy_consent', 1);
118
        $this->saveValue('contact:gdpr_consent', 1);
119
        $this->saveValue('client,mailing:commercial', $send_news);
120
        $this->saveValue('client,mailing:newsletters', $send_news);
121
    }
122
123
    protected $_again;
124
125
    public function getAgain()
126
    {
127
        /// XXX this crutch is needed bacause we use `zclient` view (not table)
128
        /// XXX and yii ActiveRecord doesn't populate model properly in this case
129
        if ($this->_again === null) {
130
            $this->_again = static::find()->whereUsername($this->username)->one();
131
        }
132
133
        return $this->_again;
134
    }
135
136
    public function saveValue($prop, $value)
137
    {
138
        $params = [
139
            'id' => $this->id,
140
            'prop' => $prop,
141
            'value' => $value,
142
        ];
143
        $sub = ':value';
144
        if ($value instanceof Expression) {
145
            $sub = (string)$value;
146
            unset($params['value']);
147
        }
148
        self::getDb()->createCommand("SELECT set_value(:id,:prop,$sub)", $params)->execute();
149
    }
150
151
    public static function find()
152
    {
153
        return new ClientQuery(get_called_class());
154
    }
155
156
    public function setId($value)
157
    {
158
        $this->obj_id = $value;
159
    }
160
161
    public function getId()
162
    {
163
        return $this->obj_id;
164
    }
165
166
    public function getSeller_id()
167
    {
168
        return $this->reseller_id;
169
    }
170
171
    /**
172
     * {@inheritdoc}
173
     */
174
    public function getPasswordHash()
175
    {
176
        return $this->password_hash;
177
    }
178
179
    public function getPassword_hash()
180
    {
181
        return $this->getAuthKey();
182
    }
183
184
    /**
185
     * @param string $email
186
     * @return bool
187
     */
188
    public function updateEmail(string $email): bool
189
    {
190
        if ($this->username) {
191
            try {
192
                if (Yii::$app->db->createCommand()
193
                    ->update('zclient', ['email' => $email], 'login = :login')
194
                    ->bindValue(':login', $this->username)
195
                    ->execute()) {
196
                    return true;
197
                }
198
            } catch (Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
199
            }
200
        }
201
202
        return false;
203
    }
204
205
    protected static function filterCondition(array $condition, array $aliases = [])
206
    {
207
        /// XXX skip condition filtering
208
        return $condition;
209
    }
210
}
211