CCrmEMail::createOutgoingMessageActivity

  1. Bitrix24 API (v. 23.675.0)
  2. crm
  3. CCrmEMail
  4. createOutgoingMessageActivity
  • Модуль: crm
  • Путь к файлу: ~/bitrix/modules/crm/classes/general/crm_email.php
  • Класс: \CCrmEMail
  • Вызов: CCrmEMail::createOutgoingMessageActivity
static function createOutgoingMessageActivity(&$messageFields, &$activityFields)
{
	if(!CModule::IncludeModule('crm'))
	{
		return false;
	}

	$userId = isset($activityFields['RESPONSIBLE_ID']) ? (int)$activityFields['RESPONSIBLE_ID'] : \CCrmSecurityHelper::GetCurrentUserID();
	$authorId = isset($activityFields['AUTHOR_ID']) ? (int)$activityFields['AUTHOR_ID'] : $userId;
	$editorId = isset($activityFields['EDITOR_ID']) ? (int)$activityFields['EDITOR_ID'] : $userId;

	$now = convertTimeStamp(time() + \CTimeZone::getOffset(), 'FULL', SITE_ID);

	$from    = isset($messageFields['FROM']) ? $messageFields['FROM'] : '';
	$replyTo = isset($messageFields['REPLY_TO']) ? $messageFields['REPLY_TO'] : '';

	$to  = isset($messageFields['TO']) ? $messageFields['TO'] : array();
	$cc  = isset($messageFields['CC']) ? $messageFields['CC'] : array();
	$bcc = isset($messageFields['BCC']) ? $messageFields['BCC'] : array();

	$subject   = trim($messageFields['SUBJECT']) ?: getMessage('CRM_EMAIL_DEFAULT_SUBJECT');
	$body = isset($messageFields['BODY']) ? $messageFields['BODY'] : '';

	// Bindings & Communications
	$arCommunications = isset($activityFields['COMMUNICATIONS']) ? $activityFields['COMMUNICATIONS'] : array();

	$arBindings = array();
	$arComms = array();

	$socNetLogDestTypes = array(
		\CCrmOwnerType::LeadName => 'leads',
		\CCrmOwnerType::DealName => 'deals',
		\CCrmOwnerType::ContactName => 'contacts',
		\CCrmOwnerType::CompanyName => 'companies',
	);

	foreach ($arCommunications as &$commDatum)
	{
		$commID = isset($commDatum['id']) ? intval($commDatum['id']) : 0;
		$commEntityType = isset($commDatum['entityType'])? mb_strtolower(strval($commDatum['entityType'])) : '';
		$commEntityType = array_search($commEntityType, $socNetLogDestTypes);
		$commEntityID = isset($commDatum['entityId']) ? intval($commDatum['entityId']) : 0;

		$commType = isset($commDatum['type'])? mb_strtoupper(strval($commDatum['type'])) : '';
		if($commType === '')
		{
			$commType = 'EMAIL';
		}
		$commValue = isset($commDatum['value']) ? strval($commDatum['value']) : '';

		if($commType === 'EMAIL' && $commValue !== '')
		{
			if(!check_email($commValue))
			{
				// ignoring
				continue;
			}

			$rcptFieldName = 'to';
			if (isset($commDatum['__field']))
			{
				$commDatum['__field'] = mb_strtolower($commDatum['__field']);
				if (in_array($commDatum['__field'], array('to', 'cc', 'bcc')))
				{
					$rcptFieldName = $commDatum['__field'];
				}
			}

			${$rcptFieldName}[] = mb_strtolower(trim($commValue));
		}

		$key = md5(sprintf(
			'%s_%u_%s_%s',
			$commEntityType,
			$commEntityID,
			$commType,
			mb_strtolower(trim($commValue))
		));
		$arComms[$key] = array(
			'ID' => $commID,
			'TYPE' => $commType,
			'VALUE' => $commValue,
			'ENTITY_ID' => $commEntityID,
			'ENTITY_TYPE_ID' => \CCrmOwnerType::ResolveID($commEntityType)
		);

		if($commEntityType !== '')
		{
			$bindingKey = $commEntityID > 0 ? "{$commEntityType}_{$commEntityID}" : uniqid("{$commEntityType}_");
			if(!isset($arBindings[$bindingKey]))
			{
				$arBindings[$bindingKey] = array(
					'OWNER_TYPE_ID' => \CCrmOwnerType::ResolveID($commEntityType),
					'OWNER_ID' => $commEntityID
				);
			}
		}
	}
	unset($commDatum);

	$to  = array_unique($to);
	$cc  = array_unique($cc);
	$bcc = array_unique($bcc);

	// owner entity
	$ownerBounded = false;

	$ownerTypeId = 0;
	$ownerId     = 0;

	$typesPriority = array(
		\CCrmOwnerType::Contact => 2,
		\CCrmOwnerType::Company => 3,
		\CCrmOwnerType::Lead    => 4,
	);

	foreach ($arBindings as $item)
	{
		if ($ownerTypeId <= 0 || $typesPriority[$item['OWNER_TYPE_ID']] < $typesPriority[$ownerTypeId])
		{
			if (\CCrmActivity::checkUpdatePermission($item['OWNER_TYPE_ID'], $item['OWNER_ID']))
			{
				$ownerTypeId = $item['OWNER_TYPE_ID'];
				$ownerId     = $item['OWNER_ID'];

				$ownerBounded = true;
			}
		}
	}

	if (!$ownerBounded)
	{
		if (empty($arComms))
		{
			$activityFields['ERROR_CODE'] = 'ACTIVITY_COMMUNICATIONS_EMPTY_ERROR';
		}
		else
		{
			$activityFields['ERROR_CODE'] = 'ACTIVITY_PERMISSION_DENIED_ERROR';
		}

		return false;
	}


	\CCrmActivity::addEmailSignature($body, \CCrmContentType::Html);

	$activityFields = array(
		'AUTHOR_ID' => $authorId,
		'OWNER_ID' => $ownerId,
		'OWNER_TYPE_ID' => $ownerTypeId,
		'TYPE_ID' => \CCrmActivityType::Email,
		'SUBJECT' => $subject,
		'START_TIME' => $now,
		'END_TIME' => $now,
		'COMPLETED' => 'Y',
		'RESPONSIBLE_ID' => $userId,
		'EDITOR_ID' => $editorId,
		'PRIORITY' => !empty($messageFields['IMPORTANT']) && $messageFields['IMPORTANT'] ? \CCrmActivityPriority::High : \CCrmActivityPriority::Medium,
		'DESCRIPTION' => $body,
		'DESCRIPTION_TYPE' => \CCrmContentType::Html,
		'DIRECTION' => \CCrmActivityDirection::Outgoing,
		'LOCATION' => '',
		'NOTIFY_TYPE' => \CCrmActivityNotifyType::None,
		'BINDINGS' => array_values($arBindings),
		'COMMUNICATIONS' => $arComms,
	);


	$storageTypeID = isset($messageFields['STORAGE_TYPE_ID']) ? $messageFields['STORAGE_TYPE_ID'] : \CCrmActivity::GetDefaultStorageTypeID();
	$activityFields['STORAGE_TYPE_ID'] = $storageTypeID;

	if ($storageTypeID === \Bitrix\Crm\Integration\StorageType::Disk)
	{
		if (isset($messageFields['STORAGE_ELEMENT_IDS']) && is_array($messageFields['STORAGE_ELEMENT_IDS']))
		{
			$activityFields['STORAGE_ELEMENT_IDS'] =
				\Bitrix\Crm\Integration\StorageManager::filterFiles($messageFields['STORAGE_ELEMENT_IDS'], $storageTypeID, $userId);
		}
	}

	if (!($activityId = \CCrmActivity::Add($activityFields, false, false, array('REGISTER_SONET_EVENT' => true))))
	{
		$activityFields['ERROR_CODE'] = 'ACTIVITY_CREATE_ERROR';
		$activityFields['ERROR_TEXT'] = \CCrmActivity::GetLastErrorMessage();

		return false;
	}



	$activityFields['ID'] = $activityId;
	$urn = \CCrmActivity::prepareUrn($activityFields);

	$hostname = \COption::getOptionString('main', 'server_name', '') ?: 'localhost';
	if (defined('BX24_HOST_NAME') && BX24_HOST_NAME != '')
	{
		$hostname = BX24_HOST_NAME;
	}
	elseif (defined('SITE_SERVER_NAME') && SITE_SERVER_NAME != '')
	{
		$hostname = SITE_SERVER_NAME;
	}

	$messageId = sprintf('', $urn, $hostname);
	$messageFields['MSG_ID'] = $messageId;


	$arRawFiles = array();
	if (isset($activityFields['STORAGE_ELEMENT_IDS']) && !empty($activityFields['STORAGE_ELEMENT_IDS']))
	{
		foreach ((array)$activityFields['STORAGE_ELEMENT_IDS'] as $item)
		{
			$arRawFiles[$item] = \Bitrix\Crm\Integration\StorageManager::makeFileArray($item, $storageTypeID);

			$fileInfo = \Bitrix\Crm\Integration\StorageManager::getFileInfo(
				$item,
				$storageTypeID,
				false,
				array('OWNER_TYPE_ID' => \CCrmOwnerType::Activity, 'OWNER_ID' => $activityId)
			);

			$body = preg_replace(
				sprintf('/(https?:\/\/)?bxacid:n?%u/i', $item),
				htmlspecialcharsbx($fileInfo['VIEW_URL']),
				$body
			);
		}
	}

	\CCrmActivity::update($activityId, array(
		'DESCRIPTION' => $body,
		'URN' => $urn,
		'SETTINGS' => array(
			'MESSAGE_HEADERS' => array(
				'Message-Id' => $messageId,
				'Reply-To' => $replyTo,
			),
			'EMAIL_META' => array(
				'__email' => $from,
				'from' => $from,
				'replyTo' => $replyTo,
				'to' => implode(', ', $to),
				'cc' => implode(', ', $cc),
				'bcc' => implode(', ', $bcc),
			),
		),
	), false, false, array('REGISTER_SONET_EVENT' => true));


	//----------
	// Try add event to entity
	$crmEvent = new \CCrmEvent();

	$eventText = '';
	$eventText .= getMessage('CRM_EMAIL_SUBJECT').': '.$subject."\n\r";
	$eventText .= getMessage('CRM_EMAIL_FROM').': '.$from."\n\r";
	if (!empty($to))
	{
		$eventText .= getMessage('CRM_EMAIL_TO').': '.implode(',', $to)."\n\r";
	}
	if (!empty($cc))
	{
		$eventText .= 'Cc: '.implode(',', $cc)."\n\r";
	}
	if (!empty($bcc))
	{
		$eventText .= 'Bcc: '.implode(',', $bcc)."\n\r";
	}
	$eventText .= "\n\r";
	$eventText .= $body;

	$eventBindings = array();
	foreach($arBindings as $item)
	{
		$bindingEntityID = $item['OWNER_ID'];
		$bindingEntityTypeID = $item['OWNER_TYPE_ID'];
		$bindingEntityTypeName = \CCrmOwnerType::resolveName($bindingEntityTypeID);

		$eventBindings["{$bindingEntityTypeName}_{$bindingEntityID}"] = array(
			'ENTITY_TYPE' => $bindingEntityTypeName,
			'ENTITY_ID' => $bindingEntityID
		);
	}

	$crmEvent->Add(
		array(
			'ENTITY' => $eventBindings,
			'EVENT_ID' => 'MESSAGE',
			'EVENT_NAME' => $subject,
			'EVENT_TEXT_1' => $eventText,
			'FILES' => array_values($arRawFiles),
		)
	);

	return ($activityId > 0);
}

Добавить комментарий