Bitrix-D7 23.9
 
Загрузка...
Поиск...
Не найдено
usertogroup.php
1<?php
2
4
6use Bitrix\Main\Entity\Query;
17
18class UserToGroup extends Base
19{
20 public function listAction(
21 PageNavigation $pageNavigation,
22 $filter = [],
23 $select = [],
24 $groupBy = false,
25 $order = ['ID' => 'DESC'],
26 $params = []
27 )
28 {
29 $relations = [];
30
31 $query = UserToGroupTable::query();
32 $query
33 ->setSelect($this->prepareQuerySelect($select))
34 ->setOrder($order)
35 ->setOffset($pageNavigation->getOffset())
36 ->setLimit(($pageNavigation->getLimit()))
37 ->countTotal(true)
38 ;
39 $query = $this->processFilter($query, $filter);
40
41 $res = $query->exec();
42 while ($relation = $res->fetch())
43 {
44 $relation['FORMATTED_USER_NAME'] = \CUser::FormatName(
45 \CSite::getNameFormat(),
46 [
47 'NAME' => $relation['USER_NAME'],
48 'LAST_NAME' => $relation['USER_LAST_NAME'],
49 'SECOND_NAME' => $relation['USER_SECOND_NAME'],
50 'LOGIN' => $relation['USER_LOGIN'],
51 ],
52 true
53 );
54 $relations[$relation['ID']] = $relation;
55 }
56
57 if (!empty($relations))
58 {
59 if (in_array('USER_PERSONAL_PHOTO', $select, true))
60 {
61 $relations = $this->fillUserAvatars($relations);
62 }
63 if (in_array('ACTIONS', $select, true))
64 {
65 $relations = $this->fillActions($relations);
66 }
67 }
68 $relations = $this->convertKeysToCamelCase($relations);
69
70 return new Engine\Response\DataType\Page('relations', array_values($relations), $res->getCount());
71 }
72
73 private function prepareQuerySelect(array $select): array
74 {
75 $userToGroupFields = [
76 'ID',
77 'USER_ID',
78 'GROUP_ID',
79 'ROLE',
80 'AUTO_MEMBER',
81 'DATE_CREATE',
82 'DATE_UPDATE',
83 'INITIATED_BY_TYPE',
84 'INITIATED_BY_USER_ID',
85 'MESSAGE',
86 ];
87 $userFields = [
88 'USER_ACTIVE',
89 'USER_NAME',
90 'USER_LAST_NAME',
91 'USER_SECOND_NAME',
92 'USER_WORK_POSITION',
93 'USER_LOGIN',
94 'USER_EMAIL',
95 'USER_CONFIRM_CODE',
96 'USER_PERSONAL_PHOTO',
97 'USER_PERSONAL_GENDER',
98 'USER_LID',
99 ];
100 $allowedFields = array_merge($userToGroupFields, $userFields);
101 $prepared = array_intersect($select, $allowedFields);
102
103 foreach ($prepared as $field)
104 {
105 if (in_array($field, $userFields, true))
106 {
107 $prepared[$field] = 'USER.' . str_replace('USER_', '', $field);
108 unset($prepared[array_search($field, $prepared, true)]);
109 }
110 }
111
112 return $prepared;
113 }
114
115 private function processFilter(Query $query, array $filter): Query
116 {
117 if (array_key_exists('ID', $filter))
118 {
119 $ids = (is_array($filter['ID']) ? $filter['ID'] : [$filter['ID']]);
120 $ids = array_map('intval', $ids);
121 $ids = array_filter($ids);
122
123 if (!empty($ids))
124 {
125 count($ids) > 1
126 ? $query->whereIn('ID', $ids)
127 : $query->where('ID', $ids[0])
128 ;
129 }
130 }
131
132 if (array_key_exists('GROUP_ID', $filter))
133 {
134 $query->where('GROUP_ID', (int)$filter['GROUP_ID']);
135 }
136
137 if (array_key_exists('ROLE', $filter))
138 {
139 $roles = (is_array($filter['ROLE']) ? $filter['ROLE'] : [$filter['ROLE']]);
140 $roles = array_filter($roles);
141
142 if (!empty($roles))
143 {
144 if (array_key_exists('INVITED_BY_ME', $filter) && $filter['INVITED_BY_ME'] === 'Y')
145 {
146 $query->where(
147 Query::filter()
148 ->logic('or')
149 ->whereIn('ROLE', $roles)
150 ->where(
151 Query::filter()
152 ->where('ROLE', UserToGroupTable::ROLE_REQUEST)
153 ->where('INITIATED_BY_TYPE', UserToGroupTable::INITIATED_BY_GROUP)
154 ->where('INITIATED_BY_USER_ID', $this->getCurrentUser()->getId())
155 )
156 );
157 }
158 else
159 {
160 $query->whereIn('ROLE', $roles);
161 }
162 }
163 else if (array_key_exists('INVITED_BY_ME', $filter) && $filter['INVITED_BY_ME'] === 'Y')
164 {
165 $query->where(
166 Query::filter()
167 ->where('ROLE', UserToGroupTable::ROLE_REQUEST)
168 ->where('INITIATED_BY_TYPE', UserToGroupTable::INITIATED_BY_GROUP)
169 ->where('INITIATED_BY_USER_ID', $this->getCurrentUser()->getId())
170 );
171 }
172 }
173
174 if (array_key_exists('INITIATED_BY_TYPE', $filter))
175 {
176 $query->where('INITIATED_BY_TYPE', $filter['INITIATED_BY_TYPE']);
177 }
178
179 if (array_key_exists('INITIATED_BY_USER_ID', $filter))
180 {
181 $query->where('INITIATED_BY_USER_ID', $filter['INITIATED_BY_USER_ID']);
182 }
183
184 if (array_key_exists('SEARCH_INDEX', $filter) && trim($filter['SEARCH_INDEX']) !== '')
185 {
186 $query->whereMatch(
187 'USER.INDEX.SEARCH_ADMIN_CONTENT',
188 Filter\Helper::matchAgainstWildcard(Content::prepareStringToken(trim($filter['SEARCH_INDEX'])))
189 );
190 }
191
192 return $query;
193 }
194
195 private function fillUserAvatars(array $relations): array
196 {
197 foreach (array_keys($relations) as $id)
198 {
199 $relations[$id]['IMAGE'] = '';
200 }
201
202 $imageIds = array_filter(
203 array_column($relations, 'USER_PERSONAL_PHOTO', 'ID'),
204 static function ($id) {
205 return (int)$id > 0;
206 }
207 );
208
209 $avatars = File::getFilesSources($imageIds);
210 $imageIds = array_flip($imageIds);
211
212 foreach ($imageIds as $imageId => $relationId)
213 {
214 $relations[$relationId]['IMAGE'] = $avatars[$imageId];
215 }
216
217 return $relations;
218 }
219
220 private function fillActions(array $relations): array
221 {
222 $userId = (int)$this->getCurrentUser()->getId();
223 $permissions = [];
224
225 foreach ($relations as $id => $relation)
226 {
227 $projectId = (int)$relation['GROUP_ID'];
228
229 if (!array_key_exists($projectId, $permissions))
230 {
231 $permissions[$projectId] = Helper\Workgroup::getPermissions(['groupId' => $projectId]);
232 }
233
234 $projectPermissions = $permissions[$projectId];
235 $canModifyGroup = $projectPermissions['UserCanModifyGroup'];
236 $canInitiate = $projectPermissions['UserCanInitiate'];
237 $canProcessRequestsIn = $projectPermissions['UserCanProcessRequestsIn'];
238
239 $role = $relation['ROLE'];
240 $memberId = (int)$relation['USER_ID'];
241 $isAutoMember = ($relation['AUTO_MEMBER'] === 'Y');
242 $initiatedByType = $relation['INITIATED_BY_TYPE'];
243
244 $relations[$id]['ACTIONS'] = [
245 'SET_OWNER' => (
246 $canModifyGroup
247 && $projectPermissions['UserIsOwner']
249 ),
250 'SET_MODERATOR' => (
251 $canModifyGroup
252 && $role === UserToGroupTable::ROLE_USER
253 ),
254 'REMOVE_MODERATOR' => (
255 $canModifyGroup
257 ),
258 'EXCLUDE' => (
259 $canModifyGroup
260 && !$isAutoMember
261 && $memberId !== $userId
263 ),
264 'REPEAT_INVITE' => (
265 $canInitiate
267 && $initiatedByType === UserToGroupTable::INITIATED_BY_GROUP
268 ),
269 'CANCEL_INVITE' => (
270 $canInitiate
272 && $initiatedByType === UserToGroupTable::INITIATED_BY_GROUP
273 ),
274 'ACCEPT_REQUEST' => (
275 $canProcessRequestsIn
277 && $initiatedByType === UserToGroupTable::INITIATED_BY_USER
278 ),
279 'DENY_REQUEST' => (
280 $canProcessRequestsIn
282 && $initiatedByType === UserToGroupTable::INITIATED_BY_USER
283 ),
284 ];
285 }
286
287 return $relations;
288 }
289
290 public function joinAction(array $params = [])
291 {
292 $userId = (int)(isset($params['userId']) && (int)$params['userId'] > 0 ? $params['userId'] : $this->getCurrentUser()->getId());
293 $groupId = (int)(isset($params['groupId']) && (int)$params['groupId'] > 0 ? $params['groupId'] : 0);
294
295 if ($userId <= 0)
296 {
297 $this->addError(new Error('No User Id', 'SONET_CONTROLLER_USERTOGROUP_NO_USER_ID'));
298 return null;
299 }
300
301 if ($groupId <= 0)
302 {
303 $this->addError(new Error('No Workgroup', 'SONET_CONTROLLER_USERTOGROUP_NO_GROUP'));
304 return null;
305 }
306
307 if (!Loader::includeModule('socialnetwork'))
308 {
309 $this->addError(new Error('Cannot include Socialnetwork module', 'SONET_CONTROLLER_USERTOGROUP_NO_SOCIALNETWORK_MODULE'));
310 return null;
311 }
312
313 if (
314 !\CSocNetUser::isCurrentUserModuleAdmin(SITE_ID, false)
315 && $userId !== (int)$this->getCurrentUser()->getId()
316 )
317 {
318 $this->addError(new Error('No permissions', 'SONET_CONTROLLER_USERTOGROUP_NO_PERMISSIONS'));
319 return null;
320 }
321
322 try
323 {
324 $confirmationNeeded = Helper\Workgroup::join([
325 'groupId' => $groupId,
326 ]);
327 }
328 catch (\Exception $e)
329 {
330 $this->addError(new Error($e->getMessage(), $e->getCode()));
331 return null;
332 }
333
334 if ($confirmationNeeded)
335 {
336 // re-calculte counters for the group moderators
337 $moderators = UserToGroupTable::getGroupModerators($groupId);
338 Service::addEvent(
339 EventDictionary::EVENT_WORKGROUP_MEMBER_REQUEST_CONFIRM,
340 [
341 'GROUP_ID' => $groupId,
342 'RECEPIENTS' => array_map(function ($row) { return $row['USER_ID']; }, $moderators),
343 ]
344 );
345 }
346
347 return [
348 'success' => true,
349 'confirmationNeeded' => $confirmationNeeded,
350 ];
351 }
352
353 /* use Helper::exclude() then */
354 public function leaveAction(array $params = [])
355 {
356 global $APPLICATION;
357
358 $userId = $this->getCurrentUser()->getId();
359 $groupId = (int)(isset($params['groupId']) && (int)$params['groupId'] > 0 ? $params['groupId'] : 0);
360
361 if ($userId <= 0)
362 {
363 $this->addError(new Error('No User Id', 'SONET_CONTROLLER_USERTOGROUP_NO_USER_ID'));
364 return null;
365 }
366
367 if ($groupId <= 0)
368 {
369 $this->addError(new Error('No Workgroup', 'SONET_CONTROLLER_USERTOGROUP_NO_GROUP'));
370 return null;
371 }
372
373 if (!Loader::includeModule('socialnetwork'))
374 {
375 $this->addError(new Error('Cannot include Socialnetwork module', 'SONET_CONTROLLER_USERTOGROUP_NO_SOCIALNETWORK_MODULE'));
376 return null;
377 }
378
379 try
380 {
381 Helper\Workgroup::leave([
382 'groupId' => $groupId,
383 'userId' => $userId,
384 ]);
385 }
386 catch (\Exception $e)
387 {
388 $this->addError(new Error($e->getMessage(), $e->getCode()));
389 return null;
390 }
391
392 return [
393 'success' => true,
394 ];
395 }
396
397 public function setOwnerAction(int $userId, int $groupId): bool
398 {
399 return Helper\Workgroup::setOwner([
400 'userId' => $userId,
401 'groupId' => $groupId,
402 ]);
403 }
404
405 public function setModeratorAction(int $userId, int $groupId): bool
406 {
407 return Helper\Workgroup::setModerator([
408 'userId' => $userId,
409 'groupId' => $groupId,
410 ]);
411 }
412
413 public function removeModeratorAction(int $userId, int $groupId): bool
414 {
415 return Helper\Workgroup::removeModerator([
416 'userId' => $userId,
417 'groupId' => $groupId,
418 ]);
419 }
420
421 public function setModeratorsAction(array $userIds, int $groupId): bool
422 {
423 return Helper\Workgroup::setModerators([
424 'userIds' => $userIds,
425 'groupId' => $groupId,
426 ]);
427 }
428
429 public function excludeAction(int $userId, int $groupId): bool
430 {
431 return Helper\Workgroup::exclude([
432 'userId' => $userId,
433 'groupId' => $groupId,
434 ]);
435 }
436
437 public function repeatInviteAction(int $userId, int $groupId): bool
438 {
439 return \CSocNetUserToGroup::SendRequestToJoinGroup(
440 $this->getCurrentUser()->getId(),
441 $userId,
442 $groupId,
443 ''
444 );
445 }
446
447 public function cancelInviteAction(int $userId, int $groupId): bool
448 {
449 return Helper\Workgroup::deleteOutgoingRequest([
450 'userId' => $userId,
451 'groupId' => $groupId,
452 ]);
453 }
454
455 public function cancelIncomingRequestAction(int $userId, int $groupId): bool
456 {
457 return Helper\Workgroup::deleteIncomingRequest([
458 'userId' => $userId,
459 'groupId' => $groupId,
460 ]);
461 }
462
463 public function acceptOutgoingRequestAction(int $groupId): bool
464 {
465 $userId = $this->getCurrentUser()->getId();
466
467 try
468 {
469 return Helper\Workgroup::acceptOutgoingRequest([
470 'groupId' => $groupId,
471 'userId' => $userId,
472 ]);
473 }
474 catch (\Exception $e)
475 {
476 $this->addError(new Error($e->getMessage()));
477
478 return false;
479 }
480 }
481
482 public function rejectOutgoingRequestAction(int $groupId): bool
483 {
484 $userId = $this->getCurrentUser()->getId();
485
486 try
487 {
488 return Helper\Workgroup::rejectOutgoingRequest([
489 'groupId' => $groupId,
490 'userId' => $userId,
491 ]);
492 }
493 catch (\Exception $e)
494 {
495 $this->addError(new Error($e->getMessage()));
496
497 return false;
498 }
499 }
500
501 public function acceptRequestAction(int $relationId, int $groupId): bool
502 {
503 return \CSocNetUserToGroup::ConfirmRequestToBeMember(
504 $this->getCurrentUser()->getId(),
505 $groupId,
506 [ $relationId ]
507 );
508 }
509
510 public function denyRequestAction(int $relationId, int $groupId): bool
511 {
512 return \CSocNetUserToGroup::RejectRequestToBeMember(
513 $this->getCurrentUser()->getId(),
514 $groupId,
515 [$relationId]
516 );
517 }
518
519 public function setHideRequestPopupAction(int $groupId): ?bool
520 {
521 $result = Helper\UserToGroup\RequestPopup::setHideRequestPopup([
522 'groupId' => $groupId,
523 'userId' => (int)$this->getCurrentUser()->getId(),
524 ]);
525
526 if (!$result)
527 {
528 $this->addError(new Error('Cannot process operation', 'SONET_CONTROLLER_USERTOGROUP_SET_HIDE_REQUEST_POPUP_ERROR'));
529 return null;
530 }
531
532 return true;
533 }
534}
setModeratorAction(int $userId, int $groupId)
setModeratorsAction(array $userIds, int $groupId)
acceptRequestAction(int $relationId, int $groupId)
listAction(PageNavigation $pageNavigation, $filter=[], $select=[], $groupBy=false, $order=['ID'=> 'DESC'], $params=[])
excludeAction(int $userId, int $groupId)
cancelIncomingRequestAction(int $userId, int $groupId)
setOwnerAction(int $userId, int $groupId)
cancelInviteAction(int $userId, int $groupId)
removeModeratorAction(int $userId, int $groupId)
denyRequestAction(int $relationId, int $groupId)
repeatInviteAction(int $userId, int $groupId)
static getGroupModerators(int $groupId)