• Модуль: sender
  • Путь к файлу: ~/bitrix/modules/sender/lib/contact.php
  • Класс: BitrixSenderContactTable
  • Вызов: ContactTable::upload
static function upload(array $list, bool $isBlacklist = false, ?int $listId = null)
{
	$sqlHelper = Application::getConnection()->getSqlHelper();
	$dateInsert = new MainTypeDateTime();

	$updateList = [];
	foreach ($list as $item)
	{
		if (is_string($item))
		{
			$item = ['CODE' => $item];
		}

		if (empty($item['CODE']))
		{
			continue;
		}
		$code = trim($item['CODE']);

		$typeId = RecipientType::detect($code);
		if (!$typeId)
		{
			continue;
		}

		$code = RecipientNormalizer::normalize($code, $typeId);
		if (!$code)
		{
			continue;
		}

		$updateItem = [
			'TYPE_ID' => $typeId,
			'CODE' => $code,
			'DATE_INSERT' => $dateInsert,
			'DATE_UPDATE' => $dateInsert,
			'NAME' => $sqlHelper->forSql($item['NAME']),
		];
		if ($isBlacklist)
		{
			$updateItem['BLACKLISTED'] = $isBlacklist ? 'Y' : 'N';
		}
		$updateList[] = $updateItem;
	}


	// insert contacts
	if (count($updateList) === 0)
	{
		return 0;
	}

	$onDuplicateUpdateFields = array(
		'NAME',
		array(
			'NAME' => 'BLACKLISTED',
			'VALUE' => $isBlacklist ? "'Y'" : "'N'"
		),
		array(
			'NAME' => 'DATE_UPDATE',
			'VALUE' => $sqlHelper->convertToDbDateTime(new MainTypeDateTime())
		)
	);
	foreach (InternalsSqlBatch::divide($updateList) as $list)
	{
		InternalsSqlBatch::insert(
			ContactTable::getTableName(),
			$list,
			$onDuplicateUpdateFields
		);
	}

	if (!$listId)
	{
		return count($updateList);
	}

	$row = ListTable::getRowById($listId);
	if (!$row)
	{
		return false;
	}

	// insert contacts & lists
	$codesByType = array();
	foreach ($updateList as $updateItem)
	{
		$typeId = $updateItem['TYPE_ID'];
		if (!isset($codesByType[$typeId]) || !is_array($codesByType[$typeId]))
		{
			$codesByType[$typeId] = array();
		}

		$codesByType[$typeId][] = $updateItem['CODE'];
	}
	foreach ($codesByType as $typeId => $allCodes)
	{
		$typeId = (int) $typeId;
		$listId = (int) $listId;
		$contactTableName = ContactTable::getTableName();
		$contactListTableName = ContactListTable::getTableName();
		foreach (InternalsSqlBatch::divide($allCodes) as $codes)
		{
			$codes = InternalsSqlBatch::getInString($codes);
			$sql = "INSERT IGNORE $contactListTableName ";
			$sql .="(CONTACT_ID, LIST_ID) ";
			$sql .="SELECT ID AS CONTACT_ID, $listId as LIST_ID ";
			$sql .="FROM $contactTableName ";
			$sql .="WHERE TYPE_ID=$typeId AND CODE in ($codes)";
			Application::getConnection()->query($sql);
		}
	}

	return ContactListTable::getCount(array('=LIST_ID' => $listId));
}