• Модуль: im
  • Путь к файлу: ~/bitrix/modules/im/classes/general/im_disk.php
  • Класс: CIMDisk
  • Вызов: CIMDisk::UploadFileFromDisk
static function UploadFileFromDisk($chatId, $files, $text = '', $options = [], $robot = false)
{
	if ((int)$chatId <= 0 || empty($files))
	{
		return false;
	}

	$orm = BitrixImModelChatTable::getList([
		'filter'=>[
			'=ID' => $chatId
		]
	]);
	$chat = $orm->fetch();
	if (!$chat)
	{
		return false;
	}

	if (isset($options['USER_ID']))
	{
		$userId = (int)$options['USER_ID'];
	}
	else
	{
		$userId = self::GetUserId();
		if (!$userId)
		{
			return false;
		}
	}

	$skipUserCheck = isset($options['SKIP_USER_CHECK']) && $options['SKIP_USER_CHECK'] === true;
	$linesSilentMode = isset($options['LINES_SILENT_MODE']) && $options['LINES_SILENT_MODE'] === true;
	$makeSymlink = isset($options['SYMLINK']) && $options['SYMLINK'] === true;
	$templateId = isset($options['TEMPLATE_ID']) && $options['TEMPLATE_ID'] <> '' ? $options['TEMPLATE_ID'] : '';
	$fileTemplateId = isset($options['FILE_TEMPLATE_ID']) && $options['FILE_TEMPLATE_ID'] <> '' ? $options['FILE_TEMPLATE_ID'] : '';
	$attach = $options['ATTACH'] ?? null;
	$asFile = isset($options['AS_FILE']) && $options['AS_FILE'] === 'Y';
	$params = isset($options['PARAMS']) && is_array($options['PARAMS']) ? $options['PARAMS'] : null;

	$chatRelation = CIMChat::GetRelationById($chatId, false, true, false);

	if ($chat['ENTITY_TYPE'] !== 'LIVECHAT' && $userId > 0 && !$skipUserCheck)
	{
		if (!$chatRelation[$userId])
		{
			return false;
		}

		if (
			$chat['ENTITY_TYPE'] === 'ANNOUNCEMENT'
			&& $chatRelation[$userId]['MANAGER'] !== 'Y'
		)
		{
			return false;
		}
	}

	$result = [];
	$result['FILES'] = [];
	$result['DISK_ID'] = [];
	$result['FILE_MODELS'] = [];
	foreach ($files as $fileId)
	{
		if (mb_substr($fileId, 0, 6) == 'upload')
		{
			$newFile = self::IncreaseFileVersionDisk($chatId, mb_substr($fileId, 6), $skipUserCheck? 0: $userId);
			if ($asFile)
			{
				$newFile->changeCode(IMV2LinkFileFileItem::MEDIA_ORIGINAL_CODE);
			}
		}
		else
		{
			$newFile = self::SaveFromLocalDisk($chatId, mb_substr($fileId, 4), $makeSymlink, $skipUserCheck? 0: $userId);
		}

		if ($newFile)
		{
			$result['FILES'][$fileId] = self::GetFileParams($chatId, $newFile);
			$result['DISK_ID'][] = $newFile->getId();
			$result['FILE_MODELS'][$fileId] = $newFile;

			if ($robot)
			{
				if ($userId)
				{
					// temporary - waiting for fix in Disk
					$recentItem = BitrixDiskInternalsRecentlyUsedTable::getList([
						'select' => ['ID'],
						'filter' => [
							'=USER_ID' => $userId,
							'=OBJECT_ID' => $newFile->getId()
						]
					])->fetch();

					if ($recentItem)
					{
						BitrixDiskInternalsRecentlyUsedTable::delete($recentItem['ID']);
					}
				}
			}
			else if (!$skipUserCheck)
			{
				if ($chat['ENTITY_TYPE'] == 'LINES')
				{
					if ($userId)
					{
						BitrixDiskDriver::getInstance()->getRecentlyUsedManager()->push($userId, $newFile);
					}
				}
				else if ($chat['ENTITY_TYPE'] != 'LIVECHAT')
				{
					foreach ($chatRelation as $relation)
					{
						if ($relation['MESSAGE_TYPE'] != IM_MESSAGE_PRIVATE)
						{
							break;
						}

						if ($userId == $relation['USER_ID'])
						{
							continue;
						}

						BitrixDiskDriver::getInstance()->getRecentlyUsedManager()->push($relation['USER_ID'], $newFile);
					}
				}
			}
		}
		else
		{
			$result['FILES'][$fileId]['id'] = 0;
		}
	}
	if (empty($result['DISK_ID']))
	{
		return false;
	}

	$result['MESSAGE_ID'] = 0;

	$ar = [
		"TO_CHAT_ID" => $chatId,
		"FROM_USER_ID" => $userId,
		"MESSAGE_TYPE" => $chat['TYPE'],
		"SILENT_CONNECTOR" => $linesSilentMode?'Y':'N',
		"SKIP_USER_CHECK" => ($skipUserCheck || !$userId || $chat['ENTITY_TYPE'] == 'LIVECHAT'),
		"TEMPLATE_ID" => $templateId,
		"FILE_TEMPLATE_ID" => $fileTemplateId,
	];

	if ($chat['ENTITY_TYPE'] == 'LIVECHAT')
	{
		[$lineId] = explode("|", $chat['ENTITY_ID']);
		$ar["EXTRA_PARAMS"] = [
			"CONTEXT" => "LIVECHAT",
			"LINE_ID" => $lineId
		];
		//TODO: fix 0135872
		//$ar['SKIP_CONNECTOR'] = 'Y';
	}

	$ar['FILES'] = $result['DISK_ID'];

	if ($params)
	{
		$ar['PARAMS'] = $params;
	}

	if ($attach)
	{
		$ar['ATTACH'] = $attach;
	}

	$text = trim($text);
	if ($text)
	{
		$ar["MESSAGE"] = $text;
	}

	$messageId = CIMMessage::Add($ar);
	if (!$messageId)
	{
		foreach ($result['FILE_MODELS'] as $file)
		{
			$file->delete($userId);
		}
		return false;
	}

	$result['MESSAGE_ID'] = $messageId;

	$message = new IMV2Message([
		'ID' => $messageId,
		'CHAT_ID' => $chatId,
		'AUTHOR_ID' => $userId,
	]);
	$message->setParams($params ?? []);
	(new IMV2LinkFileFileService())->saveFilesFromMessage($result['FILE_MODELS'], $message);

	if (
		!$robot
		&& !$linesSilentMode
		&& ($chat['ENTITY_TYPE'] == 'LINES' || $chat['ENTITY_TYPE'] == 'LIVECHAT')
	)
	{
		$fileIds = array_map(function($item){
			return 'disk' . $item;
		}, $result['DISK_ID']);

		$uploadResult = false;

		if ($chat['ENTITY_TYPE'] == 'LIVECHAT' && BitrixMainLoader::includeModule('imopenlines'))
		{
			[$lineId, $clientUserId] = explode("|", $chat['ENTITY_ID']);

			$session = new BitrixImopenlinesSession();
			if ($session->load([
				'USER_CODE' => 'livechat|'.$lineId.'|'.$chat['ID'].'|'.$clientUserId,
				'DEFERRED_JOIN' => 'Y',
			]))
			{
				if ($session->isNowCreated())
				{
					BitrixImOpenLinesConnector::saveCustomData($session->getData('CHAT_ID'), $_SESSION['LIVECHAT']['CUSTOM_DATA']);

					$session->joinUser();

					$messageParams = [
						'IMOL_SID' => $session->getData('ID'),
						"IMOL_FORM" => "welcome",
						"TYPE" => "lines",
						"COMPONENT_ID" => "bx-imopenlines-message",
					];
					CIMMessageParam::Set($messageId, $messageParams);
					CIMMessageParam::SendPull($messageId, array_keys($messageParams));
				}
				$session->getData('CHAT_ID');
				//TODO: fix 0135872
				/*$uploadResult = self::UploadFileFromDisk(
					$session->getData('CHAT_ID'),
					$fileIds,
					$text,
					['USER_ID' => $userId],
					true
				);*/
			}
		}

		if (
			!empty($uploadResult) &&
			$uploadResult['MESSAGE_ID'] &&
			$result['MESSAGE_ID']
		)
		{
			BitrixImModelMessageParamTable::add([
				"MESSAGE_ID" => $result['MESSAGE_ID'],
				"PARAM_NAME" => 'CONNECTOR_MID',
				"PARAM_VALUE" => $uploadResult['MESSAGE_ID']
			]);
			BitrixImModelMessageParamTable::add([
				"MESSAGE_ID" => $uploadResult['MESSAGE_ID'],
				"PARAM_NAME" => 'CONNECTOR_MID',
				"PARAM_VALUE" => $result['MESSAGE_ID']
			]);

			CIMMessageParam::SendPull($result['MESSAGE_ID'], ['CONNECTOR_MID']);
			CIMMessageParam::SendPull($uploadResult['MESSAGE_ID'], ['CONNECTOR_MID']);

			$event = new BitrixMainEvent("imopenlines", "OnLivechatUploadFile", ['FILES' => $uploadResult['DISK_ID']]);
			$event->send();
		}
	}

	return $result;
}