Bitrix-D7 23.9
 
Загрузка...
Поиск...
Не найдено
user.php
1<?php
2
10namespace Bitrix\Main;
11
26
27Loc::loadMessages(__FILE__);
28
46{
47 public static function getTableName()
48 {
49 return 'b_user';
50 }
51
52 public static function getUfId()
53 {
54 return 'USER';
55 }
56
57 public static function getMap()
58 {
59 $connection = Application::getConnection();
60 $helper = $connection->getSqlHelper();
61
62 return [
63 (new IntegerField('ID'))
64 ->configurePrimary()
65 ->configureAutocomplete(),
66
67 new StringField('LOGIN'),
68
69 (new StringField('PASSWORD'))
70 ->configurePrivate(),
71
72 new StringField('EMAIL'),
73
74 (new BooleanField('ACTIVE'))
75 ->configureValues('N', 'Y'),
76
77 (new BooleanField('BLOCKED'))
78 ->configureValues('N', 'Y'),
79
80 new DatetimeField('DATE_REGISTER'),
81
82 (new ExpressionField(
83 'DATE_REG_SHORT',
84 $helper->getDatetimeToDateFunction('%s'),
85 'DATE_REGISTER')
86 )->configureValueType(DatetimeField::class),
87
88 new DatetimeField('LAST_LOGIN'),
89
90 (new ExpressionField(
91 'LAST_LOGIN_SHORT',
92 $helper->getDatetimeToDateFunction('%s'),
93 'LAST_LOGIN')
94 )->configureValueType(DatetimeField::class),
95
96 new DatetimeField('LAST_ACTIVITY_DATE'),
97
98 new DatetimeField('TIMESTAMP_X'),
99
100 new StringField('NAME'),
101 new StringField('SECOND_NAME'),
102 new StringField('LAST_NAME'),
103 new StringField('TITLE'),
104 new StringField('EXTERNAL_AUTH_ID'),
105 new StringField('XML_ID'),
106 new StringField('BX_USER_ID'),
107 new StringField('CONFIRM_CODE'),
108 new StringField('LID'),
109 (new StringField('LANGUAGE_ID'))
110 ->addValidator(new ORM\Fields\Validators\RegExpValidator('/^[a-z0-9]{2}$/')),
111 new StringField('TIME_ZONE'),
112 new IntegerField('TIME_ZONE_OFFSET'),
113 new StringField('PERSONAL_PROFESSION'),
114 new StringField('PERSONAL_PHONE'),
115 new StringField('PERSONAL_MOBILE'),
116 new StringField('PERSONAL_WWW'),
117 new StringField('PERSONAL_ICQ'),
118 new StringField('PERSONAL_FAX'),
119 new StringField('PERSONAL_PAGER'),
120 new TextField('PERSONAL_STREET'),
121 new StringField('PERSONAL_MAILBOX'),
122 new StringField('PERSONAL_CITY'),
123 new StringField('PERSONAL_STATE'),
124 new StringField('PERSONAL_ZIP'),
125 new StringField('PERSONAL_COUNTRY'),
126 new DateField('PERSONAL_BIRTHDAY'),
127 new StringField('PERSONAL_GENDER'),
128 new IntegerField('PERSONAL_PHOTO'),
129 new TextField('PERSONAL_NOTES'),
130 new StringField('WORK_COMPANY'),
131 new StringField('WORK_DEPARTMENT'),
132 new StringField('WORK_PHONE'),
133 new StringField('WORK_POSITION'),
134 new StringField('WORK_WWW'),
135 new StringField('WORK_FAX'),
136 new StringField('WORK_PAGER'),
137 new TextField('WORK_STREET'),
138 new StringField('WORK_MAILBOX'),
139 new StringField('WORK_CITY'),
140 new StringField('WORK_STATE'),
141 new StringField('WORK_ZIP'),
142 new StringField('WORK_COUNTRY'),
143 new TextField('WORK_PROFILE'),
144 new IntegerField('WORK_LOGO'),
145 new TextField('WORK_NOTES'),
146 new TextField('ADMIN_NOTES'),
147
148 new ExpressionField(
149 'SHORT_NAME',
150 $helper->getConcatFunction(
151 "%s",
152 "' '",
153 "UPPER(" . $helper->getSubstrFunction("%s", 1, 1) . ")", "'.'"
154 ),
155 ['LAST_NAME', 'NAME']
156 ),
157
158 (new ExpressionField(
159 'IS_ONLINE',
160 'CASE WHEN %s > '
161 . $helper->addSecondsToDateTime('(-' . self::getSecondsForLimitOnline() . ')')
162 . ' THEN \'Y\' ELSE \'N\' END',
163 'LAST_ACTIVITY_DATE',
164 ['values' => ['N', 'Y']]
165 ))->configureValueType(BooleanField::class),
166
167 (new ExpressionField(
168 'IS_REAL_USER',
169 'CASE WHEN %s IN (\''
170 . join('\', \'', static::getExternalUserTypes())
171 . '\') THEN \'N\' ELSE \'Y\' END',
172 'EXTERNAL_AUTH_ID',
173 ['values' => ['N', 'Y']]
174 ))->configureValueType(BooleanField::class),
175
176 (new Reference(
177 'INDEX',
178 UserIndexTable::class,
179 Join::on('this.ID', 'ref.USER_ID')
180 ))->configureJoinType(Join::TYPE_INNER),
181
182 (new Reference(
183 'COUNTER',
184 UserCounterTable::class,
185 Join::on('this.ID', 'ref.USER_ID')->where('ref.CODE', 'tasks_effective')
186 )),
187 (new Reference(
188 'PHONE_AUTH',
189 UserPhoneAuthTable::class,
190 Join::on('this.ID', 'ref.USER_ID')
191 )),
192 (new OneToMany('GROUPS', UserGroupTable::class, 'USER'))
193 ->configureJoinType(Join::TYPE_INNER),
194
195 (new Reference(
196 'ACTIVE_LANGUAGE',
197 \Bitrix\Main\Localization\LanguageTable::class,
198 Join::on('this.LANGUAGE_ID', 'ref.LID')->where('ref.ACTIVE', 'Y')
199 )),
200 (new ExpressionField(
201 'NOTIFICATION_LANGUAGE_ID',
202 'CASE WHEN (%s IS NOT NULL AND %s = %s) THEN %s ELSE %s END',
203 [
204 'LANGUAGE_ID', 'LANGUAGE_ID', 'ACTIVE_LANGUAGE.LID', 'LANGUAGE_ID',
205 function () {
206 return new SqlExpression("'" . (($site = \CSite::GetList('', '', ['DEF' => 'Y', 'ACTIVE' => 'Y'])->fetch())
207 ? $site['LANGUAGE_ID'] : LANGUAGE_ID) . "'");
208 },
209 ],
210 ))->configureValueType(StringField::class),
211 ];
212 }
213
214 public static function getSecondsForLimitOnline()
215 {
216 $seconds = intval(ini_get("session.gc_maxlifetime"));
217
218 if ($seconds == 0)
219 {
220 $seconds = 1440;
221 }
222 elseif ($seconds < 120)
223 {
224 $seconds = 120;
225 }
226
227 return $seconds;
228 }
229
235 public static function getActiveUsersCount(Type\Date $lastLoginDate = null)
236 {
237 return Application::getInstance()->getLicense()->getActiveUsersCount($lastLoginDate);
238 }
239
240 public static function getUserGroupIds($userId)
241 {
242 $groups = [];
243
244 // anonymous groups
245 $result = GroupTable::getList([
246 'select' => ['ID'],
247 'filter' => [
248 '=ANONYMOUS' => 'Y',
249 '=ACTIVE' => 'Y',
250 ],
251 'cache' => ['ttl' => 86400],
252 ]);
253
254 while ($row = $result->fetch())
255 {
256 $groups[] = $row['ID'];
257 }
258
259 if (!in_array(2, $groups))
260 {
261 $groups[] = 2;
262 }
263
264 if ($userId > 0)
265 {
266 // private groups
267 $nowTimeExpression = new SqlExpression(
268 static::getEntity()->getConnection()->getSqlHelper()->getCurrentDateTimeFunction()
269 );
270
271 $result = GroupTable::getList([
272 'select' => ['ID'],
273 'filter' => [
274 '=UserGroup:GROUP.USER_ID' => $userId,
275 '=ACTIVE' => 'Y',
276 [
277 'LOGIC' => 'OR',
278 '=UserGroup:GROUP.DATE_ACTIVE_FROM' => null,
279 '<=UserGroup:GROUP.DATE_ACTIVE_FROM' => $nowTimeExpression,
280 ],
281 [
282 'LOGIC' => 'OR',
283 '=UserGroup:GROUP.DATE_ACTIVE_TO' => null,
284 '>=UserGroup:GROUP.DATE_ACTIVE_TO' => $nowTimeExpression,
285 ],
286 [
287 'LOGIC' => 'OR',
288 '!=ANONYMOUS' => 'Y',
289 '=ANONYMOUS' => null,
290 ],
291 ],
292 ]);
293
294 while ($row = $result->fetch())
295 {
296 $groups[] = $row['ID'];
297 }
298 }
299
300 sort($groups);
301
302 return $groups;
303 }
304
305 public static function getExternalUserTypes()
306 {
307 static $types = [
308 'bot',
309 'email',
310 '__controller',
311 'replica',
312 'imconnector',
313 'sale',
314 'saleanonymous',
315 'shop',
316 'call',
317 'document_editor',
318 'calendar_sharing',
319 ];
320
321 return $types;
322 }
323
329 public static function getIndexedFields(): array
330 {
331 static $fields = [
332 'ID',
333 'NAME',
334 'SECOND_NAME',
335 'LAST_NAME',
336 'WORK_POSITION',
337 'PERSONAL_PROFESSION',
338 'PERSONAL_WWW',
339 'LOGIN',
340 'EMAIL',
341 'PERSONAL_MOBILE',
342 'PERSONAL_PHONE',
343 'PERSONAL_CITY',
344 'PERSONAL_STREET',
345 'PERSONAL_STATE',
346 'PERSONAL_COUNTRY',
347 'PERSONAL_ZIP',
348 'PERSONAL_MAILBOX',
349 'WORK_CITY',
350 'WORK_STREET',
351 'WORK_STATE',
352 'WORK_ZIP',
353 'WORK_COUNTRY',
354 'WORK_MAILBOX',
355 'WORK_PHONE',
356 'WORK_COMPANY',
357 ];
358
359 if (ModuleManager::isModuleInstalled('intranet'))
360 {
361 return array_merge($fields, ['UF_DEPARTMENT']);
362 }
363 return $fields;
364 }
365
372 public static function shouldReindex(array $fields): bool
373 {
374 if (isset($fields['ID']))
375 {
376 unset($fields['ID']);
377 }
378 return !empty(array_intersect(
379 static::getIndexedFields(),
380 array_keys($fields)
381 ));
382 }
383
384 public static function indexRecord($id)
385 {
386 $id = intval($id);
387 if ($id == 0)
388 {
389 return false;
390 }
391
392 $record = parent::getList([
393 'select' => static::getIndexedFields(),
394 'filter' => ['=ID' => $id],
395 ])->fetch();
396
397 if (!is_array($record))
398 {
399 return false;
400 }
401
402 $record['UF_DEPARTMENT_NAMES'] = [];
403 if (ModuleManager::isModuleInstalled('intranet'))
404 {
405 $departmentNames = UserUtils::getDepartmentNames($record['UF_DEPARTMENT']);
406 foreach ($departmentNames as $departmentName)
407 {
408 $record['UF_DEPARTMENT_NAMES'][] = $departmentName['NAME'];
409 }
410 }
411
412 $departmentName = $record['UF_DEPARTMENT_NAMES'][0] ?? '';
413 $searchDepartmentContent = implode(' ', $record['UF_DEPARTMENT_NAMES']);
414
416 'USER_ID' => $id,
417 'NAME' => (string)$record['NAME'],
418 'SECOND_NAME' => (string)$record['SECOND_NAME'],
419 'LAST_NAME' => (string)$record['LAST_NAME'],
420 'WORK_POSITION' => (string)$record['WORK_POSITION'],
421 'UF_DEPARTMENT_NAME' => (string)$departmentName,
422 'SEARCH_USER_CONTENT' => self::generateSearchUserContent($record),
423 'SEARCH_ADMIN_CONTENT' => self::generateSearchAdminContent($record),
424 'SEARCH_DEPARTMENT_CONTENT' => MapBuilder::create()->addText($searchDepartmentContent)->build(),
425 ]);
426
427 return true;
428 }
429
430 public static function deleteIndexRecord($id)
431 {
432 UserIndexTable::delete($id);
433 }
434
435 private static function generateSearchUserContent(array $fields)
436 {
437 $text = implode(' ', [
438 $fields['NAME'],
439 $fields['LAST_NAME'],
440 $fields['WORK_POSITION'],
441 ]);
442
443 $charsToReplace = ['(', ')', '[', ']', '{', '}', '<', '>', '-', '#', '"', '\''];
444
445 $clearedText = str_replace($charsToReplace, ' ', $text);
446 $clearedText = preg_replace('/\s\s+/', ' ', $clearedText);
447
448 $result = MapBuilder::create()
449 ->addInteger($fields['ID'])
450 ->addText($clearedText)
451 ->build()
452 ;
453
454 return $result;
455 }
456
457 private static function generateSearchAdminContent(array $fields)
458 {
459 $personalCountry = (
460 isset($fields['PERSONAL_COUNTRY'])
461 && intval($fields['PERSONAL_COUNTRY'])
463 'VALUE' => intval($fields['PERSONAL_COUNTRY']),
464 ])
465 : ''
466 );
467 $workCountry = (
468 isset($fields['WORK_COUNTRY'])
469 && intval($fields['WORK_COUNTRY'])
471 'VALUE' => intval($fields['WORK_COUNTRY']),
472 ])
473 : ''
474 );
475 $department = (
476 isset($fields['UF_DEPARTMENT_NAMES'])
477 && is_array($fields['UF_DEPARTMENT_NAMES'])
478 ? implode(' ', $fields['UF_DEPARTMENT_NAMES'])
479 : ''
480 );
481
482 $ufContent = UserUtils::getUFContent($fields['ID']);
483 $tagsContent = UserUtils::getTagsContent($fields['ID']);
484
485 $result = MapBuilder::create()
486 ->addInteger($fields['ID'])
487 ->addText($fields['NAME'])
488 ->addText($fields['SECOND_NAME'])
489 ->addText($fields['LAST_NAME'])
490 ->addEmail($fields['EMAIL'])
491 ->addText($fields['WORK_POSITION'])
492 ->addText($fields['PERSONAL_PROFESSION'])
493 ->addText($fields['PERSONAL_WWW'])
494 ->addText($fields['LOGIN'])
495 ->addPhone($fields['PERSONAL_MOBILE'])
496 ->addPhone($fields['PERSONAL_PHONE'])
497 ->addText($fields['PERSONAL_CITY'])
498 ->addText($fields['PERSONAL_STREET'])
499 ->addText($fields['PERSONAL_STATE'])
500 ->addText($fields['PERSONAL_ZIP'])
501 ->addText($fields['PERSONAL_MAILBOX'])
502 ->addText($fields['WORK_CITY'])
503 ->addText($fields['WORK_STREET'])
504 ->addText($fields['WORK_STATE'])
505 ->addText($fields['WORK_ZIP'])
506 ->addText($fields['WORK_MAILBOX'])
507 ->addPhone($fields['WORK_PHONE'])
508 ->addText($fields['WORK_COMPANY'])
509 ->addText($personalCountry)
510 ->addText($workCountry)
511 ->addText($department)
512 ->addText($ufContent)
513 ->addText($tagsContent)
514 ->build()
515 ;
516
517 return $result;
518 }
519
520 public static function add(array $data)
521 {
522 throw new NotImplementedException("Use CUser class.");
523 }
524
525 public static function update($primary, array $data)
526 {
527 throw new NotImplementedException("Use CUser class.");
528 }
529
530 public static function delete($primary)
531 {
532 throw new NotImplementedException("Use CUser class.");
533 }
534
535 public static function onAfterAdd(ORM\Event $event)
536 {
537 $id = $event->getParameter("id");
538 static::indexRecord($id);
539 return new ORM\EventResult();
540 }
541
542 public static function onAfterUpdate(ORM\Event $event)
543 {
544 $primary = $event->getParameter("id");
545 $id = $primary["ID"];
546 static::indexRecord($id);
547 return new ORM\EventResult();
548 }
549
550 public static function onAfterDelete(ORM\Event $event)
551 {
552 $primary = $event->getParameter("id");
553 $id = $primary["ID"];
554 static::deleteIndexRecord($id);
555 return new ORM\EventResult();
556 }
557
558 public static function postInitialize(ORM\Entity $entity)
559 {
560 // add uts inner reference
561
562 if ($entity->hasField('UTS_OBJECT'))
563 {
565 $leftUtsRef = $entity->getField('UTS_OBJECT');
566
567 $entity->addField((
568 new Reference(
569 'UTS_OBJECT_INNER', $leftUtsRef->getRefEntity(), $leftUtsRef->getReference()
570 ))
571 ->configureJoinType('inner')
572 );
573 }
574 }
575}
static getConnection($name="")
static loadMessages($file)
Definition loc.php:64
static isModuleInstalled($moduleName)
static getList(array $parameters=array())
static postInitialize(Entity $entity)
static merge(array $data)
Definition userindex.php:92
static getExternalUserTypes()
Definition user.php:305
static getSecondsForLimitOnline()
Definition user.php:214
static getMap()
Definition user.php:57
static getUfId()
Definition user.php:52
static onAfterDelete(ORM\Event $event)
Definition user.php:550
static shouldReindex(array $fields)
Definition user.php:372
static onAfterAdd(ORM\Event $event)
Definition user.php:535
static getIndexedFields()
Definition user.php:329
static add(array $data)
Definition user.php:520
static onAfterUpdate(ORM\Event $event)
Definition user.php:542
static getActiveUsersCount(Type\Date $lastLoginDate=null)
Definition user.php:235
static indexRecord($id)
Definition user.php:384
static deleteIndexRecord($id)
Definition user.php:430
static update($primary, array $data)
Definition user.php:525
static getTableName()
Definition user.php:47
static getUserGroupIds($userId)
Definition user.php:240
static getTagsContent($userId)
static getUFContent($userId)
static getDepartmentNames($departmentIds)
static getCountryValue(array $params=[])