Bitrix-D7 23.9
 
Загрузка...
Поиск...
Не найдено
user.php
1<?php
2
3namespace Bitrix\Mail;
4
7
8Main\Localization\Loc::loadMessages(__FILE__);
9
10class User
11{
12
19 public static function create($fields)
20 {
21 $user = new \CUser;
22
23 $userFields = array(
24 'LOGIN' => $fields["EMAIL"],
25 'EMAIL' => $fields["EMAIL"],
26 'NAME' => (!empty($fields["NAME"]) ? $fields["NAME"] : ''),
27 'LAST_NAME' => (!empty($fields["LAST_NAME"]) ? $fields["LAST_NAME"] : ''),
28 'PERSONAL_PHOTO' => (!empty($fields["PERSONAL_PHOTO_ID"]) ? \CFile::makeFileArray($fields['PERSONAL_PHOTO_ID']) : false),
29 'EXTERNAL_AUTH_ID' => 'email',
30 );
31
32 if (Main\ModuleManager::isModuleInstalled('intranet'))
33 {
34 $userFields['UF_DEPARTMENT'] = array();
35 }
36
37 if (
38 isset($fields['UF'])
39 && is_array($fields['UF'])
40 )
41 {
42 foreach($fields['UF'] as $key => $value)
43 {
44 if (!empty($value))
45 {
46 $userFields[$key] = $value;
47 }
48 }
49 }
50
51 $mailGroup = self::getMailUserGroup();
52 if (!empty($mailGroup))
53 {
54 $userFields["GROUP_ID"] = $mailGroup;
55 }
56
57 $result = $user->add($userFields);
58
59 return $result;
60 }
61
67 public static function login()
68 {
69 $eventManager = Main\EventManager::getInstance();
70 $handler = $eventManager->addEventHandlerCompatible('main', 'OnUserLoginExternal', array('\Bitrix\Mail\User', 'onLoginExternal'));
71
72 global $USER;
73 $USER->login(null, null, 'Y');
74
75 $eventManager->removeEventHandler('main', 'OnUserLoginExternal', $handler);
76 }
77
84 public static function onLoginExternal(&$params)
85 {
86 $context = Main\Application::getInstance()->getContext();
87 $request = $context->getRequest();
88
89 if ($token = $request->get('token') ?: $request->getCookie('MAIL_AUTH_TOKEN'))
90 {
91 $userRelation = UserRelationsTable::getList(array(
92 'select' => array('USER_ID'),
93 'filter' => array(
94 '=TOKEN' => $token,
95 '=USER.EXTERNAL_AUTH_ID' => 'email',
96 'USER.ACTIVE' => 'Y'
97 )
98 ))->fetch();
99
100 if ($userRelation)
101 {
102 $context->getResponse()->addCookie(new Main\Web\Cookie('MAIL_AUTH_TOKEN', $token));
103
104 return $userRelation['USER_ID'];
105 }
106 }
107
108 return false;
109 }
110
122 public static function getReplyTo($siteId, $userId, $entityType, $entityId, $entityLink = null, $backurl = null)
123 {
124 $filter = array(
125 '=SITE_ID' => $siteId,
126 '=USER_ID' => $userId,
127 '=ENTITY_TYPE' => $entityType,
128 '=ENTITY_ID' => $entityId
129 );
130 $userRelation = UserRelationsTable::getList(array('filter' => $filter))->fetch();
131
132 if (empty($userRelation))
133 {
134 $filter['=SITE_ID'] = null;
135 $userRelation = UserRelationsTable::getList(array('filter' => $filter))->fetch();
136 }
137
138 if (empty($userRelation))
139 {
140 if (empty($entityLink))
141 return false;
142
143 $userRelation = array(
144 'SITE_ID' => $siteId,
145 'TOKEN' => base_convert(md5(time().Main\Security\Random::getBytes(6)), 16, 36),
146 'USER_ID' => $userId,
147 'ENTITY_TYPE' => $entityType,
148 'ENTITY_ID' => $entityId,
149 'ENTITY_LINK' => $entityLink,
150 'BACKURL' => $backurl
151 );
152
153 if (!UserRelationsTable::add($userRelation)->isSuccess())
154 return false;
155 }
156
157 $site = Main\SiteTable::getByPrimary($siteId)->fetch();
158 $context = Main\Application::getInstance()->getContext();
159
160 $scheme = $context->getRequest()->isHttps() ? 'https' : 'http';
161 $domain = $site['SERVER_NAME'] ?: \COption::getOptionString('main', 'server_name', '');
162
163 if (preg_match('/^(?<domain>.+):(?<port>\d+)$/', $domain, $matches))
164 {
165 $domain = $matches['domain'];
166 $port = $matches['port'];
167 }
168 else
169 {
170 $port = $context->getServer()->getServerPort();
171 }
172
173 $port = in_array($port, array(80, 443)) ? '' : ':'.$port;
174 $path = ltrim(trim($site['DIR'], '/') . '/pub/entry.php', '/');
175
176 $replyTo = sprintf('rpl%s@%s', $userRelation['TOKEN'], $domain);
177 $backUrl = sprintf('%s://%s%s/%s#%s', $scheme, $domain, $port, $path, $userRelation['TOKEN']);
178
179 return array($replyTo, $backUrl);
180 }
181
190 public static function getForwardTo($siteId, $userId, $entityType)
191 {
192 $cache = new \CPHPCache();
193
194 $cacheKey = sprintf('%s_%s', $userId, $entityType);
195 $cacheDir = sprintf('/mail/user/forward/%s', bin2hex($siteId));
196
197 if ($cache->initCache(365*24*3600, $cacheKey, $cacheDir))
198 {
199 $forwardTo = $cache->getVars();
200 }
201 else
202 {
203 $userRelation = UserRelationsTable::getList(array(
204 'filter' => array(
205 '=SITE_ID' => $siteId,
206 '=USER_ID' => $userId,
207 '=ENTITY_TYPE' => $entityType,
208 '=ENTITY_ID' => null
209 )
210 ))->fetch();
211
212 if (empty($userRelation))
213 {
214 $userRelation = array(
215 'SITE_ID' => $siteId,
216 'TOKEN' => base_convert(md5(time().Main\Security\Random::getBytes(6)), 16, 36),
217 'USER_ID' => $userId,
218 'ENTITY_TYPE' => $entityType
219 );
220
221 if (!UserRelationsTable::add($userRelation)->isSuccess())
222 return false;
223
224 // for dav addressbook modification label
225 $user = new \CUser;
226 $user->update($userId, array());
227 }
228
229 $site = Main\SiteTable::getByPrimary($siteId)->fetch();
230 $domain = $site['SERVER_NAME'] ?: \COption::getOptionString('main', 'server_name', '');
231
232 if (preg_match('/^(?<domain>.+):(?<port>\d+)$/', $domain, $matches))
233 $domain = $matches['domain'];
234
235 $forwardTo = sprintf('fwd%s@%s', $userRelation['TOKEN'], $domain);
236
237 $cache->startDataCache();
238 $cache->endDataCache($forwardTo);
239 }
240
241 return array($forwardTo);
242 }
243
244 public static function parseEmailRecipient($to)
245 {
246 if (!preg_match('/^(?<type>rpl|fwd)(?<token>[a-z0-9]+)@(?<domain>.+)/i', $to, $matches))
247 {
248 return false;
249 }
250 return $matches;
251 }
252
253 public static function getUserRelation($token)
254 {
255 $userRelation = UserRelationsTable::getList(array(
256 'filter' => array(
257 '=TOKEN' => $token,
258 'USER.ACTIVE' => 'Y'
259 )
260 ))->fetch();
261
262 if (!$userRelation)
263 {
264 return false;
265 }
266
267 return $userRelation;
268 }
269
278 public static function onEmailReceived($to, $message, $recipient, $userRelation, &$error)
279 {
280 $type = $recipient['type'];
281 $token = $recipient['token'];
282
283 $message['secret'] = $token;
284
285 switch ($type)
286 {
287 case 'rpl':
288 $content = Message::parseReply($message);
289 break;
290 case 'fwd':
291 $content = Message::parseForward($message);
292 break;
293 }
294
295 if (empty($content) && empty($message['files']))
296 {
297 $error = sprintf('Empty message (rcpt: %s)', $to);
298 return false;
299 }
300
301 $attachments = array_filter(
302 array_combine(
303 array_column((array) $message['files'], 'name'),
304 array_column((array) $message['files'], 'tmp_name')
305 )
306 );
307
308 $addResult = User\MessageTable::add(array(
309 'TYPE' => $type,
310 'SITE_ID' => $userRelation['SITE_ID'],
311 'ENTITY_TYPE' => $userRelation['ENTITY_TYPE'],
312 'ENTITY_ID' => $userRelation['ENTITY_ID'],
313 'USER_ID' => $userRelation['USER_ID'],
314 'SUBJECT' => $message['subject'],
315 'CONTENT' => $content,
316 'ATTACHMENTS' => serialize($attachments),
317 ));
318
319 if ($addResult->isSuccess())
320 {
321 \CAgent::addAgent(
322 "\\Bitrix\\Mail\\User::sendEventAgent(".$addResult->getId().");",
323 "mail", //module
324 "N", //period
325 10 //interval
326 );
327 return true;
328 }
329
330 return false;
331 }
332
336 public static function sendEventAgent($messageId = 0, $cnt = 0)
337 {
338 $messageId = intval($messageId);
339 if ($messageId <= 0)
340 {
341 return;
342 }
343
344 $res = User\MessageTable::getList(array(
345 'filter' => array(
346 '=ID' => $messageId
347 )
348 ));
349 if ($messageFields = $res->fetch())
350 {
351 if (intval($cnt) > 10)
352 {
353 if (Main\Loader::includeModule('im'))
354 {
355 $title = trim($messageFields['SUBJECT']);
356 if ($title == '')
357 {
358 $title = trim($messageFields['CONTENT']);
359 $title = preg_replace("/\[ATTACHMENT\s*=\s*[^\]]*\]/is".BX_UTF_PCRE_MODIFIER, "", $title);
360
361 $CBXSanitizer = new \CBXSanitizer;
362 $CBXSanitizer->delAllTags();
363 $title = $CBXSanitizer->sanitizeHtml($title);
364 }
365
366 \CIMNotify::add(array(
367 "MESSAGE_TYPE" => IM_MESSAGE_SYSTEM,
368 "NOTIFY_TYPE" => IM_NOTIFY_SYSTEM,
369 "NOTIFY_MODULE" => "mail",
370 "NOTIFY_EVENT" => "user_message_failed",
371 "TO_USER_ID" => $messageFields['USER_ID'],
372 "NOTIFY_MESSAGE" => Loc::getMessage("MAIL_USER_MESSAGE_FAILED", array(
373 "#TITLE#" => $title
374 ))
375 ));
376 }
377 User\MessageTable::delete($messageId);
378 return;
379 }
380
381 switch ($messageFields['TYPE'])
382 {
383 case 'rpl':
384 $eventId = sprintf('onReplyReceived%s', $messageFields['ENTITY_TYPE']);
385 break;
386 case 'fwd':
387 $eventId = sprintf('onForwardReceived%s', $messageFields['ENTITY_TYPE']);
388 break;
389 }
390
391 if (!empty($eventId))
392 {
393 $attachments = array();
394 if (!empty($messageFields['ATTACHMENTS']))
395 {
396 $tmpAttachments = unserialize($messageFields['ATTACHMENTS'], ['allowed_classes' => false]);
397 if (is_array($tmpAttachments))
398 {
399 foreach($tmpAttachments as $key => $uploadFile)
400 {
401 $file = \CFile::makeFileArray($uploadFile);
402 if (
403 is_array($file)
404 && !empty($file)
405 )
406 {
407 $file['name'] = $key;
408 $attachments[$key] = $file;
409 }
410 }
411 }
412 }
413
414 $event = new Main\Event(
415 'mail', $eventId,
416 array(
417 'site_id' => $messageFields['SITE_ID'],
418 'entity_id' => $messageFields['ENTITY_ID'],
419 'from' => $messageFields['USER_ID'],
420 'subject' => $messageFields['SUBJECT'],
421 'content' => $messageFields['CONTENT'],
422 'attachments' => $attachments
423 )
424 );
425 $event->send();
426
427 foreach ($event->getResults() as $eventResult)
428 {
429 if ($eventResult->getType() == \Bitrix\Main\EventResult::ERROR)
430 {
431 $cnt++;
432
433 global $pPERIOD;
434 $pPERIOD = 10 + (60 * $cnt);
435 return "\\Bitrix\\Mail\\User::sendEventAgent(".$messageId.", ".$cnt.");";
436 }
437 }
438
439 User\MessageTable::delete($messageId);
440 }
441 }
442
443 return;
444 }
445
451 public static function getMailUserGroup()
452 {
453 $res = array();
454 $mailInvitedGroup = Main\Config\Option::get("mail", "mail_invited_group", false);
455 if ($mailInvitedGroup)
456 {
457 $res[] = intval($mailInvitedGroup);
458 }
459 return $res;
460 }
461
462 public static function getDefaultEmailFrom($serverName = false)
463 {
464 if (Main\ModuleManager::isModuleInstalled('bitrix24') && defined("BX24_HOST_NAME"))
465 {
466 if(preg_match("/\\.bitrix24\\.([a-z]+|com\\.br)$/i", BX24_HOST_NAME))
467 {
468 $domain = BX24_HOST_NAME;
469 }
470 else
471 {
472 $domain = str_replace(".", "-", BX24_HOST_NAME).".bitrix24.com";
473 }
474
475 $defaultEmailFrom = "info@".$domain;
476 }
477 else
478 {
479 $defaultEmailFrom = Main\Config\Option::get('main', 'email_from', '');
480 if ($defaultEmailFrom == '')
481 {
482 $defaultEmailFrom = "info@".($serverName ?: Main\Config\Option::get('main', 'server_name', $GLOBALS["SERVER_NAME"]));
483 }
484 }
485
486 return $defaultEmailFrom;
487 }
488
489 public static function getUserData($userList, $nameTemplate)
490 {
491 $result = array();
492
493 if (
494 !is_array($userList)
495 || empty($userList)
496 )
497 {
498 return $result;
499 }
500
501 $filter = array(
502 "ID" => $userList,
503 "ACTIVE" => "Y",
504 "=EXTERNAL_AUTH_ID" => 'email'
505 );
506
507 if (
508 \IsModuleInstalled('intranet')
509 || Main\Config\Option::get("main", "new_user_registration_email_confirmation", "N") == "Y"
510 )
511 {
512 $filter["CONFIRM_CODE"] = false;
513 }
514
515 $res = \Bitrix\Main\UserTable::getList(array(
516 'order' => array(),
517 'filter' => $filter,
518 'select' => array("ID", "EMAIL", "NAME", "LAST_NAME", "SECOND_NAME", "LOGIN")
519 ));
520
521 while ($user = $res->fetch())
522 {
523 $result[$user["ID"]] = array(
524 "NAME_FORMATTED" => (
525 !empty($user["NAME"])
526 || !empty($user["LAST_NAME"])
527 ? \CUser::formatName($nameTemplate, $user)
528 : ''
529 ),
530 "EMAIL" => $user["EMAIL"]
531 );
532 }
533
534 return $result;
535 }
536
537 public static function handleSiteUpdate($fields)
538 {
539 if (array_key_exists('SERVER_NAME', $fields))
540 {
541 static::clearTokensCache();
542 }
543 }
544
545 public static function handleServerNameUpdate()
546 {
547 static::clearTokensCache();
548 }
549
550 public static function clearTokensCache()
551 {
552 $cache = new \CPHPCache();
553 $cache->cleanDir('/mail/user/forward');
554 }
555
556}
static parseReply(array &$message)
Definition message.php:326
static parseForward(array &$message)
Definition message.php:339
static onLoginExternal(&$params)
Definition user.php:84
static getReplyTo($siteId, $userId, $entityType, $entityId, $entityLink=null, $backurl=null)
Definition user.php:122
static create($fields)
Definition user.php:19
static getUserRelation($token)
Definition user.php:253
static onEmailReceived($to, $message, $recipient, $userRelation, &$error)
Definition user.php:278
static clearTokensCache()
Definition user.php:550
static getUserData($userList, $nameTemplate)
Definition user.php:489
static getMailUserGroup()
Definition user.php:451
static parseEmailRecipient($to)
Definition user.php:244
static login()
Definition user.php:67
static handleServerNameUpdate()
Definition user.php:545
static getForwardTo($siteId, $userId, $entityType)
Definition user.php:190
static sendEventAgent($messageId=0, $cnt=0)
Definition user.php:336
static getDefaultEmailFrom($serverName=false)
Definition user.php:462
static handleSiteUpdate($fields)
Definition user.php:537
static getMessage($code, $replace=null, $language=null)
Definition loc.php:29
static isModuleInstalled($moduleName)
$GLOBALS['____1444769544']
Definition license.php:1