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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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
<?php
namespace ProcessMaker\BusinessModel\Role;

use Configurations;
use Criteria;
use Exception;
use G;
use ProcessMaker\BusinessModel\Process;
use ProcessMaker\BusinessModel\Role;
use ProcessMaker\BusinessModel\Validator;
use RBAC;
use RbacUsersPeer;
use ResultSet;
use Roles;
use UsersRolesPeer;

class User
{
    private $arrayFieldDefinition = array(
        "ROL_UID" => array("type" => "string", "required" => false, "empty" => false, "defaultValues" => array(), "fieldNameAux" => "roleUid"),
        "USR_UID" => array("type" => "string", "required" => true,  "empty" => false, "defaultValues" => array(), "fieldNameAux" => "userUid")
    );

    private $formatFieldNameInUppercase = true;

    private $arrayFieldNameForException = array(
        "filter" => "FILTER",
        "start"  => "START",
        "limit"  => "LIMIT"
    );

    /**
     * Constructor of the class
     *
     * @return void
     */
    public function __construct()
    {
        try {
            foreach ($this->arrayFieldDefinition as $key => $value) {
                $this->arrayFieldNameForException[$value["fieldNameAux"]] = $key;
            }
        } catch (Exception $e) {
            throw $e;
        }
    }

    /**
     * Set the format of the fields name (uppercase, lowercase)
     *
     * @param bool $flag Value that set the format
     * @return void
     */
    public function setFormatFieldNameInUppercase($flag)
    {
        try {
            $this->formatFieldNameInUppercase = $flag;

            $this->setArrayFieldNameForException($this->arrayFieldNameForException);
        } catch (Exception $e) {
            throw $e;
        }
    }

    /**
     * Set exception messages for fields
     *
     * @param array $arrayData Data with the fields
     * @return void
     */
    public function setArrayFieldNameForException(array $arrayData)
    {
        try {
            foreach ($arrayData as $key => $value) {
                $this->arrayFieldNameForException[$key] = $this->getFieldNameByFormatFieldName($value);
            }
        } catch (Exception $e) {
            throw $e;
        }
    }

    /**
     * Get the name of the field according to the format
     *
     * @param string $fieldName Field name
     * @return string Return the field name according the format
     */
    public function getFieldNameByFormatFieldName($fieldName)
    {
        try {
            return ($this->formatFieldNameInUppercase)? strtoupper($fieldName) : strtolower($fieldName);
        } catch (Exception $e) {
            throw $e;
        }
    }

    /**
     * Verify if it's assigned the User to Role
     *
     * @param string $roleUid               Unique id of Role
     * @param string $userUid               Unique id of User
     * @param string $fieldNameForException Field name for the exception
     * @return void Throw exception if it's assigned the User to Role
     */
    public function throwExceptionIfItsAssignedUserToRole($roleUid, $userUid, $fieldNameForException)
    {
        try {
            $obj = UsersRolesPeer::retrieveByPK($userUid, $roleUid);

            if (!is_null($obj)) {
                throw new Exception(G::LoadTranslation("ID_ROLE_USER_IS_ALREADY_ASSIGNED", array($fieldNameForException, $userUid)));
            }
        } catch (Exception $e) {
            throw $e;
        }
    }

    /**
     * Verify if not it's assigned the User to Role
     *
     * @param string $roleUid               Unique id of Role
     * @param string $userUid               Unique id of User
     * @param string $fieldNameForException Field name for the exception
     * @return void Throw exception if not it's assigned the User to Role
     */
    public function throwExceptionIfNotItsAssignedUserToRole($roleUid, $userUid, $fieldNameForException)
    {
        try {
            $obj = UsersRolesPeer::retrieveByPK($userUid, $roleUid);

            if (is_null($obj)) {
                throw new Exception(G::LoadTranslation("ID_ROLE_USER_IS_NOT_ASSIGNED", array($fieldNameForException, $userUid)));
            }
        } catch (Exception $e) {
            throw $e;
        }
    }

    /**
     * Assign User to Role
     *
     * @param string $roleUid   Unique id of Role
     * @param array  $arrayData Data
     * @return array Return data of the User assigned to Role
     */
    public function create($roleUid, array $arrayData)
    {
        try {
            //Verify data
            $process = new Process();
            $validator = new Validator();

            $validator->throwExceptionIfDataIsEmpty($arrayData, "\$arrayData");

            //Set data
            $arrayData = array_change_key_case($arrayData, CASE_UPPER);

            unset($arrayData["ROL_UID"]);

            //Verify data
            $role = new Role();

            $role->throwExceptionIfNotExistsRole($roleUid, $this->arrayFieldNameForException["roleUid"]);

            $process->throwExceptionIfDataNotMetFieldDefinition($arrayData, $this->arrayFieldDefinition, $this->arrayFieldNameForException, true);

            $process->throwExceptionIfNotExistsUser($arrayData["USR_UID"], $this->arrayFieldNameForException["userUid"]);

            $this->throwExceptionIfItsAssignedUserToRole($roleUid, $arrayData["USR_UID"], $this->arrayFieldNameForException["userUid"]);

            if ($arrayData["USR_UID"] == "00000000000000000000000000000001") {
                throw new Exception(G::LoadTranslation("ID_ADMINISTRATOR_ROLE_CANT_CHANGED"));
            }

            //Create
            $role = new Roles();

            $arrayData = array_merge(array("ROL_UID" => $roleUid), $arrayData);

            $role->assignUserToRole($arrayData);

            //Return
            if (!$this->formatFieldNameInUppercase) {
                $arrayData = array_change_key_case($arrayData, CASE_LOWER);
            }

            return $arrayData;
        } catch (Exception $e) {
            throw $e;
        }
    }

    /**
     * Unassign User of the Role
     *
     * @param string $roleUid Unique id of Role
     * @param string $userUid Unique id of User
     * @return void
     */
    public function delete($roleUid, $userUid)
    {
        try {
            //Verify data
            $process = new Process();
            $role = new Role();

            $role->throwExceptionIfNotExistsRole($roleUid, $this->arrayFieldNameForException["roleUid"]);

            $process->throwExceptionIfNotExistsUser($userUid, $this->arrayFieldNameForException["userUid"]);

            $this->throwExceptionIfNotItsAssignedUserToRole($roleUid, $userUid, $this->arrayFieldNameForException["userUid"]);

            if ($userUid == "00000000000000000000000000000001") {
                throw new Exception(G::LoadTranslation("ID_ADMINISTRATOR_ROLE_CANT_CHANGED"));
            }

            //Delete
            $role = new Roles();

            $role->deleteUserRole($roleUid, $userUid);
        } catch (Exception $e) {
            throw $e;
        }
    }

    /**
     * Get data of a User from a record
     *
     * @param array $record Record
     * @return array Return an array with data User
     */
    public function getUserDataFromRecord(array $record)
    {
        try {
            return array(
                $this->getFieldNameByFormatFieldName("USR_UID")       => $record["USR_UID"],
                $this->getFieldNameByFormatFieldName("USR_USERNAME")  => $record["USR_USERNAME"],
                $this->getFieldNameByFormatFieldName("USR_FIRSTNAME") => $record["USR_FIRSTNAME"] . "",
                $this->getFieldNameByFormatFieldName("USR_LASTNAME")  => $record["USR_LASTNAME"] . "",
                $this->getFieldNameByFormatFieldName("USR_STATUS")    => ($record["USR_STATUS"] . "" == "1")? "ACTIVE" : "INACTIVE"
            );
        } catch (Exception $e) {
            throw $e;
        }
    }

    /**
     * Get all Users of a Role
     *
     * @param string $roleUid         Unique id of Role
     * @param string $option          Option (USERS, AVAILABLE-USERS)
     * @param array  $arrayFilterData Data of the filters
     * @param string $sortField       Field name to sort
     * @param string $sortDir         Direction of sorting (ASC, DESC)
     * @param int    $start           Start
     * @param int    $limit           Limit
     * @return array Return an array with all Users of a Role
     */
    public function getUsers($roleUid, $option, array $arrayFilterData = null, $sortField = null, $sortDir = null, $start = null, $limit = null)
    {
        try {
            $arrayUser = array();

            $numRecTotal = 0;

            //Verify data and Set variables
            $flagFilter = !is_null($arrayFilterData) && is_array($arrayFilterData) && isset($arrayFilterData['filter']);

            $process = new Process();
            $role    = new Role();

            $role->throwExceptionIfNotExistsRole($roleUid, $this->arrayFieldNameForException["roleUid"]);

            $process->throwExceptionIfDataNotMetFieldDefinition(
                array("OPTION" => $option),
                array("OPTION" => array("type" => "string", "required" => true, "empty" => false, "defaultValues" => array("USERS", "AVAILABLE-USERS"), "fieldNameAux" => "option")),
                array("option" => "\$option"),
                true
            );

            $process->throwExceptionIfDataNotMetPagerVarDefinition(array("start" => $start, "limit" => $limit), $this->arrayFieldNameForException);

            //Set variables
            $filterName = 'filter';

            if ($flagFilter) {
                $arrayAux = [
                    ''      => 'filter',
                    'LEFT'  => 'lfilter',
                    'RIGHT' => 'rfilter'
                ];

                $filterName = $arrayAux[
                    (isset($arrayFilterData['filterOption']))? $arrayFilterData['filterOption'] : ''
                ];
            }

            //Get data
            if (!is_null($limit) && (string)($limit) == '0') {
                return [
                    'total'     => $numRecTotal,
                    'start'     => (int)((!is_null($start))? $start : 0),
                    'limit'     => (int)((!is_null($limit))? $limit : 0),
                    $filterName => ($flagFilter)? $arrayFilterData['filter'] : '',
                    'data'      => $arrayUser
                ];
            }

            //Query
            $criteria = new Criteria('rbac');

            $criteria->addSelectColumn(RbacUsersPeer::USR_UID);
            $criteria->addSelectColumn(RbacUsersPeer::USR_USERNAME);
            $criteria->addSelectColumn(RbacUsersPeer::USR_FIRSTNAME);
            $criteria->addSelectColumn(RbacUsersPeer::USR_LASTNAME);
            $criteria->addSelectColumn(RbacUsersPeer::USR_STATUS);

            $criteria->addJoin(RbacUsersPeer::USR_UID, UsersRolesPeer::USR_UID, Criteria::LEFT_JOIN);

            $criteria->add(RbacUsersPeer::USR_USERNAME, '', Criteria::NOT_EQUAL);

            switch ($option) {
                case "USERS":
                    $criteria->add(UsersRolesPeer::ROL_UID, $roleUid, Criteria::EQUAL);
                    break;
                case "AVAILABLE-USERS":
                    $criteria->add(UsersRolesPeer::ROL_UID, $roleUid, Criteria::NOT_EQUAL);
                    $criteria->add(RbacUsersPeer::USR_UID, [RBAC::GUEST_USER_UID], Criteria::NOT_IN);
                    break;
            }

            if ($flagFilter && trim($arrayFilterData['filter']) != '') {
                $arraySearch = [
                    ''      => '%' . $arrayFilterData['filter'] . '%',
                    'LEFT'  => $arrayFilterData['filter'] . '%',
                    'RIGHT' => '%' . $arrayFilterData['filter']
                ];

                $search = $arraySearch[
                    (isset($arrayFilterData['filterOption']))? $arrayFilterData['filterOption'] : ''
                ];

                $criteria->add(
                    $criteria->getNewCriterion(RbacUsersPeer::USR_USERNAME,  $search, Criteria::LIKE)->addOr(
                    $criteria->getNewCriterion(RbacUsersPeer::USR_FIRSTNAME, $search, Criteria::LIKE)->addOr(
                    $criteria->getNewCriterion(RbacUsersPeer::USR_LASTNAME,  $search, Criteria::LIKE)))
                );
            }

            //Number records total
            $numRecTotal = RbacUsersPeer::doCount($criteria);

            //Query
            $conf = new Configurations();
            $sortFieldDefault = RbacUsersPeer::TABLE_NAME . '.' . $conf->userNameFormatGetFirstFieldByUsersTable();

            if (!is_null($sortField) && trim($sortField) != '') {
                $sortField = strtoupper($sortField);

                if (in_array(RbacUsersPeer::TABLE_NAME . '.' . $sortField, $criteria->getSelectColumns())) {
                    $sortField = RbacUsersPeer::TABLE_NAME . '.' . $sortField;
                } else {
                    $sortField = $sortFieldDefault;
                }
            } else {
                $sortField = $sortFieldDefault;
            }

            if (!is_null($sortDir) && trim($sortDir) != "" && strtoupper($sortDir) == "DESC") {
                $criteria->addDescendingOrderByColumn($sortField);
            } else {
                $criteria->addAscendingOrderByColumn($sortField);
            }

            if (!is_null($start)) {
                $criteria->setOffset((int)($start));
            }

            if (!is_null($limit)) {
                $criteria->setLimit((int)($limit));
            }

            $rsCriteria = RbacUsersPeer::doSelectRS($criteria);
            $rsCriteria->setFetchmode(ResultSet::FETCHMODE_ASSOC);

            while ($rsCriteria->next()) {
                $row = $rsCriteria->getRow();

                $arrayUser[] = $this->getUserDataFromRecord($row);
            }

            //Return
            return [
                'total'     => $numRecTotal,
                'start'     => (int)((!is_null($start))? $start : 0),
                'limit'     => (int)((!is_null($limit))? $limit : 0),
                $filterName => ($flagFilter)? $arrayFilterData['filter'] : '',
                'data'      => $arrayUser
            ];
        } catch (Exception $e) {
            throw $e;
        }
    }
}