/
BulkUserAssignCommand.php
141 lines (116 loc) · 5.2 KB
/
BulkUserAssignCommand.php
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
<?php
namespace Concrete\Core\Console\Command;
use Concrete\Core\Console\Command;
use Concrete\Core\File\Service\File;
use Concrete\Core\Logging\Channels;
use Concrete\Core\Logging\LoggerFactory;
use Concrete\Core\Support\Facade\Application;
use Concrete\Core\User\Group\Group;
use Concrete\Core\User\Group\GroupRepository;
use Concrete\Core\User\UserInfo;
use Concrete\Core\User\UserInfoRepository;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Exception;
class BulkUserAssignCommand extends Command
{
protected function configure()
{
$this
->setName('c5:user-group:bulk-assign-users')
->setDescription('Bulk assign users to groups by a given CSV file.')
->addOption('csv-file', 'c', InputOption::VALUE_REQUIRED, 'Path to CSV file.')
->addOption('group-id', 'g', InputOption::VALUE_REQUIRED, 'The id of the target group.')
->addOption('remove-unlisted-users', 'r', InputOption::VALUE_OPTIONAL, 'Remove users from this group if they don\'t appear in CSV.')
->addOption('dry-run', 'd', InputOption::VALUE_OPTIONAL, 'Perform a dry run.');
}
/**
* @param InputInterface $input
* @param OutputInterface $output
* @return int
* @throws Exception
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$mailAddresses = [];
$app = Application::getFacadeApplication();
/** @var GroupRepository $groupRepository */
$groupRepository = $app->make(GroupRepository::class);
/** @var UserInfoRepository $userInfoRepository */
$userInfoRepository = $app->make(UserInfoRepository::class);
/** @var LoggerFactory $loggerFactory */
$loggerFactory = $app->make(LoggerFactory::class);
/** @var File $fileHelper */
$fileHelper = $app->make(File::class);
$logger = $loggerFactory->createLogger(Channels::CHANNEL_USERS);
$csvFile = $input->getOption('csv-file');
$groupId = $input->getOption('group-id');
$dryRun = $this->input->getParameterOption(['--dry-run', '-d']) !== false;
$removeUnlistedUsers = $this->input->getParameterOption(['--remove-unlisted-users', '-r']) !== false;
$targetGroup = $groupRepository->getGroupByID($groupId);
if ($targetGroup instanceof Group) {
if (strtolower(pathinfo($csvFile, PATHINFO_EXTENSION)) === 'csv') {
$csvData = $fileHelper->getContents($csvFile);
/*
* Validate the CSV and extract all mail addresses.
*/
foreach (explode(PHP_EOL, $csvData) as $line) {
$rows = str_getcsv($line);
if (count($rows) === 1) {
if (filter_var($rows[0], FILTER_VALIDATE_EMAIL)) {
$mailAddresses[] = $rows[0];
} else if ($rows[0] !== null) {
throw new Exception('The given CSV contains invalid mail addresses.');
}
} else {
throw new Exception('The given CSV contains more then one column.');
}
}
} else {
throw new Exception('The file extension is invalid.');
}
} else {
throw new Exception('You need to select valid target group.');
}
$totalUsersProvided = count($mailAddresses);
$totalUsersAddedToTargetGroup = 0;
$totalUsersRemovedFromTargetGroup = 0;
/*
* Add the given users to the target group.
*/
foreach ($mailAddresses as $mailAddress) {
$userInfo = $userInfoRepository->getByEmail($mailAddress);
if ($userInfo instanceof UserInfo) {
$user = $userInfo->getUserObject();
if (!$user->inGroup($targetGroup)) {
if (!$dryRun) {
$user->enterGroup($targetGroup);
}
$totalUsersAddedToTargetGroup++;
}
}
}
/*
* Remove all users from the target group that are not part of the given CSV file if this option is selected.
*/
if ($removeUnlistedUsers) {
foreach ($targetGroup->getGroupMembers() as $groupMember) {
/** @var UserInfo $groupMember */
if (!in_array($groupMember->getUserEmail(), $mailAddresses)) {
$user = $groupMember->getUserObject();
if (!$dryRun) {
$user->exitGroup($targetGroup);
}
$totalUsersRemovedFromTargetGroup++;
}
}
}
$output->writeln(sprintf('<info>Done! %s user records are found in the given CSV. %s users were added to the target group and %s users were removed from target group. For further details please check the logs.</info>',
$totalUsersProvided,
$totalUsersAddedToTargetGroup,
$totalUsersRemovedFromTargetGroup
));
return static::SUCCESS;
}
}