-
Notifications
You must be signed in to change notification settings - Fork 54
Expand file tree
/
Copy pathProvisioningService.php
More file actions
522 lines (446 loc) · 21.4 KB
/
ProvisioningService.php
File metadata and controls
522 lines (446 loc) · 21.4 KB
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
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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
<?php
/**
* SPDX-FileCopyrightText: 2022 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace OCA\UserOIDC\Service;
use OCA\UserOIDC\AppInfo\Application;
use OCA\UserOIDC\Db\UserMapper;
use OCA\UserOIDC\Event\AttributeMappedEvent;
use OCP\Accounts\IAccountManager;
use OCP\AppFramework\Db\DoesNotExistException;
use OCP\AppFramework\Db\MultipleObjectsReturnedException;
use OCP\DB\Exception;
use OCP\EventDispatcher\IEventDispatcher;
use OCP\IAvatarManager;
use OCP\IConfig;
use OCP\IGroupManager;
use OCP\Image;
use OCP\ISession;
use OCP\IUser;
use OCP\IUserManager;
use OCP\User\Events\UserChangedEvent;
use Psr\Log\LoggerInterface;
use Throwable;
class ProvisioningService {
public function __construct(
private LocalIdService $idService,
private ProviderService $providerService,
private UserMapper $userMapper,
private IUserManager $userManager,
private IGroupManager $groupManager,
private IEventDispatcher $eventDispatcher,
private LoggerInterface $logger,
private IAccountManager $accountManager,
private NetworkService $networkService,
private IAvatarManager $avatarManager,
private IConfig $config,
private ISession $session,
) {
}
public function hasOidcUserProvisitioned(string $userId): bool {
try {
$this->userMapper->getUser($userId);
return true;
} catch (DoesNotExistException|MultipleObjectsReturnedException) {
}
return false;
}
/**
* @param string $tokenUserId
* @param int $providerId
* @param object $idTokenPayload
* @param IUser|null $existingLocalUser
* @return IUser|null
* @throws Exception
*/
public function provisionUser(string $tokenUserId, int $providerId, object $idTokenPayload, ?IUser $existingLocalUser = null): ?IUser {
// user data potentially later used by globalsiteselector if user_oidc is used with global scale
$oidcGssUserData = get_object_vars($idTokenPayload);
// get name/email/quota information from the token itself
$emailAttribute = $this->providerService->getSetting($providerId, ProviderService::SETTING_MAPPING_EMAIL, 'email');
$email = $idTokenPayload->{$emailAttribute} ?? null;
$displaynameAttribute = $this->providerService->getSetting($providerId, ProviderService::SETTING_MAPPING_DISPLAYNAME, 'name');
$userName = $idTokenPayload->{$displaynameAttribute} ?? null;
$quotaAttribute = $this->providerService->getSetting($providerId, ProviderService::SETTING_MAPPING_QUOTA, 'quota');
$quota = $idTokenPayload->{$quotaAttribute} ?? null;
$genderAttribute = $this->providerService->getSetting($providerId, ProviderService::SETTING_MAPPING_GENDER, 'gender');
$gender = $idTokenPayload->{$genderAttribute} ?? null;
$addressAttribute = $this->providerService->getSetting($providerId, ProviderService::SETTING_MAPPING_ADDRESS, 'address');
$address = $idTokenPayload->{$addressAttribute} ?? null;
$postalcodeAttribute = $this->providerService->getSetting($providerId, ProviderService::SETTING_MAPPING_POSTALCODE, 'postal_code');
$postalcode = $idTokenPayload->{$postalcodeAttribute} ?? null;
$streetAttribute = $this->providerService->getSetting($providerId, ProviderService::SETTING_MAPPING_STREETADDRESS, 'street_address');
$street = $idTokenPayload->{$streetAttribute} ?? null;
$localityAttribute = $this->providerService->getSetting($providerId, ProviderService::SETTING_MAPPING_LOCALITY, 'locality');
$locality = $idTokenPayload->{$localityAttribute} ?? null;
$regionAttribute = $this->providerService->getSetting($providerId, ProviderService::SETTING_MAPPING_REGION, 'region');
$region = $idTokenPayload->{$regionAttribute} ?? null;
$countryAttribute = $this->providerService->getSetting($providerId, ProviderService::SETTING_MAPPING_COUNTRY, 'country');
$country = $idTokenPayload->{$countryAttribute} ?? null;
$websiteAttribute = $this->providerService->getSetting($providerId, ProviderService::SETTING_MAPPING_WEBSITE, 'website');
$website = $idTokenPayload->{$websiteAttribute} ?? null;
$avatarAttribute = $this->providerService->getSetting($providerId, ProviderService::SETTING_MAPPING_AVATAR, 'avatar');
$avatar = $idTokenPayload->{$avatarAttribute} ?? null;
$phoneAttribute = $this->providerService->getSetting($providerId, ProviderService::SETTING_MAPPING_PHONE, 'phone_number');
$phone = $idTokenPayload->{$phoneAttribute} ?? null;
$twitterAttribute = $this->providerService->getSetting($providerId, ProviderService::SETTING_MAPPING_TWITTER, 'twitter');
$twitter = $idTokenPayload->{$twitterAttribute} ?? null;
$fediverseAttribute = $this->providerService->getSetting($providerId, ProviderService::SETTING_MAPPING_FEDIVERSE, 'fediverse');
$fediverse = $idTokenPayload->{$fediverseAttribute} ?? null;
$organisationAttribute = $this->providerService->getSetting($providerId, ProviderService::SETTING_MAPPING_ORGANISATION, 'organisation');
$organisation = $idTokenPayload->{$organisationAttribute} ?? null;
$roleAttribute = $this->providerService->getSetting($providerId, ProviderService::SETTING_MAPPING_ROLE, 'role');
$role = $idTokenPayload->{$roleAttribute} ?? null;
$headlineAttribute = $this->providerService->getSetting($providerId, ProviderService::SETTING_MAPPING_HEADLINE, 'headline');
$headline = $idTokenPayload->{$headlineAttribute} ?? null;
$biographyAttribute = $this->providerService->getSetting($providerId, ProviderService::SETTING_MAPPING_BIOGRAPHY, 'biography');
$biography = $idTokenPayload->{$biographyAttribute} ?? null;
$event = new AttributeMappedEvent(ProviderService::SETTING_MAPPING_UID, $idTokenPayload, $tokenUserId);
$this->eventDispatcher->dispatchTyped($event);
// use an existing user (from another backend) when soft auto provisioning is enabled
if ($existingLocalUser !== null) {
$user = $existingLocalUser;
} else {
// if disable_account_creation is true, user_oidc should not create any user
// so we just exit
// but it will accept connection from users it might have created in the past (before disable_account_creation was enabled)
$oidcSystemConfig = $this->config->getSystemValue('user_oidc', []);
$isUserCreationDisabled = isset($oidcSystemConfig['disable_account_creation'])
&& in_array($oidcSystemConfig['disable_account_creation'], [true, 'true', 1, '1'], true);
if ($isUserCreationDisabled) {
return null;
}
$backendUser = $this->userMapper->getOrCreate($providerId, $event->getValue() ?? '');
$this->logger->debug('User obtained from the OIDC user backend: ' . $backendUser->getUserId());
$user = $this->userManager->get($backendUser->getUserId());
if ($user === null) {
return null;
}
}
$account = $this->accountManager->getAccount($user);
$scope = 'v2-local';
// Update displayname
if (isset($userName)) {
$newDisplayName = mb_substr($userName, 0, 255);
$event = new AttributeMappedEvent(ProviderService::SETTING_MAPPING_DISPLAYNAME, $idTokenPayload, $newDisplayName);
} else {
$event = new AttributeMappedEvent(ProviderService::SETTING_MAPPING_DISPLAYNAME, $idTokenPayload);
}
$this->eventDispatcher->dispatchTyped($event);
$this->logger->debug('Displayname mapping event dispatched');
if ($event->hasValue() && $event->getValue() !== null && $event->getValue() !== '') {
$oidcGssUserData[$displaynameAttribute] = $event->getValue();
$newDisplayName = $event->getValue();
if ($existingLocalUser === null) {
$oldDisplayName = $backendUser->getDisplayName();
if ($newDisplayName !== $oldDisplayName) {
$backendUser->setDisplayName($newDisplayName);
$this->userMapper->update($backendUser);
}
// 2 reasons why we should update the display name: It does not match the one
// - of our backend
// - returned by the user manager (outdated one before the fix in https://github.com/nextcloud/user_oidc/pull/530)
if ($newDisplayName !== $oldDisplayName || $newDisplayName !== $user->getDisplayName()) {
$this->eventDispatcher->dispatchTyped(new UserChangedEvent($user, 'displayName', $newDisplayName, $oldDisplayName));
}
} else {
$oldDisplayName = $user->getDisplayName();
if ($newDisplayName !== $oldDisplayName) {
$user->setDisplayName($newDisplayName);
if ($user->getBackendClassName() === Application::APP_ID) {
$backendUser = $this->userMapper->getOrCreate($providerId, $user->getUID());
$backendUser->setDisplayName($newDisplayName);
$this->userMapper->update($backendUser);
}
$this->eventDispatcher->dispatchTyped(new UserChangedEvent($user, 'displayName', $newDisplayName, $oldDisplayName));
}
}
}
// Update e-mail
$event = new AttributeMappedEvent(ProviderService::SETTING_MAPPING_EMAIL, $idTokenPayload, $email);
$this->eventDispatcher->dispatchTyped($event);
$this->logger->debug('Email mapping event dispatched');
if ($event->hasValue() && $event->getValue() !== null && $event->getValue() !== '') {
$oidcGssUserData[$emailAttribute] = $event->getValue();
$user->setSystemEMailAddress($event->getValue());
}
// Update the quota
$event = new AttributeMappedEvent(ProviderService::SETTING_MAPPING_QUOTA, $idTokenPayload, $quota);
$this->eventDispatcher->dispatchTyped($event);
$this->logger->debug('Quota mapping event dispatched');
if ($event->hasValue() && $event->getValue() !== null && $event->getValue() !== '') {
$oidcGssUserData[$quotaAttribute] = $event->getValue();
$user->setQuota($event->getValue());
}
// Update groups
if ($this->providerService->getSetting($providerId, ProviderService::SETTING_GROUP_PROVISIONING, '0') === '1') {
$groups = $this->provisionUserGroups($user, $providerId, $idTokenPayload);
// for gss
if ($groups !== null) {
$groupIds = array_map(static function ($group) {
return $group->gid;
}, $groups);
$groupsAttribute = $this->providerService->getSetting($providerId, ProviderService::SETTING_MAPPING_GROUPS, 'groups');
$oidcGssUserData[$groupsAttribute] = $groupIds;
}
}
// Update the phone number
$event = new AttributeMappedEvent(ProviderService::SETTING_MAPPING_PHONE, $idTokenPayload, $phone);
$this->eventDispatcher->dispatchTyped($event);
$this->logger->debug('Phone mapping event dispatched');
if ($event->hasValue()) {
$account->setProperty('phone', $event->getValue(), $scope, '1', '');
}
$addressParts = null;
if (is_object($address)) {
// Update the location/address
$addressArray = json_decode(json_encode($address), true);
if (is_array($addressArray)
&& (isset($addressArray[$streetAttribute]) || isset($addressArray[$postalcodeAttribute]) || isset($addressArray[$localityAttribute])
|| isset($addressArray[$regionAttribute]) || isset($addressArray[$countryAttribute]))
) {
$addressParts = [
$addressArray[$streetAttribute] ?? '',
($addressArray[$postalcodeAttribute] ?? '') . ' ' . ($addressArray[$localityAttribute] ?? ''),
$addressArray[$regionAttribute] ?? '',
$addressArray[$countryAttribute] ?? '',
];
} else {
$address = null;
}
} elseif ($street !== null || $postalcode !== null || $locality !== null || $region !== null || $country !== null) {
// Concatenate the address components
$addressParts = [
$street ?? '',
($postalcode ?? '') . ' ' . ($locality ?? ''),
$region ?? '',
$country ?? '',
];
}
if ($addressParts !== null) {
// concatenate them back together into a string and remove unused ', '
$address = str_replace(' ', ' ', implode(', ', $addressParts));
}
$event = new AttributeMappedEvent(ProviderService::SETTING_MAPPING_ADDRESS, $idTokenPayload, $address);
$this->eventDispatcher->dispatchTyped($event);
$this->logger->debug('Address mapping event dispatched');
if ($event->hasValue() && $event->getValue() !== null && $event->getValue() !== '') {
$account->setProperty('address', $event->getValue(), $scope, '1', '');
}
// Update the website
$event = new AttributeMappedEvent(ProviderService::SETTING_MAPPING_WEBSITE, $idTokenPayload, $website);
$this->eventDispatcher->dispatchTyped($event);
$this->logger->debug('Website mapping event dispatched');
if ($event->hasValue() && $event->getValue() !== null && $event->getValue() !== '') {
$account->setProperty('website', $event->getValue(), $scope, '1', '');
}
// Update the avatar
$event = new AttributeMappedEvent(ProviderService::SETTING_MAPPING_AVATAR, $idTokenPayload, $avatar);
$this->eventDispatcher->dispatchTyped($event);
$this->logger->debug('Avatar mapping event dispatched');
if ($event->hasValue() && $event->getValue() !== null && $event->getValue() !== '') {
$this->setUserAvatar($user->getUID(), $event->getValue());
}
// Update twitter/X
$event = new AttributeMappedEvent(ProviderService::SETTING_MAPPING_TWITTER, $idTokenPayload, $twitter);
$this->eventDispatcher->dispatchTyped($event);
$this->logger->debug('Twitter mapping event dispatched');
if ($event->hasValue() && $event->getValue() !== null && $event->getValue() !== '') {
$account->setProperty('twitter', $event->getValue(), $scope, '1', '');
}
// Update fediverse
$event = new AttributeMappedEvent(ProviderService::SETTING_MAPPING_FEDIVERSE, $idTokenPayload, $fediverse);
$this->eventDispatcher->dispatchTyped($event);
$this->logger->debug('Fediverse mapping event dispatched');
if ($event->hasValue() && $event->getValue() !== null && $event->getValue() !== '') {
$account->setProperty('fediverse', $event->getValue(), $scope, '1', '');
}
// Update the organisation
$event = new AttributeMappedEvent(ProviderService::SETTING_MAPPING_ORGANISATION, $idTokenPayload, $organisation);
$this->eventDispatcher->dispatchTyped($event);
$this->logger->debug('Organisation mapping event dispatched');
if ($event->hasValue() && $event->getValue() !== null && $event->getValue() !== '') {
$account->setProperty('organisation', $event->getValue(), $scope, '1', '');
}
// Update role
$event = new AttributeMappedEvent(ProviderService::SETTING_MAPPING_ROLE, $idTokenPayload, $role);
$this->eventDispatcher->dispatchTyped($event);
$this->logger->debug('Role mapping event dispatched');
if ($event->hasValue() && $event->getValue() !== null && $event->getValue() !== '') {
$account->setProperty('role', $event->getValue(), '1', '');
}
// Update the headline
$event = new AttributeMappedEvent(ProviderService::SETTING_MAPPING_HEADLINE, $idTokenPayload, $headline);
$this->eventDispatcher->dispatchTyped($event);
$this->logger->debug('Headline mapping event dispatched');
if ($event->hasValue() && $event->getValue() !== null && $event->getValue() !== '') {
$account->setProperty('headline', $event->getValue(), $scope, '1', '');
}
// Update the biography
$event = new AttributeMappedEvent(ProviderService::SETTING_MAPPING_BIOGRAPHY, $idTokenPayload, $biography);
$this->eventDispatcher->dispatchTyped($event);
$this->logger->debug('Biography mapping event dispatched');
if ($event->hasValue() && $event->getValue() !== null && $event->getValue() !== '') {
$account->setProperty('biography', $event->getValue(), $scope, '1', '');
}
// Update the gender
$event = new AttributeMappedEvent(ProviderService::SETTING_MAPPING_GENDER, $idTokenPayload, $gender);
$this->eventDispatcher->dispatchTyped($event);
$this->logger->debug('Gender mapping event dispatched');
if ($event->hasValue() && $event->getValue() !== null && $event->getValue() !== '') {
$account->setProperty('gender', $event->getValue(), $scope, '1', '');
}
$this->session->set('user_oidc.oidcUserData', $oidcGssUserData);
$this->accountManager->updateAccount($account);
return $user;
}
/**
* @param string $userId
* @param string $avatarAttribute
* @return void
*/
private function setUserAvatar(string $userId, string $avatarAttribute): void {
$avatarContent = null;
if (filter_var($avatarAttribute, FILTER_VALIDATE_URL)) {
$client = $this->networkService->newClient();
try {
$avatarContent = $client->get($avatarAttribute)->getBody();
if (is_resource($avatarContent)) {
$avatarContent = stream_get_contents($avatarContent);
}
if ($avatarContent === false) {
$this->logger->warning('Failed to read remote avatar response for user ' . $userId, ['avatar_attribute' => $avatarAttribute]);
return;
}
} catch (Throwable $e) {
$this->logger->warning('Failed to get remote avatar for user ' . $userId, ['avatar_attribute' => $avatarAttribute]);
return;
}
} elseif (str_starts_with($avatarAttribute, 'data:image/png;base64,')) {
$avatarContent = base64_decode(str_replace('data:image/png;base64,', '', $avatarAttribute));
if ($avatarContent === false) {
$this->logger->warning('Failed to decode base64 PNG avatar for user ' . $userId, ['avatar_attribute' => $avatarAttribute]);
return;
}
} elseif (str_starts_with($avatarAttribute, 'data:image/jpeg;base64,')) {
$avatarContent = base64_decode(str_replace('data:image/jpeg;base64,', '', $avatarAttribute));
if ($avatarContent === false) {
$this->logger->warning('Failed to decode base64 JPEG avatar for user ' . $userId, ['avatar_attribute' => $avatarAttribute]);
return;
}
}
if ($avatarContent === null || $avatarContent === '') {
$this->logger->warning('Failed to set avatar for user ' . $userId, ['avatar_attribute' => $avatarAttribute]);
return;
}
try {
// inspired from OC\Core\Controller\AvatarController::postAvatar()
$image = new Image();
$image->loadFromData($avatarContent);
$image->readExif($avatarContent);
$image->fixOrientation();
if ($image->valid()) {
$mimeType = $image->mimeType();
if ($mimeType !== 'image/jpeg' && $mimeType !== 'image/png') {
$this->logger->warning('Failed to set remote avatar for user ' . $userId, ['error' => 'Unknown filetype']);
return;
}
if ($image->width() === $image->height()) {
try {
$avatar = $this->avatarManager->getAvatar($userId);
$avatar->set($image);
return;
} catch (Throwable $e) {
$this->logger->error('Failed to set remote avatar for user ' . $userId, ['exception' => $e]);
return;
}
}
$this->logger->warning('Failed to set remote avatar for user ' . $userId, ['error' => 'Image is not square']);
} else {
$this->logger->warning('Failed to set remote avatar for user ' . $userId, ['error' => 'Invalid image']);
}
} catch (\Exception $e) {
$this->logger->error('Failed to set remote avatar for user ' . $userId, ['exception' => $e]);
}
}
public function getSyncGroupsOfToken(int $providerId, object $idTokenPayload) {
$groupsAttribute = $this->providerService->getSetting($providerId, ProviderService::SETTING_MAPPING_GROUPS, 'groups');
$groupsData = $idTokenPayload->{$groupsAttribute} ?? null;
$groupsWhitelistRegex = $this->getGroupWhitelistRegex($providerId);
$event = new AttributeMappedEvent(ProviderService::SETTING_MAPPING_GROUPS, $idTokenPayload, json_encode($groupsData));
$this->eventDispatcher->dispatchTyped($event);
$this->logger->debug('Group mapping event dispatched');
if ($event->hasValue() && $event->getValue() !== null) {
// casted to null if empty value
$groups = json_decode($event->getValue() ?? '');
// support values like group1,group2
if (is_string($groups)) {
$groups = explode(',', $groups);
// remove surrounding spaces in each group
$groups = array_map('trim', $groups);
// remove empty strings
$groups = array_filter($groups);
}
$syncGroups = [];
foreach ($groups as $k => $v) {
if (is_object($v)) {
// Handle array of objects, e.g. [{gid: "1", displayName: "group1"}, ...]
if (empty($v->gid) && $v->gid !== '0' && $v->gid !== 0) {
continue;
}
$group = $v;
} elseif (is_string($v)) {
// Handle array of strings, e.g. ["group1", "group2", ...]
$group = (object)['gid' => $v, 'displayName' => $v];
} else {
continue;
}
if ($groupsWhitelistRegex && !preg_match($groupsWhitelistRegex, $group->gid)) {
$this->logger->debug('Skipped group `' . $group->gid . '` for importing as not part of whitelist');
continue;
}
$group->gid = $this->idService->getId($providerId, $group->gid);
$syncGroups[] = $group;
}
return $syncGroups;
}
return null;
}
public function provisionUserGroups(IUser $user, int $providerId, object $idTokenPayload): ?array {
$groupsWhitelistRegex = $this->getGroupWhitelistRegex($providerId);
$syncGroups = $this->getSyncGroupsOfToken($providerId, $idTokenPayload);
if ($syncGroups === null) {
return null;
}
$userGroups = $this->groupManager->getUserGroups($user);
foreach ($userGroups as $group) {
if (!in_array($group->getGID(), array_column($syncGroups, 'gid'))) {
if ($groupsWhitelistRegex && !preg_match($groupsWhitelistRegex, $group->getGID())) {
continue;
}
$group->removeUser($user);
}
}
foreach ($syncGroups as $group) {
// Creates a new group or return the exiting one.
if ($newGroup = $this->groupManager->createGroup($group->gid)) {
// Adds the user to the group. Does nothing if user is already in the group.
$newGroup->addUser($user);
if (isset($group->displayName)) {
$newGroup->setDisplayName($group->displayName);
}
}
}
return $syncGroups;
}
public function getGroupWhitelistRegex(int $providerId): string {
$regex = $this->providerService->getSetting($providerId, ProviderService::SETTING_GROUP_WHITELIST_REGEX, '');
// If regex does not start with '/', add '/' to the beginning and end
// Only check first character to allow for flags at the end of the regex
if ($regex && substr($regex, 0, 1) !== '/') {
$regex = '/' . $regex . '/';
}
return $regex;
}
}