public function sendInvoice()
{
global $USER_FIELD_MANAGER;
$result = new Main\Result();
$now = new DateTime();
$invoice = $this->invoice;
if (empty($invoice['ID']) || empty($invoice['ACCOUNT_NUMBER']))
{
$result->addError(new Main\Error('Mail sending error. Invoice data are empty!'));
return $result;
}
$message = $this->fillEmailMessage($invoice);
if(!check_email($this->dataFrom['VALUE']))
{
$result->addError(new Main\Error('Mail sending error. Wrong owner email!'));
return $result;
}
try
{
$attachmentId = static::getPdfAttachment($invoice['ID']);
if (is_bool($attachmentId))
{
if ($attachmentId === false)
{
$result->addError(new Main\Error(Loc::getMessage('CRM_ERROR_SAVING_BILL')));
}
return $result;
}
}
catch (Main\SystemException $e)
{
$result->addError(new Main\Error($e->getMessage(), $e->getCode()));
return $result;
}
$attachments = array($attachmentId);
if (!empty($this->templateData['ID']) && $this->templateData['ID'] > 0 && StorageType::getDefaultTypeId() === StorageType::Disk)
{
$files = $USER_FIELD_MANAGER->getUserFieldValue('CRM_MAIL_TEMPLATE', 'UF_ATTACHMENT', $this->templateData['ID']);
if (!empty($files) && is_array($files))
{
$diskUfManager = Disk\Driver::getInstance()->getUserFieldManager();
$diskUfManager->loadBatchAttachedObject($files);
foreach ($files as $attachedId)
{
if ($attachedObject = $diskUfManager->getAttachedObjectById($attachedId))
{
$attachments[] = $attachedObject->getObjectId();
$message['BODY'] = str_replace(
sprintf('bxacid:%u', $attachedId),
sprintf('bxacid:n%u', $attachedObject->getObjectId()),
$message['BODY']
);
}
}
}
}
$fields = array(
'OWNER_ID' => $this->dataFrom['ID'],
'OWNER_TYPE_ID' => $this->dataFrom['TYPE_ID'],
'TYPE_ID' => \CCrmActivityType::Email,
'SUBJECT' => $message['SUBJECT'],
'START_TIME' => $now,
'END_TIME' => $now,
'COMPLETED' => 'Y',
'RESPONSIBLE_ID' => $invoice['RESPONSIBLE_ID'],
'PRIORITY' => \CCrmActivityPriority::Medium,
'DESCRIPTION' => $message['BODY'],
'DESCRIPTION_TYPE' => \CCrmContentType::Html,
'DIRECTION' => \CCrmActivityDirection::Outgoing,
'LOCATION' => '',
'SETTINGS' => array('MESSAGE_FROM' => $this->dataFrom['VALUE']),
'NOTIFY_TYPE' => \CCrmActivityNotifyType::None,
'STORAGE_TYPE_ID' => StorageType::getDefaultTypeID(),
'COMMUNICATIONS' => array($this->dataTo['COMMUNICATIONS']),
'STORAGE_ELEMENT_IDS' => $attachments,
'BINDINGS' => array_values($this->dataTo['BINDINGS'])
);
if(!($id = \CCrmActivity::Add($fields, false, false, array('REGISTER_SONET_EVENT' => true))))
{
$result->addError(new Main\Error(\CCrmActivity::GetLastErrorMessage()));
return $result;
}
\CCrmActivity::SaveCommunications($id, $fields['COMMUNICATIONS'], $fields);
$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;
}
$description = $fields['DESCRIPTION'];
foreach ($attachments as $item)
{
$fileInfo = StorageManager::getFileInfo(
$item, $fields['STORAGE_TYPE_ID'], false,
array('OWNER_TYPE_ID' => \CCrmOwnerType::Activity, 'OWNER_ID' => $id)
);
$description = str_replace(
sprintf('bxacid:n%u', $item),
htmlspecialcharsbx($fileInfo['VIEW_URL']),
$description,
$count
);
if ($count > 0)
{
$descriptionUpdated = true;
}
$fileArray = StorageManager::makeFileArray($item, $fields['STORAGE_TYPE_ID']);
$contentId = sprintf(
'bxacid.%s@%s.crm',
hash('crc32b', $fileArray['external_id'].$fileArray['size'].$fileArray['name']),
hash('crc32b', $hostname)
);
$fields['DESCRIPTION'] = str_replace(
sprintf('bxacid:n%u', $item),
sprintf('cid:%s', $contentId),
$fields['DESCRIPTION']
);
}
if (!empty($descriptionUpdated))
{
\CCrmActivity::update($id, array(
'DESCRIPTION' => $description,
), false, false, array('REGISTER_SONET_EVENT' => true));
}
$sendErrors = array();
if(!\CCrmActivityEmailSender::TrySendEmail($id, $fields, $sendErrors))
{
$errorList = array();
foreach($sendErrors as $error)
{
$code = $error['CODE'];
if($code === \CCrmActivityEmailSender::ERR_CANT_LOAD_SUBSCRIBE)
{
$errors[] = 'Email send error. Failed to load module "subscribe".';
}
elseif($code === \CCrmActivityEmailSender::ERR_INVALID_DATA)
{
$errors[] = 'Email send error. Invalid data.';
}
elseif($code === \CCrmActivityEmailSender::ERR_INVALID_EMAIL)
{
$errors[] = 'Email send error. Invalid email is specified.';
}
elseif($code === \CCrmActivityEmailSender::ERR_CANT_FIND_EMAIL_FROM)
{
$errors[] = 'Email send error. "From" is not found.';
}
elseif($code === \CCrmActivityEmailSender::ERR_CANT_FIND_EMAIL_TO)
{
$errors[] = 'Email send error. "To" is not found.';
}
elseif($code === \CCrmActivityEmailSender::ERR_CANT_ADD_POSTING)
{
$errors[] = 'Email send error. Failed to add posting. Please see details below.';
}
elseif($code === \CCrmActivityEmailSender::ERR_CANT_SAVE_POSTING_FILE)
{
$errors[] = 'Email send error. Failed to save posting file. Please see details below.';
}
elseif($code === \CCrmActivityEmailSender::ERR_CANT_UPDATE_ACTIVITY)
{
$errors[] = 'Email send error. Failed to update activity.';
}
else
{
$errors[] = 'Email send error. General error.';
}
$msg = $error['MESSAGE'] ?? '';
if($msg !== '')
{
$errors[] = $msg;
}
foreach ($errors as $errorMsg)
{
$errorList[] = new Main\Error($errorMsg);
}
}
$result->addErrors($errorList);
return $result;
}
addEventToStatFile(
'crm',
'send_email_message',
sprintf('recurring_%s', $invoice['RECURRING_ID']),
trim(trim($fields['SETTINGS']['MESSAGE_HEADERS']['Message-Id']), '<>')
);
if ($result->isSuccess())
{
$result->setData(array('ACTIVITY_ID' => $id));
}
return $result;
}