Users.php 6.57 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
<?php

namespace Lu\LuAuth\Models;

use Lu\LuApi\Generators\Randomizer;
use TYPO3\CMS\Core\Utility\GeneralUtility;

/**
 * Class Users/ Makes requests for users.
 *
 * @author  Dainis Abols <dainis.abols@lu.lv>
 * @owner   University of Latvia
 * @version 3.0
 * @since   28.05.2018
 *
 * @package Lu\LuAuth\Models
 */
class Users
{
    /**
     * Extension configuration
     *
     * @array
     */
    public $conf;

    /**
     * Table name
     *
     * @var string
     */
    protected $table;

    /**
     * Set request type
     *
     * @var string
     */
    protected $type = 'be';

    /**
     * Username
     *
     * @var string
     */
    private $username;

    /**
     * Users constructor. Set initial usage.
     *
     * @param string $type 'be' or 'fe'
     */
    public function __construct(string $type)
    {
        // Set config value
        $this->conf = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Configuration\ExtensionConfiguration::class)->get('lu_auth');

        // Set used group
        if ($type == 'fe') {
            $this->table = 'fe_users';
        } else {
            $this->table = 'be_users';
        }

        // Set used group
        $this->type = $type == 'fe' ? 'fe' : 'be';
    }

    /**
     * Retrieve table name by type
     *
     * @param string $type
     *
     * @return string
     */
    static public function getTable(string $type)
    {
        $self = new self($type);

        return $self->table;
    }

    /**
     * Retrieve valid username
     *
     * @param $username
     *
     * @return array
     */
    public function getUserData($username, string $options = NULL): array
    {
        // Check if username given
        if (empty($username)) {
            return [];
        } else {
            $this->username = $username;
        }

        // Request user data from DB
        $queryBuilder = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Database\ConnectionPool::class)->getQueryBuilderForTable($this->table);
        $queryBuilder->select('*')
                     ->from($this->table)
                     ->where('disable = 0 AND deleted = 0')
                     ->andWhere($queryBuilder->expr()->eq('username', $queryBuilder->createNamedParameter($this->username)));
        $user = $queryBuilder->execute()->fetch();

        // Check if options
        if (empty($user) && $options == 'activate') {
            // Update user and refetch, if something updated
            $result = $this->activateUser();
            if ($result) {
                $user = self::getUserData($username);
            }
        }

        // Return user
        return empty($user) ? [] : $user;
    }

    /**
     * Activate user
     *
     * @return array|bool
     */
    public function activateUser()
    {
        // Check for where parameters and username
        if (empty($this->username)) {
            return [];
        }

        // Update user data in DB
        $queryBuilder = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Database\ConnectionPool::class)->getQueryBuilderForTable($this->table);
        $queryBuilder->update($this->table)
                     ->where($queryBuilder->expr()->eq('username', $queryBuilder->createNamedParameter($this->username)))
                     ->set('disable', '0')
                     ->set('deleted', '0');
        $result = $queryBuilder->execute();

        // Return affected rows, if any
        return $result;
    }

    /**
     * Update user data
     *
     * @param $user
     *
     * @return array
     */
    public function updateUser($user)
    {
        // Pre-set used models
        $GroupsModel = new Groups($this->type);

        // @TODO: Log event here
        //$this->writelog(255,3,3,2, "Importing user %s!", array($this->remoteUser));

        // Get groups string
        $arrGroups = $GroupsModel->getGroupsData($user['username']);

        $user = [
            'tstamp'     => time(),
            'email'      => $user['email'] ?? '',
            'username'   => $user['username'],
            'name'       => $user['name'] ?? '',
            'first_name' => $user['first_name'] ?? '',
            'last_name'  => $user['last_name'] ?? '',
            'telephone'  => $user['telephone'] ?? '',
            'address'    => $user['address'] ?? '',
            'usergroup'  => $arrGroups,
        ];

        // Update database
        $queryBuilder = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Database\ConnectionPool::class)->getQueryBuilderForTable($this->table);
        $queryBuilder->update($this->table);
        $queryBuilder->where($queryBuilder->expr()->eq('username', $queryBuilder->createNamedParameter($this->username)));

        // Set user fields. There's got to be a better way >.<
        foreach ($user as $key => $value) {
            $queryBuilder->set($key, $value);
        }

        $queryBuilder->execute();

        // Request new user and return
        return $this->getUserData($user['username']);
    }

    /**
     * Create new user and return its data
     *
     * @param array $user
     *
     * @return array
     */
    public function insertUser($user = [])
    {
        // Pre-set used models
        $ApiRand     = new Randomizer();
        $GroupsModel = new Groups($this->type);

        // @TODO: Log event here
        //$this->writelog(255,3,3,2, "Importing user %s!", array($this->remoteUser));

        // Get password string
        $password = $ApiRand->getRandomString(32);
        $password = json_decode($password);

        // Get groups string
        $arrGroups = $GroupsModel->getGroupsData($user['username']);

        $user = [
            'crdate'     => time(),
            'tstamp'     => time(),
            'pid'        => $this->conf['extraStoragePid'],
            'password'   => $password->data,
            'email'      => $user['email'],
            'username'   => $user['username'],
            'name'       => $user['name'],
            'first_name' => $user['first_name'],
            'last_name'  => $user['last_name'],
            'telephone'  => $user['telephone'],
            'address'    => (string)$user['address'],
            'usergroup'  => $arrGroups,
        ];

        // Remove empty values
        foreach($user as $k=>$item) {
            if (empty($item)) {
                unset($user[$k]);
            }
        }

        // Save to database
        $queryBuilder = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Database\ConnectionPool::class)->getQueryBuilderForTable($this->table);
        $queryBuilder->insert($this->table)->values($user)->execute();

        // Request new user and return
        return $this->getUserData($user['username']);
    }
}