if (!isset($_POST['TITLE']) || empty($_POST['TITLE'])) { $_REQUEST['TITLE'] = $_POST['TITLE'] = GetMessage('CRM_DEFAULT_TITLE'); } }*/ $bVarsFromForm = true; if (isset($_POST['save']) || isset($_POST['saveAndView']) || isset($_POST['saveAndAdd']) || isset($_POST['apply'])) { $content = isset($_POST['CONTENT']) ? trim($_POST['CONTENT']) : ''; $terms = isset($_POST['TERMS']) ? trim($_POST['TERMS']) : ''; $comments = isset($_POST['COMMENTS']) ? trim($_POST['COMMENTS']) : ''; $bSanContent = $content !== '' && strpos($content, '<'); $bSanTerms = $terms !== '' && strpos($terms, '<'); $bSanComments = $comments !== '' && strpos($comments, '<'); if ($bSanContent || $bSanTerms || $bSanComments) { $sanitizer = new CBXSanitizer(); $sanitizer->ApplyDoubleEncode(false); $sanitizer->SetLevel(CBXSanitizer::SECURE_LEVEL_MIDDLE); //Crutch for for Chrome line break behaviour in HTML editor. $sanitizer->AddTags(array('div' => array(), 'span' => array('style'))); if ($bSanContent) { $content = $sanitizer->SanitizeHtml($content); } if ($bSanTerms) { $terms = $sanitizer->SanitizeHtml($terms); } if ($bSanComments) { $comments = $sanitizer->SanitizeHtml($comments); } } unset($bSanContent, $bSanTerms, $bSanComments); $arFields = array('TITLE' => trim($_POST['TITLE']), 'CONTENT' => $content, 'CONTENT_TYPE' => CCrmContentType::Html, 'TERMS' => $terms, 'TERMS_TYPE' => CCrmContentType::Html, 'COMMENTS' => $comments, 'COMMENTS_TYPE' => CCrmContentType::Html, 'STATUS_ID' => trim($_POST['STATUS_ID']), 'OPENED' => isset($_POST['OPENED']) && $_POST['OPENED'] == 'Y' ? 'Y' : 'N', 'ASSIGNED_BY_ID' => (int) (is_array($_POST['ASSIGNED_BY_ID']) ? $_POST['ASSIGNED_BY_ID'][0] : $_POST['ASSIGNED_BY_ID']));
private static function SetFromTask($taskID, &$arTaskFields, &$arFields) { $isNew = !(isset($arFields['ID']) && intval($arFields['ID']) > 0); if ($isNew) { $arFields['TYPE_ID'] = CCrmActivityType::Task; $arFields['ASSOCIATED_ENTITY_ID'] = $taskID; $arFields['NOTIFY_TYPE'] = CCrmActivityNotifyType::None; } if ($isNew || isset($arTaskFields['TITLE'])) { $arFields['SUBJECT'] = isset($arTaskFields['TITLE']) ? $arTaskFields['TITLE'] : ''; } if ($isNew || isset($arTaskFields['RESPONSIBLE_ID'])) { $arFields['RESPONSIBLE_ID'] = isset($arTaskFields['RESPONSIBLE_ID']) ? intval($arTaskFields['RESPONSIBLE_ID']) : 0; } if ($isNew || isset($arTaskFields['PRIORITY'])) { // Try to convert 'task priority' to 'crm activity priority' $priorityText = isset($arTaskFields['PRIORITY']) ? strval($arTaskFields['PRIORITY']) : '0'; $priority = CCrmActivityPriority::Low; if ($priorityText === '1') { $priority = CCrmActivityPriority::Medium; } elseif ($priorityText === '2') { $priority = CCrmActivityPriority::High; } $arFields['PRIORITY'] = $priority; } if ($isNew || isset($arTaskFields['STATUS'])) { // Try to find status $completed = 'N'; if (isset($arTaskFields['STATUS'])) { $status = intval($arTaskFields['STATUS']); // COMPLETED: 5, DECLINED: 7 if ($status === 5 || $status === 7) { $completed = 'Y'; } } $arFields['COMPLETED'] = $completed; } $start = null; $end = null; if (isset($arTaskFields['DATE_START']) || isset($arTaskFields['START_DATE_PLAN'])) { // Try to find start date if (isset($arTaskFields['DATE_START']) && $arTaskFields['DATE_START'] !== false) { $start = $arTaskFields['DATE_START']; } elseif (isset($arTaskFields['START_DATE_PLAN']) && $arTaskFields['START_DATE_PLAN'] !== false) { $start = $arTaskFields['START_DATE_PLAN']; } if ($start) { $arFields['START_TIME'] = $start; } } if (isset($arTaskFields['DEADLINE']) || isset($arTaskFields['CLOSED_DATE']) || isset($arTaskFields['END_DATE_PLAN'])) { $isCompleted = isset($arFields['COMPLETED']) && $arFields['COMPLETED'] === 'Y'; // Try to find end date if (!$isCompleted && isset($arTaskFields['DEADLINE']) && $arTaskFields['DEADLINE'] !== false) { $end = $arTaskFields['DEADLINE']; } elseif ($isCompleted && isset($arTaskFields['CLOSED_DATE']) && $arTaskFields['CLOSED_DATE'] !== false) { $end = $arTaskFields['CLOSED_DATE']; } if (!$end) { if (isset($arTaskFields['END_DATE_PLAN']) && $arTaskFields['END_DATE_PLAN'] !== false) { $end = $arTaskFields['END_DATE_PLAN']; } elseif ($arFields['START_TIME']) { $end = $arFields['START_TIME']; } } if ($end) { $arFields['END_TIME'] = $end; if (!$start) { $arFields['START_TIME'] = $end; } } } if ($isNew || isset($arTaskFields['DESCRIPTION'])) { $description = isset($arTaskFields['DESCRIPTION']) ? $arTaskFields['DESCRIPTION'] : ''; $descriptionType = isset($arTaskFields['DESCRIPTION_IN_BBCODE']) && $arTaskFields['DESCRIPTION_IN_BBCODE'] === 'Y' ? CCrmContentType::BBCode : CCrmContentType::Html; if ($description !== '' && $descriptionType === CCrmContentType::Html) { $sanitizer = new CBXSanitizer(); $sanitizer->ApplyDoubleEncode(false); $sanitizer->SetLevel(CBXSanitizer::SECURE_LEVEL_MIDDLE); $description = $sanitizer->SanitizeHtml($description); } if ($description === '') { //Ignore content type if description is empty $descriptionType = CCrmContentType::PlainText; } $arFields['DESCRIPTION'] = $description; $arFields['DESCRIPTION_TYPE'] = $descriptionType; } $arTaskOwners = isset($arTaskFields['UF_CRM_TASK']) ? $arTaskFields['UF_CRM_TASK'] : array(); $arOwnerData = array(); if (!is_array($arTaskOwners)) { $arTaskOwners = array($arTaskOwners); } $arFields['BINDINGS'] = array(); if (self::TryResolveUserFieldOwners($arTaskOwners, $arOwnerData, CCrmUserType::GetTaskBindingField())) { foreach ($arOwnerData as $arOwnerInfo) { $arFields['BINDINGS'][] = array('OWNER_TYPE_ID' => CCrmOwnerType::ResolveID($arOwnerInfo['OWNER_TYPE_NAME']), 'OWNER_ID' => $arOwnerInfo['OWNER_ID']); } } }
public static function PrepareUpdate($ownerTypeID, &$arFields, &$arFieldNames, &$arFieldValues) { $sanitizer = null; $count = count($arFieldNames); $fieldMap = array(); for ($i = 0; $i < $count; $i++) { $fieldName = $arFieldNames[$i]; $fieldValue = isset($arFieldValues[$i]) ? $arFieldValues[$i] : ''; if ($fieldName === 'COMMENTS' || $fieldName === 'USER_DESCRIPTION') { if ($sanitizer === null) { $sanitizer = new CBXSanitizer(); $sanitizer->ApplyDoubleEncode(false); $sanitizer->SetLevel(CBXSanitizer::SECURE_LEVEL_MIDDLE); //Crutch for for Chrome line break behaviour in HTML editor and background button. $sanitizer->AddTags(array('div' => array(), 'span' => array('style'))); } $arFields[$fieldName] = $sanitizer->SanitizeHtml($fieldValue); } elseif (strpos($fieldName, 'FM.') === 0) { // Processing of multifield name (FM.[TYPE].[VALUE_TYPE].[ID]) $fmParts = explode('.', substr($fieldName, 3)); if (count($fmParts) === 3) { list($fmType, $fmValueType, $fmID) = $fmParts; $fmType = strval($fmType); $fmValueType = strval($fmValueType); $fmID = intval($fmID); if ($fmType !== '' && $fmValueType !== '' && $fmID > 0) { if (!isset($arFields['FM'])) { $arFields['FM'] = array(); } if (!isset($arFields['FM'][$fmType])) { $arFields['FM'][$fmType] = array(); } $arFields['FM'][$fmType][$fmID] = array('VALUE_TYPE' => $fmValueType, 'VALUE' => $fieldValue); } } } elseif (array_key_exists($fieldName, $arFields)) { $arFields[$fieldName] = $fieldValue; } $fieldMap[$fieldName] = isset($arFields[$fieldName]) ? $arFields[$fieldName] : null; } //Cleanup not changed user fields foreach ($arFields as $fieldName => $fieldValue) { if (strpos($fieldName, 'UF_') === 0 && !isset($fieldMap[$fieldName])) { unset($arFields[$fieldName]); } } if ($ownerTypeID === CCrmOwnerType::Lead || $ownerTypeID === CCrmOwnerType::Deal || $ownerTypeID === CCrmOwnerType::Contact || $ownerTypeID === CCrmOwnerType::Company) { if (isset($arFields['CREATED_BY_ID'])) { unset($arFields['CREATED_BY_ID']); } if (isset($arFields['DATE_CREATE'])) { unset($arFields['DATE_CREATE']); } if (isset($arFields['MODIFY_BY_ID'])) { unset($arFields['MODIFY_BY_ID']); } if (isset($arFields['DATE_MODIFY'])) { unset($arFields['DATE_MODIFY']); } } }
public static function EmailMessageAdd($arMessageFields, $ACTION_VARS) { if (!CModule::IncludeModule('crm')) { return false; } $date = isset($arMessageFields['FIELD_DATE']) ? $arMessageFields['FIELD_DATE'] : ''; $maxAgeDays = intval(COption::GetOptionString('crm', 'email_max_age', 7)); $maxAge = $maxAgeDays > 0 ? $maxAgeDays * 86400 : 0; if ($maxAge > 0 && $date !== '') { $now = time() + CTimeZone::GetOffset(); $timestamp = MakeTimeStamp($date, FORMAT_DATETIME); if ($now - $timestamp > $maxAge) { //Time threshold is exceeded return false; } } $crmEmail = strtolower(trim(COption::GetOptionString('crm', 'mail', ''))); $msgID = isset($arMessageFields['ID']) ? intval($arMessageFields['ID']) : 0; $mailboxID = isset($arMessageFields['MAILBOX_ID']) ? intval($arMessageFields['MAILBOX_ID']) : 0; $from = isset($arMessageFields['FIELD_FROM']) ? $arMessageFields['FIELD_FROM'] : ''; $replyTo = isset($arMessageFields['FIELD_REPLY_TO']) ? $arMessageFields['FIELD_REPLY_TO'] : ''; if ($replyTo !== '') { // Ignore FROM if REPLY_TO EXISTS $from = $replyTo; } $addresserInfo = CCrmMailHelper::ParseEmail($from); if ($crmEmail !== '' && strcasecmp($addresserInfo['EMAIL'], $crmEmail) === 0) { // Ignore emails from ourselves return false; } $to = isset($arMessageFields['FIELD_TO']) ? $arMessageFields['FIELD_TO'] : ''; $cc = isset($arMessageFields['FIELD_CC']) ? $arMessageFields['FIELD_CC'] : ''; $bcc = isset($arMessageFields['FIELD_BCC']) ? $arMessageFields['FIELD_BCC'] : ''; $addresseeEmails = array_unique(array_merge($to !== '' ? CMailUtil::ExtractAllMailAddresses($to) : array(), $cc !== '' ? CMailUtil::ExtractAllMailAddresses($cc) : array(), $bcc !== '' ? CMailUtil::ExtractAllMailAddresses($bcc) : array()), SORT_STRING); if ($mailboxID > 0) { $dbMailbox = CMailBox::GetById($mailboxID); $arMailbox = $dbMailbox->Fetch(); // POP3 mailboxes are ignored - they bound to single email if ($arMailbox && $arMailbox['SERVER_TYPE'] === 'smtp' && (empty($crmEmail) || !in_array($crmEmail, $addresseeEmails, true))) { return false; } } $subject = isset($arMessageFields['SUBJECT']) ? $arMessageFields['SUBJECT'] : ''; $body = isset($arMessageFields['BODY']) ? $arMessageFields['BODY'] : ''; $arBodyEmails = null; $userID = 0; $parentID = 0; $ownerTypeID = CCrmOwnerType::Undefined; $ownerID = 0; $addresserID = self::FindUserIDByEmail($addresserInfo['EMAIL']); $arCommEmails = $addresserID <= 0 ? array($addresserInfo['EMAIL']) : ($crmEmail !== '' ? array_diff($addresseeEmails, array($crmEmail)) : $addresseeEmails); //Trying to fix strange behaviour of array_diff under OPcache (issue #60862) $arCommEmails = array_filter($arCommEmails); $targInfo = CCrmActivity::ParseUrn(CCrmActivity::ExtractUrnFromMessage($arMessageFields, CCrmEMailCodeAllocation::GetCurrent())); $targActivity = $targInfo['ID'] > 0 ? CCrmActivity::GetByID($targInfo['ID'], false) : null; // Check URN if (!$targActivity && (!isset($targActivity['URN']) || strtoupper($targActivity['URN']) !== strtoupper($targInfo['URN']))) { $targActivity = null; } if ($targActivity) { $postingID = self::ExtractPostingID($arMessageFields); if ($postingID > 0 && isset($targActivity['ASSOCIATED_ENTITY_ID']) && intval($targActivity['ASSOCIATED_ENTITY_ID']) === $postingID) { // Ignore - it is our message. return false; } $parentID = $targActivity['ID']; $subject = CCrmActivity::ClearUrn($subject); if ($addresserID > 0) { $userID = $addresserID; } elseif (isset($targActivity['RESPONSIBLE_ID'])) { $userID = $targActivity['RESPONSIBLE_ID']; } if (isset($targActivity['OWNER_TYPE_ID'])) { $ownerTypeID = intval($targActivity['OWNER_TYPE_ID']); } if (isset($targActivity['OWNER_ID'])) { $ownerID = intval($targActivity['OWNER_ID']); } $arCommData = self::ExtractCommsFromEmails($arCommEmails); if ($ownerTypeID > 0 && $ownerID > 0) { if (empty($arCommData)) { if ($addresserID > 0) { foreach ($addresseeEmails as $email) { if ($email === $crmEmail) { continue; } $arCommData = array(self::CreateComm($ownerTypeID, $ownerID, $email)); } } else { $arCommData = array(self::CreateComm($ownerTypeID, $ownerID, $addresserInfo['EMAIL'])); } } elseif ($ownerTypeID !== CCrmOwnerType::Deal) { //Check if owner in communications. Otherwise clear owner. //There is only one exception for DEAL - it entity has no communications $isOwnerInComms = false; foreach ($arCommData as &$arCommItem) { $commEntityTypeID = isset($arCommItem['ENTITY_TYPE_ID']) ? $arCommItem['ENTITY_TYPE_ID'] : CCrmOwnerType::Undefined; $commEntityID = isset($arCommItem['ENTITY_ID']) ? $arCommItem['ENTITY_ID'] : 0; if ($commEntityTypeID === $ownerTypeID && $commEntityID === $ownerID) { $isOwnerInComms = true; break; } } unset($arCommItem); if (!$isOwnerInComms) { $ownerTypeID = CCrmOwnerType::Undefined; $ownerID = 0; } } } } else { if ($addresserID > 0) { //It is email from registred user $userID = $addresserID; if (empty($arCommEmails)) { $arBodyEmails = self::ExtractEmailsFromBody($body); //Clear system user emails if (!empty($arBodyEmails)) { foreach ($arBodyEmails as $email) { if (self::FindUserIDByEmail($email) <= 0) { $arCommEmails[] = $email; } } } } // Try to resolve communications $arCommData = self::ExtractCommsFromEmails($arCommEmails); } else { //It is email from unknown user //Try to resolve bindings from addresser $arCommData = self::ExtractCommsFromEmails($arCommEmails); if (!empty($arCommData)) { // Try to resolve responsible user foreach ($arCommData as &$arComm) { $userID = self::ResolveResponsibleID($arComm['ENTITY_TYPE_ID'], $arComm['ENTITY_ID']); if ($userID > 0) { break; } } unset($arComm); } } // Try to resolve owner by old-style method--> $arACTION_VARS = explode('&', $ACTION_VARS); for ($i = 0, $ic = count($arACTION_VARS); $i < $ic; $i++) { $v = $arACTION_VARS[$i]; if ($pos = strpos($v, '=')) { $name = substr($v, 0, $pos); ${$name} = urldecode(substr($v, $pos + 1)); } } $arTypeNames = CCrmOwnerType::GetNames(array(CCrmOwnerType::Lead, CCrmOwnerType::Deal, CCrmOwnerType::Contact, CCrmOwnerType::Company)); foreach ($arTypeNames as $typeName) { $regexVar = 'W_CRM_ENTITY_REGEXP_' . $typeName; if (empty(${$regexVar})) { continue; } $match = array(); if (preg_match('/' . ${$regexVar} . '/i' . BX_UTF_PCRE_MODIFIER, $subject, $match) === 1) { $ownerID = intval($match[1]); $ownerTypeID = CCrmOwnerType::ResolveID($typeName); break; } } // <-- Try to resolve owner by old-style method // Filter communications by owner if ($ownerTypeID > 0 && $ownerID > 0) { if (!empty($arCommData)) { foreach ($arCommData as $commKey => $arComm) { if ($arComm['ENTITY_TYPE_ID'] === $ownerTypeID && $arComm['ENTITY_ID'] === $ownerID) { continue; } unset($arCommData[$commKey]); } $arCommData = array_values($arCommData); } if (empty($arCommData)) { if ($addresserID > 0) { foreach ($addresseeEmails as $email) { if ($email === $crmEmail) { continue; } $arCommData = array(self::CreateComm($ownerTypeID, $ownerID, $email)); } } else { $arCommData = array(self::CreateComm($ownerTypeID, $ownerID, $addresserInfo['EMAIL'])); } } } } $arBindingData = self::ConvertCommsToBindings($arCommData); // Check bindings for converted leads --> // Not Existed entities are ignored. Converted leads are ignored if their associated entities (contacts, companies, deals) are contained in bindings. $arCorrectedBindingData = array(); $arConvertedLeadData = array(); foreach ($arBindingData as $bindingKey => &$arBinding) { if ($arBinding['TYPE_ID'] !== CCrmOwnerType::Lead) { if (self::IsEntityExists($arBinding['TYPE_ID'], $arBinding['ID'])) { $arCorrectedBindingData[$bindingKey] = $arBinding; } continue; } $arFields = self::GetEntity(CCrmOwnerType::Lead, $arBinding['ID'], array('STATUS_ID')); if (!is_array($arFields)) { continue; } if (isset($arFields['STATUS_ID']) && $arFields['STATUS_ID'] === 'CONVERTED') { $arConvertedLeadData[$bindingKey] = $arBinding; } else { $arCorrectedBindingData[$bindingKey] = $arBinding; } } unset($arBinding); foreach ($arConvertedLeadData as &$arConvertedLead) { $leadID = $arConvertedLead['ID']; $exists = false; $dbRes = CCrmCompany::GetListEx(array(), array('LEAD_ID' => $leadID, 'CHECK_PERMISSIONS' => 'N'), false, false, array('ID')); if ($dbRes) { while ($arRes = $dbRes->Fetch()) { if (isset($arCorrectedBindingData[self::PrepareEntityKey(CCrmOwnerType::Company, $arRes['ID'])])) { $exists = true; break; } } } if ($exists) { continue; } $dbRes = CCrmContact::GetListEx(array(), array('LEAD_ID' => $leadID, 'CHECK_PERMISSIONS' => 'N'), false, false, array('ID')); if ($dbRes) { while ($arRes = $dbRes->Fetch()) { if (isset($arCorrectedBindingData[self::PrepareEntityKey(CCrmOwnerType::Contact, $arRes['ID'])])) { $exists = true; break; } } } if ($exists) { continue; } $dbRes = CCrmDeal::GetListEx(array(), array('LEAD_ID' => $leadID, 'CHECK_PERMISSIONS' => 'N'), false, false, array('ID')); if ($dbRes) { while ($arRes = $dbRes->Fetch()) { if (isset($arCorrectedBindingData[self::PrepareEntityKey(CCrmOwnerType::Deal, $arRes['ID'])])) { $exists = true; break; } } } if ($exists) { continue; } $arCorrectedBindingData[self::PrepareEntityKey(CCrmOwnerType::Lead, $leadID)] = $arConvertedLead; } unset($arConvertedLead); $arBindingData = $arCorrectedBindingData; // <-- Check bindings for converted leads // If no bindings are found then create new lead from this message // Skip lead creation if email list is empty. Otherwise we will create lead with no email-addresses. It is absolutely useless. $emailQty = count($arCommEmails); if (empty($arBindingData) && $emailQty > 0) { if (strtoupper(COption::GetOptionString('crm', 'email_create_lead_for_new_addresser', 'Y')) !== 'Y') { // Creation of new lead is not allowed return true; } //"Lead from forwarded email..." or "Lead from email..." $title = GetMessage($addresserID > 0 ? 'CRM_MAIL_LEAD_FROM_USER_EMAIL_TITLE' : 'CRM_MAIL_LEAD_FROM_EMAIL_TITLE', array('%SENDER%' => $addresserInfo['ORIGINAL'])); $comment = ''; if ($body !== '') { // Remove extra new lines (fix for #31807) $comment = preg_replace("/(\r\n|\n|\r)+/", '<br/>', $body); } if ($comment === '') { $comment = $subject; } $name = ''; if ($addresserID <= 0) { $name = $addresserInfo['NAME']; } else { //Try get name from body for ($i = 0; $i < $emailQty; $i++) { $email = $arCommEmails[$i]; $match = array(); if (preg_match('/"([^"]+)"\\s*<' . $email . '>/i' . BX_UTF_PCRE_MODIFIER, $body, $match) === 1 && count($match) > 1) { $name = $match[1]; break; } if (preg_match('/"([^"]+)"\\s*[\\s*mailto\\:\\s*' . $email . ']/i' . BX_UTF_PCRE_MODIFIER, $body, $match) === 1 && count($match) > 1) { $name = $match[1]; break; } } if ($name === '') { $name = $arCommEmails[0]; } } $arLeadFields = array('TITLE' => $title, 'NAME' => $name, 'STATUS_ID' => 'NEW', 'COMMENTS' => $comment, 'SOURCE_ID' => 'EMAIL', 'SOURCE_DESCRIPTION' => GetMessage('CRM_MAIL_LEAD_FROM_EMAIL_SOURCE', array('%SENDER%' => $addresserInfo['ORIGINAL'])), 'OPENED' => 'Y', 'FM' => array('EMAIL' => array())); $responsibleID = intval(COption::GetOptionString('crm', 'email_lead_responsible_id', 0)); if ($responsibleID > 0) { $arLeadFields['CREATED_BY_ID'] = $arLeadFields['MODIFY_BY_ID'] = $arLeadFields['ASSIGNED_BY_ID'] = $responsibleID; if ($userID === 0) { $userID = $responsibleID; } } for ($i = 0; $i < $emailQty; $i++) { $arLeadFields['FM']['EMAIL']['n' . ($i + 1)] = array('VALUE_TYPE' => 'WORK', 'VALUE' => $arCommEmails[$i]); } $leadEntity = new CCrmLead(false); $leadID = $leadEntity->Add($arLeadFields, true, array('DISABLE_USER_FIELD_CHECK' => true, 'REGISTER_SONET_EVENT' => true, 'CURRENT_USER' => $responsibleID)); // TODO: log error if ($leadID > 0) { $arBizProcErrors = array(); CCrmBizProcHelper::AutoStartWorkflows(CCrmOwnerType::Lead, $leadID, CCrmBizProcEventType::Create, $arBizProcErrors); $arCommData = array(); for ($i = 0; $i < $emailQty; $i++) { $arCommData[] = self::CreateComm(CCrmOwnerType::Lead, $leadID, $arCommEmails[$i]); } $arBindingData = array(self::PrepareEntityKey(CCrmOwnerType::Lead, $leadID) => self::CreateBinding(CCrmOwnerType::Lead, $leadID)); } } // Terminate processing if no bindings are found. if (empty($arBindingData)) { // Try to export vcf-files before exit if email from registered user if ($addresserID > 0) { $dbAttachment = CMailAttachment::GetList(array(), array('MESSAGE_ID' => $msgID)); while ($arAttachment = $dbAttachment->Fetch()) { if (GetFileExtension(strtolower($arAttachment['FILE_NAME'])) === 'vcf') { self::TryImportVCard($arAttachment['FILE_DATA']); } } } return false; } // If owner info not defined set it by default if ($ownerID <= 0 || $ownerTypeID <= 0) { if (count($arBindingData) > 1) { // Search owner in specified order: Contact, Company, Lead. $arTypeIDs = array(CCrmOwnerType::Contact, CCrmOwnerType::Company, CCrmOwnerType::Lead); foreach ($arTypeIDs as $typeID) { foreach ($arBindingData as &$arBinding) { if ($arBinding['TYPE_ID'] === $typeID) { $ownerTypeID = $typeID; $ownerID = $arBinding['ID']; break; } } unset($arBinding); if ($ownerID > 0 && $ownerTypeID > 0) { break; } } } if ($ownerID <= 0 || $ownerTypeID <= 0) { $arBinding = array_shift(array_values($arBindingData)); $ownerTypeID = $arBinding['TYPE_ID']; $ownerID = $arBinding['ID']; } } // Precessing of attachments --> $attachmentMaxSizeMb = intval(COption::GetOptionString('crm', 'email_attachment_max_size', 16)); $attachmentMaxSize = $attachmentMaxSizeMb > 0 ? $attachmentMaxSizeMb * 1048576 : 0; $arFilesData = array(); $dbAttachment = CMailAttachment::GetList(array(), array('MESSAGE_ID' => $msgID)); $arBannedAttachments = array(); while ($arAttachment = $dbAttachment->Fetch()) { if ($arAttachment['FILE_NAME'] === '1.tmp') { // HACK: For bug in module 'Mail' continue; } elseif (GetFileExtension(strtolower($arAttachment['FILE_NAME'])) === 'vcf') { self::TryImportVCard($arAttachment['FILE_DATA']); } $fileSize = isset($arAttachment['FILE_SIZE']) ? intval($arAttachment['FILE_SIZE']) : 0; if ($fileSize <= 0) { //Skip zero lenth files continue; } if ($attachmentMaxSize > 0 && $fileSize > $attachmentMaxSize) { //File size limit is exceeded $arBannedAttachments[] = array('name' => $arAttachment['FILE_NAME'], 'size' => $fileSize); continue; } $arFilesData[] = array('name' => $arAttachment['FILE_NAME'], 'type' => $arAttachment['CONTENT_TYPE'], 'content' => $arAttachment['FILE_DATA'], 'MODULE_ID' => 'crm'); } //<-- Precessing of attachments // Remove extra new lines (fix for #31807) $body = preg_replace("/(\r\n|\n|\r)+/", PHP_EOL, $body); $sanitizer = new CBXSanitizer(); $sanitizer->ApplyDoubleEncode(false); $sanitizer->SetLevel(CBXSanitizer::SECURE_LEVEL_MIDDLE); $sanitizedBody = $sanitizer->SanitizeHtml($body); // Creating of new event --> $arEventBindings = array(); foreach ($arBindingData as &$arBinding) { $arEventBindings[] = array('ENTITY_TYPE' => $arBinding['TYPE_NAME'], 'ENTITY_ID' => $arBinding['ID']); } unset($arBinding); $eventText = ''; $eventText .= '<b>' . GetMessage('CRM_EMAIL_SUBJECT') . '</b>: ' . $subject . PHP_EOL; $eventText .= '<b>' . GetMessage('CRM_EMAIL_FROM') . '</b>: ' . $addresserInfo['EMAIL'] . PHP_EOL; $eventText .= '<b>' . GetMessage('CRM_EMAIL_TO') . '</b>: ' . implode($addresseeEmails, '; ') . PHP_EOL; if (!empty($arBannedAttachments)) { $eventText .= '<b>' . GetMessage('CRM_EMAIL_BANNENED_ATTACHMENTS', array('%MAX_SIZE%' => $attachmentMaxSizeMb)) . '</b>: '; foreach ($arBannedAttachments as &$attachmentInfo) { $eventText .= GetMessage('CRM_EMAIL_BANNENED_ATTACHMENT_INFO', array('%NAME%' => $attachmentInfo['name'], '%SIZE%' => round($attachmentInfo['size'] / 1048576, 1))); } unset($attachmentInfo); $eventText .= PHP_EOL; } $eventText .= $sanitizedBody; $CCrmEvent = new CCrmEvent(); $CCrmEvent->Add(array('USER_ID' => $userID, 'ENTITY' => array_values($arEventBindings), 'ENTITY_TYPE' => CCrmOwnerType::ResolveName($ownerTypeID), 'ENTITY_ID' => $ownerID, 'EVENT_NAME' => GetMessage('CRM_EMAIL_GET_EMAIL'), 'EVENT_TYPE' => 2, 'EVENT_TEXT_1' => $eventText, 'FILES' => $arFilesData), false); // <-- Creating of new event // Creating new activity --> $siteID = ''; $dbSites = CSite::GetList($by = 'sort', $order = 'desc', array('DEFAULT' => 'Y', 'ACTIVE' => 'Y')); $defaultSite = is_object($dbSites) ? $dbSites->Fetch() : null; if (is_array($defaultSite)) { $siteID = $defaultSite['LID']; } if ($siteID === '') { $siteID = 's1'; } $storageTypeID = CCrmActivity::GetDefaultStorageTypeID(); $arElementIDs = array(); foreach ($arFilesData as $fileData) { $fileID = CFile::SaveFile($fileData, 'crm'); if ($fileID > 0) { $elementID = StorageManager::saveEmailAttachment(CFile::GetFileArray($fileID), $storageTypeID, $siteID); if (is_int($elementID) && $elementID > 0) { $arElementIDs[] = $elementID; } } } $descr = preg_replace("/(\r\n|\n|\r)+/", '<br/>', $sanitizedBody); $now = ConvertTimeStamp(time() + CTimeZone::GetOffset(), 'FULL', $siteID); $arActivityFields = array('OWNER_ID' => $ownerID, 'OWNER_TYPE_ID' => $ownerTypeID, 'TYPE_ID' => CCrmActivityType::Email, 'ASSOCIATED_ENTITY_ID' => 0, 'PARENT_ID' => $parentID, 'SUBJECT' => $subject, 'START_TIME' => $now, 'END_TIME' => $now, 'COMPLETED' => 'N', 'AUTHOR_ID' => $userID, 'RESPONSIBLE_ID' => $userID, 'PRIORITY' => CCrmActivityPriority::Medium, 'DESCRIPTION' => $descr, 'DESCRIPTION_TYPE' => CCrmContentType::Html, 'DIRECTION' => CCrmActivityDirection::Incoming, 'LOCATION' => '', 'NOTIFY_TYPE' => CCrmActivityNotifyType::None, 'STORAGE_TYPE_ID' => $storageTypeID, 'STORAGE_ELEMENT_IDS' => $arElementIDs); $arActivityFields['BINDINGS'] = array(); foreach ($arBindingData as &$arBinding) { $entityTypeID = $arBinding['TYPE_ID']; $entityID = $arBinding['ID']; if ($entityTypeID <= 0 || $entityID <= 0) { continue; } $arActivityFields['BINDINGS'][] = array('OWNER_TYPE_ID' => $entityTypeID, 'OWNER_ID' => $entityID); } unset($arBinding); $activityID = CCrmActivity::Add($arActivityFields, false, false, array('REGISTER_SONET_EVENT' => true)); if ($activityID > 0 && !empty($arCommData)) { CCrmActivity::SaveCommunications($activityID, $arCommData, $arActivityFields, false, false); $arActivityFields['COMMUNICATIONS'] = $arCommData; } //Notity responsible user if ($userID > 0) { CCrmActivity::Notify($arActivityFields, CCrmNotifierSchemeType::IncomingEmail); } // <-- Creating new activity return true; }
public static function update($params) { global $DB; $ID = CCrmInvoiceRestUtil::getParamScalar($params, 'id', 0); if ($ID <= 0) { throw new RestException('Invalid identifier.'); } $invoice = new CCrmInvoice(); if (!CCrmInvoice::CheckUpdatePermission($ID)) { throw new RestException('Access denied.'); } $fields = CCrmInvoiceRestUtil::getParamArray($params, 'fields'); $fields = self::filterFields($fields, 'update'); // sanitize $updateComments = isset($fields['COMMENTS']); $updateUserDescription = isset($fields['USER_DESCRIPTION']); $comments = $updateComments ? trim($fields['COMMENTS']) : ''; $userDescription = $updateUserDescription ? trim($fields['USER_DESCRIPTION']) : ''; $bSanitizeComments = $comments !== '' && strpos($comments, '<'); $bSanitizeUserDescription = $userDescription !== '' && strpos($userDescription, '<'); if ($bSanitizeComments || $bSanitizeUserDescription) { $sanitizer = new CBXSanitizer(); $sanitizer->ApplyDoubleEncode(false); $sanitizer->SetLevel(CBXSanitizer::SECURE_LEVEL_MIDDLE); //Crutch for for Chrome line break behaviour in HTML editor. $sanitizer->AddTags(array('div' => array())); if ($bSanitizeComments) { $fields['COMMENTS'] = $sanitizer->SanitizeHtml($fields['COMMENTS']); } if ($bSanitizeUserDescription) { $fields['USER_DESCRIPTION'] = $sanitizer->SanitizeHtml($fields['USER_DESCRIPTION']); } unset($sanitizer); } unset($bSanitizeComments, $bSanitizeUserDescription); if ($updateComments) { $fields['COMMENTS'] = $comments; } if ($updateUserDescription) { $fields['USER_DESCRIPTION'] = $userDescription; } unset($updateComments, $updateUserDescription, $comments, $userDescription); if (!is_array($fields) || count($fields) === 0) { throw new RestException('Invalid parameters.'); } $origFields = self::getInvoiceDataByID($ID); $origFields = self::filterFields($origFields, 'update'); foreach ($origFields as $fName => $fValue) { if (!array_key_exists($fName, $fields)) { $fields[$fName] = $fValue; } } $bStatusSuccess = CCrmStatusInvoice::isStatusSuccess($fields['STATUS_ID']); if ($bStatusSuccess) { $bStatusFailed = false; } else { $bStatusFailed = CCrmStatusInvoice::isStatusFailed($fields['STATUS_ID']); } if (!$invoice->CheckFields($fields, false, $bStatusSuccess, $bStatusFailed)) { if (!empty($invoice->LAST_ERROR)) { throw new RestException($invoice->LAST_ERROR); } else { throw new RestException('Error on check fields.'); } } $propsInfo = CCrmInvoice::GetPropertiesInfo($fields['PERSON_TYPE_ID']); $propsInfo = is_array($propsInfo[$fields['PERSON_TYPE_ID']]) ? $propsInfo[$fields['PERSON_TYPE_ID']] : array(); $invoiceProperties = array(); foreach ($propsInfo as $propCode => $arProp) { if (array_key_exists($propCode, $fields['INVOICE_PROPERTIES'])) { $invoiceProperties[$arProp['ID']] = $fields['INVOICE_PROPERTIES'][$propCode]; } else { if ($propCode === 'COMPANY_NAME' && array_key_exists('COMPANY', $fields['INVOICE_PROPERTIES'])) { $invoiceProperties[$arProp['ID']] = $fields['INVOICE_PROPERTIES']['COMPANY']; } else { if (is_array($origFields['INVOICE_PROPERTIES'])) { if (array_key_exists($propCode, $origFields['INVOICE_PROPERTIES'])) { $invoiceProperties[$arProp['ID']] = $origFields['INVOICE_PROPERTIES'][$propCode]; } else { if ($propCode === 'COMPANY_NAME' && array_key_exists('COMPANY', $fields['INVOICE_PROPERTIES'])) { $invoiceProperties[$arProp['ID']] = $origFields['INVOICE_PROPERTIES']['COMPANY']; } } } } } } $fields['INVOICE_PROPERTIES'] = $invoiceProperties; unset($propsInfo, $invoiceProperties, $propCode, $arProp); $DB->StartTransaction(); $ID = $invoice->Update($ID, $fields, array('UPDATE_SEARCH' => true)); if (!is_int($ID) || $ID <= 0) { $DB->Rollback(); if (!empty($invoice->LAST_ERROR)) { throw new RestException($invoice->LAST_ERROR); } else { throw new RestException('Error on updating invoice.'); } } else { $DB->Commit(); } return $ID; }
protected function tryInternalizeProductPropertyField(&$fields, &$fieldsInfo, $fieldName) { static $sanitizer = null; if (!is_array($fields) || !isset($fields[$fieldName])) { return; } $info = isset($fieldsInfo[$fieldName]) ? $fieldsInfo[$fieldName] : null; $rawValue = isset($fields[$fieldName]) ? $fields[$fieldName] : null; if (!$info) { unset($fields[$fieldName]); return; } $attrs = isset($info['ATTRIBUTES']) ? $info['ATTRIBUTES'] : array(); $fieldType = isset($info['TYPE']) ? $info['TYPE'] : ''; $propertyType = isset($info['PROPERTY_TYPE']) ? $info['PROPERTY_TYPE'] : ''; $userType = isset($info['USER_TYPE']) ? $info['USER_TYPE'] : ''; if ($fieldType === 'product_property') { $value = array(); $newIndex = 0; $valueId = 'n' . $newIndex; if (!self::isIndexedArray($rawValue)) { $rawValue = array($rawValue); } foreach ($rawValue as $valueElement) { if (isset($valueElement['value'])) { $valueId = intval($valueElement['valueId']) > 0 ? intval($valueElement['valueId']) : 'n' . $newIndex++; } $value[$valueId] =& $valueElement['value']; } unset($rawValue, $valueElement); foreach ($value as $valueId => $v) { if ($propertyType === 'S' && $userType === 'Date') { $date = CRestUtil::unConvertDate($v); if (is_string($date)) { $value[$valueId] = $date; } else { unset($value[$valueId]); } } elseif ($propertyType === 'S' && $userType === 'DateTime') { $datetime = CRestUtil::unConvertDateTime($v); if (is_string($datetime)) { $value[$valueId] = $datetime; } else { unset($value[$valueId]); } } elseif ($propertyType === 'F' && empty($userType)) { $this->tryInternalizeProductFileField($value, $valueId); } elseif ($propertyType === 'S' && $userType === 'HTML') { if (is_array($v) && isset($v['TYPE']) && isset($v['TEXT']) && strtolower($v['TYPE']) === 'html' && !empty($v['TEXT'])) { if ($sanitizer === null) { $sanitizer = new CBXSanitizer(); $sanitizer->ApplyDoubleEncode(false); $sanitizer->SetLevel(CBXSanitizer::SECURE_LEVEL_LOW); } $value[$valueId]['TEXT'] = $sanitizer->SanitizeHtml($v['TEXT']); } } } $fields[$fieldName] = $value; } else { unset($fields[$fieldName]); } }