Beispiel #1
0
 public static function SyncModifyTaskItem($arModifyEventArray)
 {
     global $DB;
     $ID = $arModifyEventArray["ID"];
     // sanitize description here
     $Sanitizer = new CBXSanitizer();
     $Sanitizer->SetLevel(CBXSanitizer::SECURE_LEVEL_LOW);
     $Sanitizer->ApplyHtmlSpecChars(false);
     $Sanitizer->DeleteSanitizedTags(true);
     $arModifyEventArray['BODY'] = trim($Sanitizer->SanitizeHtml($arModifyEventArray['BODY']));
     $arFields = array("RESPONSIBLE_ID" => $arModifyEventArray["USER_ID"], "SITE_ID" => SITE_ID, "EXCHANGE_ID" => $arModifyEventArray["XML_ID"], "EXCHANGE_MODIFIED" => $arModifyEventArray["MODIFICATION_LABEL"], "TITLE" => $arModifyEventArray["SUBJECT"], "DESCRIPTION" => $arModifyEventArray["BODY"], "DESCRIPTION_IN_BBCODE" => 'N', "CREATED_DATE" => $arModifyEventArray["DATE_CREATE"], "PRIORITY" => self::$PriorityMapping[strtolower($arModifyEventArray["IMPORTANCE"])], "DURATION_FACT" => ceil($arModifyEventArray["ACTUAL_WORK"] / 60), "START_DATE_PLAN" => $arModifyEventArray["START_DATE"], "DEADLINE" => $arModifyEventArray["DUE_DATE"], "STATUS" => self::$StatusMapping[strtolower($arModifyEventArray["STATUS"])], "DURATION_PLAN" => ceil($arModifyEventArray["TOTAL_WORK"] / 60), "DURATION_TYPE" => "hours");
     $arExtraFields = array();
     if (isset($arModifyEventArray['ExtendedProperty']) && is_array($arModifyEventArray['ExtendedProperty'])) {
         foreach ($arModifyEventArray['ExtendedProperty'] as $arExtendedProperty) {
             $arExtraFields[$arExtendedProperty['Name']] = $arExtendedProperty['Value'];
         }
     }
     if ($ID == 0) {
         $arFields["STATUS_CHANGED_BY"] = $arFields["CHANGED_BY"] = $arFields["CREATED_BY"] = $arFields["RESPONSIBLE_ID"];
         $arFields["STATUS_CHANGED_DATE"] = $arFields["CHANGED_DATE"] = $arFields["CREATED_DATE"];
         $ID = $DB->Add("b_tasks", $arFields, array("DESCRIPTION"), "tasks");
         if ($ID) {
             $arFields["ID"] = $ID;
             CTaskNotifications::SendAddMessage($arFields);
             $arLogFields = array("TASK_ID" => $ID, "USER_ID" => $arFields["CREATED_BY"], "CREATED_DATE" => $arFields["CREATED_DATE"], "FIELD" => "NEW");
             $log = new CTaskLog();
             $log->Add($arLogFields);
         }
     } else {
         $strUpdate = $DB->PrepareUpdate("b_tasks", $arFields, "tasks");
         $strSql = "UPDATE b_tasks SET " . $strUpdate . " WHERE ID=" . $ID;
         $arBinds = array('DESCRIPTION' => $arFields['DESCRIPTION']);
         $result = $DB->QueryBind($strSql, $arBinds, false, "File: " . __FILE__ . "<br>Line: " . __LINE__);
         if ($result) {
             $rsTask = CTasks::GetByID($ID, false);
             if ($arTask = $rsTask->Fetch()) {
                 $arFields["CHANGED_BY"] = $arFields["RESPONSIBLE_ID"];
                 $arFields["CHANGED_DATE"] = date($DB->DateFormatToPHP(CSite::GetDateFormat("FULL")), time() + CTimeZone::GetOffset());
                 CTaskNotifications::SendUpdateMessage($arFields, $arTask);
                 $arChanges = CTaskLog::GetChanges($arTask, $arFields);
                 foreach ($arChanges as $key => $value) {
                     $arLogFields = array("TASK_ID" => $ID, "USER_ID" => $arFields["CHANGED_BY"], "CREATED_DATE" => $arFields["CHANGED_DATE"], "FIELD" => $key, "FROM_VALUE" => $value["FROM_VALUE"], "TO_VALUE" => $value["TO_VALUE"]);
                     $log = new CTaskLog();
                     $log->Add($arLogFields);
                 }
             }
         }
     }
 }
Beispiel #2
0
             if ($productID > 0 && isset($products[$productID]) && $products[$productID] !== '') {
                 $productRow['PRODUCT_NAME'] = $products[$productID];
                 $productRow['CUSTOMIZED'] = 'Y';
             } else {
                 unset($productRow[$productRowKey]);
             }
         }
         unset($productRow);
     }
 }
 if (empty($productRows)) {
     __CrmMobileInvoiceEditEndResonse(array('ERROR' => GetMessage('CRM_INVOICE_PRODUCT_ROWS_ARE_EMPTY')));
 }
 //<-- PRODUCT_ROWS
 // COMMENTS & USER_DESCRIPTION -->
 $sanitizer = new CBXSanitizer();
 $sanitizer->SetLevel(CBXSanitizer::SECURE_LEVEL_HIGH);
 $comments = isset($data['COMMENTS']) ? trim($data['COMMENTS']) : '';
 if ($comments !== '') {
     $comments = $sanitizer->SanitizeHtml($comments);
 }
 $userDescription = isset($data['USER_DESCRIPTION']) ? trim($data['USER_DESCRIPTION']) : '';
 if ($userDescription !== '') {
     $userDescription = $sanitizer->SanitizeHtml($userDescription);
 }
 //<-- COMMENTS & USER_DESCRIPTION
 $responsibleID = max(isset($data['RESPONSIBLE_ID']) ? intval($data['RESPONSIBLE_ID']) : 0, 0);
 if ($responsibleID == 0) {
     $responsibleID = CCrmSecurityHelper::GetCurrentUserID();
 }
 $arFields = array('ID' => $ID, 'ORDER_TOPIC' => $topic, 'STATUS_ID' => $statusID, 'CURRENCY' => $currencyID, 'PAY_SYSTEM_ID' => $resolvedPaySystemID, 'PERSON_TYPE_ID' => $resolvedPersonTypeID, 'RESPONSIBLE_ID' => $responsibleID, 'UF_DEAL_ID' => $dealID, 'UF_COMPANY_ID' => $companyID, 'UF_CONTACT_ID' => $contactID, 'COMMENTS' => $comments, 'USER_DESCRIPTION' => $userDescription, 'PRODUCT_ROWS' => $productRows);
Beispiel #3
0
 public static function GetHtml()
 {
     global $CACHE_MANAGER;
     $arNotify = false;
     if ($CACHE_MANAGER->Read(86400, "admin_notify_list_" . LANGUAGE_ID)) {
         $arNotify = $CACHE_MANAGER->Get("admin_notify_list_" . LANGUAGE_ID);
     }
     if ($arNotify === false) {
         $arNotify = array();
         $CBXSanitizer = new CBXSanitizer();
         $CBXSanitizer->AddTags(array('a' => array('href', 'style'), 'b' => array(), 'u' => array(), 'i' => array(), 'br' => array(), 'span' => array('style')));
         $dbRes = self::GetList();
         while ($ar = $dbRes->Fetch()) {
             $ar["MESSAGE"] = $CBXSanitizer->SanitizeHtml('' != $ar['MESSAGE_LANG'] ? $ar['MESSAGE_LANG'] : $ar['MESSAGE']);
             $arNotify[] = $ar;
         }
         $CACHE_MANAGER->Set("admin_notify_list_" . LANGUAGE_ID, $arNotify);
     }
     $html = "";
     foreach ($arNotify as $value) {
         $html .= '<div class="adm-warning-block" data-id="' . intval($value['ID']) . '" data-ajax="Y"><span class="adm-warning-text">' . $value['MESSAGE'] . '</span><span class="adm-warning-icon"></span>' . ($value['ENABLE_CLOSE'] == 'Y' ? '<span onclick="BX.adminPanel ? BX.adminPanel.hideNotify(this.parentNode) : BX.admin.panel.hideNotify(this.parentNode);" class="adm-warning-close"></span>' : '') . '</div>';
     }
     return $html;
 }
Beispiel #4
0
 /**
  * @deprecated For compability only will be erased next versions
  */
 public static function SetTags($arTags)
 {
     self::$arOldTags = $arTags;
     /* for next version
     			$this->DelAllTags();
     
     			return $this->AddTags($arTags);
     			*/
 }
Beispiel #5
0
function GetPropertyInfo($strPrefix, $ID, $boolUnpack = true, $arHiddenPropFields = array())
{
    global $arDefPropInfo;
    $boolUnpack = $boolUnpack === true;
    $arResult = false;
    if (!is_array($arHiddenPropFields)) {
        return $arResult;
    }
    if (isset($_POST[$strPrefix . $ID . '_NAME']) && 0 < strlen($_POST[$strPrefix . $ID . '_NAME']) && isset($_POST[$strPrefix . $ID . '_PROPINFO'])) {
        $strEncodePropInfo = $_POST[$strPrefix . $ID . '_PROPINFO'];
        $strPropInfo = base64_decode($strEncodePropInfo);
        if (CheckSerializedData($strPropInfo)) {
            $arResult = array('ID' => isset($_POST[$strPrefix . $ID . '_ID']) && 0 < intval($_POST[$strPrefix . $ID . '_ID']) ? intval($_POST[$strPrefix . $ID . '_ID']) : 0, 'NAME' => strval($_POST[$strPrefix . $ID . "_NAME"]), 'SORT' => 0 < intval($_POST[$strPrefix . $ID . "_SORT"]) ? intval($_POST[$strPrefix . $ID . "_SORT"]) : 500, 'CODE' => isset($_POST[$strPrefix . $ID . "_CODE"]) ? strval($_POST[$strPrefix . $ID . "_CODE"]) : '', 'MULTIPLE' => isset($_POST[$strPrefix . $ID . "_MULTIPLE"]) && 'Y' == $_POST[$strPrefix . $ID . "_MULTIPLE"] ? 'Y' : 'N', 'IS_REQUIRED' => isset($_POST[$strPrefix . $ID . "_IS_REQUIRED"]) && 'Y' == $_POST[$strPrefix . $ID . "_IS_REQUIRED"] ? 'Y' : 'N', 'ACTIVE' => isset($_POST[$strPrefix . $ID . "_ACTIVE"]) && 'Y' == $_POST[$strPrefix . $ID . "_ACTIVE"] ? 'Y' : 'N', 'USER_TYPE' => false);
            if (isset($_POST[$strPrefix . $ID . "_PROPERTY_TYPE"])) {
                if (false !== strpos($_POST[$strPrefix . $ID . "_PROPERTY_TYPE"], ":")) {
                    list($arResult["PROPERTY_TYPE"], $arResult["USER_TYPE"]) = explode(':', $_POST[$strPrefix . $ID . "_PROPERTY_TYPE"], 2);
                } else {
                    $arResult["PROPERTY_TYPE"] = $_POST[$strPrefix . $ID . "_PROPERTY_TYPE"];
                }
            }
            if ($boolUnpack) {
                $arPropInfo = unserialize($strPropInfo);
                foreach ($arHiddenPropFields as &$strFieldKey) {
                    $arResult[$strFieldKey] = isset($arPropInfo[$strFieldKey]) ? $arPropInfo[$strFieldKey] : $arDefPropInfo[$strFieldKey];
                }
                $arResult['ROW_COUNT'] = intval($arResult['ROW_COUNT']);
                if (0 >= $arResult['ROW_COUNT']) {
                    $arResult['ROW_COUNT'] = $arDefPropInfo['ROW_COUNT'];
                }
                $arResult['COL_COUNT'] = intval($arResult['COL_COUNT']);
                if (0 >= $arResult['COL_COUNT']) {
                    $arResult['COL_COUNT'] = $arDefPropInfo['COL_COUNT'];
                }
                $arResult['LINK_IBLOCK_ID'] = intval($arResult['LINK_IBLOCK_ID']);
                if (0 > $arResult['LINK_IBLOCK_ID']) {
                    $arResult['LINK_IBLOCK_ID'] = $arDefPropInfo['LINK_IBLOCK_ID'];
                }
                $arResult['WITH_DESCRIPTION'] = 'Y' == $arResult['WITH_DESCRIPTION'] ? 'Y' : 'N';
                $arResult['FILTRABLE'] = 'Y' == $arResult['FILTRABLE'] ? 'Y' : 'N';
                $arResult['SEARCHABLE'] = 'Y' == $arResult['SEARCHABLE'] ? 'Y' : 'N';
                $arResult['SECTION_PROPERTY'] = 'N' == $arResult['SECTION_PROPERTY'] ? 'N' : 'Y';
                $arResult['SMART_FILTER'] = 'Y' == $arResult['SMART_FILTER'] ? 'Y' : 'N';
                $arResult['DISPLAY_TYPE'] = substr($arResult['DISPLAY_TYPE'], 0, 1);
                $arResult['DISPLAY_EXPANDED'] = 'Y' == $arResult['DISPLAY_EXPANDED'] ? 'Y' : 'N';
                $arProperty['FILTER_HINT'] = trim($arProperty['FILTER_HINT']);
                if ($arProperty['FILTER_HINT']) {
                    $TextParser = new CBXSanitizer();
                    $TextParser->SetLevel(CBXSanitizer::SECURE_LEVEL_LOW);
                    $TextParser->ApplyHtmlSpecChars(false);
                    $arProperty['FILTER_HINT'] = $TextParser->SanitizeHtml($arProperty['FILTER_HINT']);
                }
                $arResult['MULTIPLE_CNT'] = intval($arResult['MULTIPLE_CNT']);
                if (0 >= $arResult['MULTIPLE_CNT']) {
                    $arResult['MULTIPLE_CNT'] = $arDefPropInfo['MULTIPLE_CNT'];
                }
                $arResult['LIST_TYPE'] = 'C' == $arResult['LIST_TYPE'] ? 'C' : 'L';
                if ('Y' != COption::GetOptionString("iblock", "show_xml_id", "N") && isset($arResult["XML_ID"])) {
                    unset($arResult["XML_ID"]);
                }
            } else {
                $arResult['PROPINFO'] = $strEncodePropInfo;
            }
            if (0 < intval($ID)) {
                $arResult['DEL'] = isset($_POST[$strPrefix . $ID . "_DEL"]) && 'Y' == $_POST[$strPrefix . $ID . "_DEL"] ? 'Y' : 'N';
            }
        }
    }
    return $arResult;
}
Beispiel #6
0
 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']);
         }
     }
 }
Beispiel #7
0
}
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_REQUEST['save']) && $arResult['CAN_EDIT'] && check_bitrix_sessid()) {
    $bFromEditForm = $_POST['edit'] == 'Y';
    $arParams['COPY'] = $_POST['COPY'] == 'Y';
    $MEETING_ID = $arParams['MEETING_ID'];
    $res = true;
    $bNew = false;
    $bUpdateEvent = false;
    if ($bFromEditForm) {
        $bUpdateEvent = true;
        $res = false;
        $arFields = array('TITLE' => trim($_REQUEST['TITLE']), 'DESCRIPTION' => trim($_REQUEST['DESCRIPTION']), 'DATE_START' => CMeeting::MakeDateTime($_REQUEST['DATE_START_DATE'], $_REQUEST['DATE_START_TIME']), 'DURATION' => $_REQUEST['DURATION'] * $_REQUEST['DURATION_COEF'], 'PLACE' => $_REQUEST['PLACE'], 'GROUP_ID' => $_REQUEST['GROUP_ID']);
        if (strlen($_REQUEST['PLACE_ID']) > 0) {
            $arFields['PLACE'] = $_REQUEST['PLACE_ID'];
        }
        $TextParser = new CBXSanitizer();
        $TextParser->SetLevel(CBXSanitizer::SECURE_LEVEL_LOW);
        $TextParser->ApplyHtmlSpecChars(false);
        $arFields['DESCRIPTION'] = $TextParser->SanitizeHtml($arFields['DESCRIPTION']);
        if (strlen($arFields['TITLE']) <= 0) {
            $arFields['TITLE'] = GetMessage('ME_MEETING_TITLE_DEFAULT');
        }
        $arFields['FILES'] = \Bitrix\Main\UI\FileInputUtility::instance()->checkFiles('MEETING_DESCRIPTION', $_REQUEST['FILES']);
        /*$count = sizeof($_FILES["FILES_TMP"]["name"]);
        		if ($count > 0)
        		{
        			for($i = 0; $i < $count; $i++)
        			{
        				$arFile = array(
        					"name" => $_FILES["FILES_TMP"]["name"][$i],
        					"size" => $_FILES["FILES_TMP"]["size"][$i],
<?php

if (!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED !== true) {
    die;
}
$sanitizer = new CBXSanitizer();
$sanitizer->SetLevel(CBXSanitizer::SECURE_LEVEL_LOW);
foreach ($arResult['ENTRIES'] as $key => $val) {
    $arResult['ENTRIES'][$key]['TITLE'] = $sanitizer->SanitizeHtml($val["TITLE"]);
}
Beispiel #9
0
     }
 } else {
     if ($arProps[$currentKey]['PROPERTY_TYPE'] === 'F' && $arProps[$currentKey]['USER_TYPE'] === '') {
         if (CCrmUrlUtil::HasScheme($data) && CCrmUrlUtil::IsSecureUrl($data)) {
             $data = CFile::MakeFileArray($data);
             $file = new CFile();
             if (is_array($data) && strlen($file->CheckFile($data)) === 0) {
                 $prop = array('VALUE' => array_merge($data, array('MODULE_ID' => 'crm')));
             }
             unset($file);
         }
     } else {
         if ($arProps[$currentKey]['PROPERTY_TYPE'] === 'S' && $arProps[$currentKey]['USER_TYPE'] === 'HTML') {
             if (strtoupper(substr($data, 0, 6)) !== '[TEXT]') {
                 if ($sanitizer === null || !$sanitizer instanceof CBXSanitizer) {
                     $sanitizer = new CBXSanitizer();
                     $sanitizer->ApplyDoubleEncode(false);
                     $sanitizer->SetLevel(CBXSanitizer::SECURE_LEVEL_LOW);
                 }
                 $data = $sanitizer->SanitizeHtml($data);
             }
             $prop = array('VALUE' => $data);
         } else {
             if ($arProps[$currentKey]['PROPERTY_TYPE'] === 'S' && $arProps[$currentKey]['USER_TYPE'] === 'Date') {
                 if (CheckDateTime($data, FORMAT_DATE)) {
                     $prop = array('VALUE' => $data);
                 } else {
                     $prop = null;
                 }
             } else {
                 if ($arProps[$currentKey]['PROPERTY_TYPE'] === 'S' && $arProps[$currentKey]['USER_TYPE'] === 'DateTime') {
Beispiel #10
0
 public static function Add($arFields)
 {
     global $DB;
     if (isset($arFields['TITLE']) && !isset($arFields['NOTIFY_TITLE'])) {
         $arFields['NOTIFY_TITLE'] = $arFields['TITLE'];
     }
     if (isset($arFields['NOTIFY_MESSAGE']) && !isset($arFields['MESSAGE'])) {
         $arFields['MESSAGE'] = $arFields['NOTIFY_MESSAGE'];
     }
     if (isset($arFields['NOTIFY_MESSAGE_OUT']) && !isset($arFields['MESSAGE_OUT'])) {
         $arFields['MESSAGE_OUT'] = $arFields['NOTIFY_MESSAGE_OUT'];
     }
     if (isset($arFields['MESSAGE'])) {
         $arFields['MESSAGE'] = trim($arFields['MESSAGE']);
     }
     $arFields['MESSAGE_OUT'] = isset($arFields['MESSAGE_OUT']) ? trim($arFields['MESSAGE_OUT']) : "";
     $bConvert = false;
     if (isset($arFields['CONVERT']) && $arFields['CONVERT'] == 'Y') {
         $bConvert = true;
     }
     if (!isset($arFields['MESSAGE_TYPE'])) {
         $arFields['MESSAGE_TYPE'] = "";
     }
     if (!isset($arFields['NOTIFY_MODULE'])) {
         $arFields['NOTIFY_MODULE'] = 'im';
     }
     if (!isset($arFields['NOTIFY_EVENT'])) {
         $arFields['NOTIFY_EVENT'] = 'default';
     }
     if (!isset($arFields['PARAMS'])) {
         $arFields['PARAMS'] = array();
     }
     if (isset($arFields['ATTACH']) || isset($arFields['PARAMS']['ATTACH'])) {
         $attach = isset($arFields['ATTACH']) ? $arFields['ATTACH'] : $arFields['PARAMS']['ATTACH'];
         if (is_object($attach)) {
             $arFields['PARAMS']['ATTACH'] = array($attach);
         } else {
             if (is_array($attach)) {
                 $arFields['PARAMS']['ATTACH'] = $attach;
             } else {
                 $arFields['PARAMS']['ATTACH'] = array();
             }
         }
     }
     if (isset($arFields['FOR_USER_ID'])) {
         $arFields['PARAMS']['FOR_USER_ID'] = $arFields['FOR_USER_ID'];
     }
     $arFields['URL_ATTACH'] = array();
     if ($arFields['MESSAGE_TYPE'] == IM_MESSAGE_SYSTEM) {
         if (!isset($arFields['NOTIFY_TYPE']) && intval($arFields['FROM_USER_ID']) > 0) {
             $arFields['NOTIFY_TYPE'] = IM_NOTIFY_FROM;
         } else {
             if (!isset($arFields['NOTIFY_TYPE'])) {
                 $arFields['NOTIFY_TYPE'] = IM_NOTIFY_SYSTEM;
             }
         }
         if (isset($arFields['NOTIFY_ANSWER']) && $arFields['NOTIFY_ANSWER'] == 'Y') {
             $arFields['PARAMS']['CAN_ANSWER'] = 'Y';
         }
         /*
         $urlPrepare = self::PrepareUrl($arFields['MESSAGE']);
         if ($urlPrepare['RESULT'])
         {
         	if (empty($arFields['MESSAGE_OUT']))
         	{
         		$arFields['MESSAGE_OUT'] = $arFields['MESSAGE'];
         	}
         	$arFields['MESSAGE'] = $urlPrepare['MESSAGE'];
         	$arFields['PARAMS']['ATTACH'] = array_merge($arFields['PARAMS']['ATTACH'], $urlPrepare['ATTACH']);
         }
         */
     } else {
         $link = new CIMMessageLink();
         $urlPrepare = $link->prepareInsert($arFields['MESSAGE']);
         if ($urlPrepare['RESULT']) {
             if (empty($arFields['MESSAGE_OUT'])) {
                 $arFields['MESSAGE_OUT'] = $arFields['MESSAGE'];
             }
             $arFields['MESSAGE'] = $urlPrepare['MESSAGE'];
             if (isset($arFields['PARAMS']['URL_ID'])) {
                 $arFields['PARAMS']['URL_ID'] = array_merge($arFields['PARAMS']['URL_ID'], $urlPrepare['URL_ID']);
             } else {
                 $arFields['PARAMS']['URL_ID'] = $urlPrepare['URL_ID'];
             }
             $arFields['URL_ATTACH'] = $urlPrepare['ATTACH'];
         }
     }
     if (isset($arFields['NOTIFY_EMAIL_TEMPLATE']) && !isset($arFields['EMAIL_TEMPLATE'])) {
         $arFields['EMAIL_TEMPLATE'] = $arFields['NOTIFY_EMAIL_TEMPLATE'];
     }
     if (!isset($arFields['AUTHOR_ID'])) {
         $arFields['AUTHOR_ID'] = intval($arFields['FROM_USER_ID']);
     }
     foreach (GetModuleEvents("im", "OnBeforeMessageNotifyAdd", true) as $arEvent) {
         $result = ExecuteModuleEventEx($arEvent, array(&$arFields));
         if ($result === false || isset($result['result']) && $result['result'] === false) {
             if (isset($result['reason'])) {
                 $CBXSanitizer = new CBXSanitizer();
                 $CBXSanitizer->AddTags(array('a' => array('href', 'style', 'target'), 'b' => array(), 'u' => array(), 'i' => array(), 'br' => array(), 'span' => array('style')));
                 $reason = $CBXSanitizer->SanitizeHtml($result['reason']);
             } else {
                 if ($arFields['MESSAGE_TYPE'] == IM_MESSAGE_PRIVATE) {
                     $reason = GetMessage("IM_ERROR_MESSAGE_CANCELED");
                 } else {
                     if ($arFields['MESSAGE_TYPE'] == IM_MESSAGE_SYSTEM) {
                         $reason = GetMessage("IM_ERROR_NOTIFY_CANCELED");
                     } else {
                         $reason = GetMessage("IM_ERROR_GROUP_CANCELED");
                     }
                 }
             }
             $GLOBALS["APPLICATION"]->ThrowException($reason, "ERROR_FROM_OTHER_MODULE");
             return false;
         }
     }
     if (!self::CheckFields($arFields)) {
         return false;
     }
     if ($arFields['MESSAGE_TYPE'] == IM_MESSAGE_PRIVATE) {
         if (isset($arFields['TO_CHAT_ID'])) {
             $chatId = $arFields['TO_CHAT_ID'];
             $arRel = CIMChat::GetRelationById($chatId);
             foreach ($arRel as $rel) {
                 if ($rel['USER_ID'] == $arFields['FROM_USER_ID']) {
                     continue;
                 }
                 $arFields['TO_USER_ID'] = $rel['USER_ID'];
             }
             if (!IsModuleInstalled('intranet')) {
                 if (CIMSettings::GetPrivacy(CIMSettings::PRIVACY_MESSAGE) == CIMSettings::PRIVACY_RESULT_CONTACT && CModule::IncludeModule('socialnetwork') && CSocNetUser::IsFriendsAllowed() && !CSocNetUserRelations::IsFriends($arFields['FROM_USER_ID'], $arFields['TO_USER_ID'])) {
                     $GLOBALS["APPLICATION"]->ThrowException(GetMessage('IM_ERROR_MESSAGE_PRIVACY_SELF'), "ERROR_FROM_PRIVACY_SELF");
                     return false;
                 } else {
                     if (CIMSettings::GetPrivacy(CIMSettings::PRIVACY_MESSAGE, $arFields['TO_USER_ID']) == CIMSettings::PRIVACY_RESULT_CONTACT && CModule::IncludeModule('socialnetwork') && CSocNetUser::IsFriendsAllowed() && !CSocNetUserRelations::IsFriends($arFields['FROM_USER_ID'], $arFields['TO_USER_ID'])) {
                         $GLOBALS["APPLICATION"]->ThrowException(GetMessage('IM_ERROR_MESSAGE_PRIVACY'), "ERROR_FROM_PRIVACY");
                         return false;
                     }
                 }
             }
         } else {
             $arFields['FROM_USER_ID'] = intval($arFields['FROM_USER_ID']);
             $arFields['TO_USER_ID'] = intval($arFields['TO_USER_ID']);
             if (!IsModuleInstalled('intranet')) {
                 if (CIMSettings::GetPrivacy(CIMSettings::PRIVACY_MESSAGE) == CIMSettings::PRIVACY_RESULT_CONTACT && CModule::IncludeModule('socialnetwork') && CSocNetUser::IsFriendsAllowed() && !CSocNetUserRelations::IsFriends($arFields['FROM_USER_ID'], $arFields['TO_USER_ID'])) {
                     $GLOBALS["APPLICATION"]->ThrowException(GetMessage('IM_ERROR_MESSAGE_PRIVACY_SELF'), "ERROR_FROM_PRIVACY_SELF");
                     return false;
                 } else {
                     if (CIMSettings::GetPrivacy(CIMSettings::PRIVACY_MESSAGE, $arFields['TO_USER_ID']) == CIMSettings::PRIVACY_RESULT_CONTACT && CModule::IncludeModule('socialnetwork') && CSocNetUser::IsFriendsAllowed() && !CSocNetUserRelations::IsFriends($arFields['FROM_USER_ID'], $arFields['TO_USER_ID'])) {
                         $GLOBALS["APPLICATION"]->ThrowException(GetMessage('IM_ERROR_MESSAGE_PRIVACY'), "ERROR_FROM_PRIVACY");
                         return false;
                     }
                 }
             }
             $chatId = CIMMessage::GetChatId($arFields['FROM_USER_ID'], $arFields['TO_USER_ID']);
         }
         if ($chatId > 0) {
             $arParams = array();
             $arParams['CHAT_ID'] = $chatId;
             $arParams['AUTHOR_ID'] = intval($arFields['AUTHOR_ID']);
             $arParams['MESSAGE'] = $arFields['MESSAGE'];
             $arParams['MESSAGE_OUT'] = $arFields['MESSAGE_OUT'];
             $arParams['NOTIFY_MODULE'] = $arFields['NOTIFY_MODULE'];
             $arParams['NOTIFY_EVENT'] = $arFields['SYSTEM'] == 'Y' ? 'private_system' : 'private';
             if (isset($arFields['IMPORT_ID'])) {
                 $arParams['IMPORT_ID'] = intval($arFields['IMPORT_ID']);
             }
             if (isset($arFields['MESSAGE_DATE'])) {
                 $arParams['DATE_CREATE'] = $arFields['MESSAGE_DATE'];
             }
             $arFiles = array();
             $arFields['FILES'] = array();
             if (isset($arFields['PARAMS']['FILE_ID'])) {
                 foreach ($arFields['PARAMS']['FILE_ID'] as $fileId) {
                     $arFiles[$fileId] = $fileId;
                 }
             }
             $arFields['FILES'] = CIMDisk::GetFiles($chatId, $arFiles);
             $messageFiles = self::GetFormatFilesMessageOut($arFields['FILES']);
             if (strlen($messageFiles) > 0) {
                 $arParams['MESSAGE_OUT'] = strlen($arParams['MESSAGE_OUT']) > 0 ? $arParams['MESSAGE_OUT'] . "\n" . $messageFiles : $messageFiles;
                 $arFields['MESSAGE_OUT'] = $arParams['MESSAGE_OUT'];
             }
             $result = IM\MessageTable::add($arParams);
             $messageID = IntVal($result->getId());
             if ($messageID <= 0) {
                 return false;
             }
             IM\ChatTable::update($chatId, array('LAST_MESSAGE_ID' => $messageID));
             if (!empty($arFields['PARAMS'])) {
                 CIMMessageParam::Set($messageID, $arFields['PARAMS']);
             }
             if (!empty($arFields['URL_ATTACH'])) {
                 if (isset($arFields['PARAMS']['ATTACH'])) {
                     $arFields['PARAMS']['ATTACH'] = array_merge($arFields['PARAMS']['ATTACH'], $arFields['URL_ATTACH']);
                 } else {
                     $arFields['PARAMS']['ATTACH'] = $arFields['URL_ATTACH'];
                 }
             }
             //CUserCounter::Increment($arFields['TO_USER_ID'], 'im_message_v2', '**', false);
             CIMContactList::SetRecent(array('ENTITY_ID' => $arFields['TO_USER_ID'], 'MESSAGE_ID' => $messageID, 'CHAT_TYPE' => IM_MESSAGE_PRIVATE, 'USER_ID' => $arFields['FROM_USER_ID']));
             CIMContactList::SetRecent(array('ENTITY_ID' => $arFields['FROM_USER_ID'], 'MESSAGE_ID' => $messageID, 'CHAT_TYPE' => IM_MESSAGE_PRIVATE, 'USER_ID' => $arFields['TO_USER_ID']));
             CIMStatus::SetIdle($arFields['FROM_USER_ID'], false);
             if (!$bConvert) {
                 $arRel = CIMChat::GetRelationById($chatId);
                 foreach ($arRel as $relation) {
                     if ($relation["USER_ID"] == $arFields["TO_USER_ID"]) {
                         if ($relation['STATUS'] != IM_STATUS_UNREAD) {
                             IM\RelationTable::update($relation["ID"], array("STATUS" => IM_STATUS_UNREAD));
                         }
                     } else {
                         IM\RelationTable::update($relation["ID"], array("STATUS" => IM_STATUS_READ, "LAST_ID" => $messageID, "LAST_SEND_ID" => $messageID, "LAST_READ" => new Bitrix\Main\Type\DateTime()));
                     }
                 }
                 if (CModule::IncludeModule("pull")) {
                     $arParams['FROM_USER_ID'] = $arFields['FROM_USER_ID'];
                     $arParams['TO_USER_ID'] = $arFields['TO_USER_ID'];
                     $pullMessage = array('module_id' => 'im', 'command' => 'message', 'params' => CIMMessage::GetFormatMessage(array('ID' => $messageID, 'CHAT_ID' => $chatId, 'TO_USER_ID' => $arParams['TO_USER_ID'], 'FROM_USER_ID' => $arParams['FROM_USER_ID'], 'SYSTEM' => $arFields['SYSTEM'] == 'Y' ? 'Y' : 'N', 'MESSAGE' => $arParams['MESSAGE'], 'DATE_CREATE' => time(), 'PARAMS' => self::PrepareParamsForPull($arFields['PARAMS']), 'FILES' => $arFields['FILES'])));
                     $pullMessageTo = $pullMessage;
                     if (CPullOptions::GetPushStatus() && (!isset($arFields['PUSH']) || $arFields['PUSH'] == 'Y')) {
                         if (CIMSettings::GetNotifyAccess($arParams["TO_USER_ID"], 'im', 'message', CIMSettings::CLIENT_PUSH)) {
                             $pushParams = self::PreparePushForPrivate(array('FROM_USER_ID' => $arParams['FROM_USER_ID'], 'MESSAGE' => $arParams['MESSAGE'], 'SYSTEM' => $arFields['SYSTEM'], 'FILES' => $arFields['FILES'], 'ATTACH' => isset($arFields['PARAMS']['ATTACH']) ? true : false));
                             $pullMessageTo = array_merge($pullMessage, $pushParams);
                         }
                     }
                     CPullStack::AddByUser($arParams['TO_USER_ID'], $pullMessageTo);
                     CPullStack::AddByUser($arParams['FROM_USER_ID'], $pullMessage);
                     CPushManager::DeleteFromQueueBySubTag($arParams['FROM_USER_ID'], 'IM_MESS');
                     //self::SendBadges($arParams['TO_USER_ID']);
                 }
                 foreach (GetModuleEvents("im", "OnAfterMessagesAdd", true) as $arEvent) {
                     ExecuteModuleEventEx($arEvent, array(intval($messageID), $arFields));
                 }
             }
             return $messageID;
         } else {
             $GLOBALS["APPLICATION"]->ThrowException(GetMessage("IM_ERROR_MESSAGE_CREATE"), "CHAT_ID");
             return false;
         }
     } else {
         if ($arFields['MESSAGE_TYPE'] == IM_MESSAGE_CHAT || $arFields['MESSAGE_TYPE'] == IM_MESSAGE_OPEN) {
             $arFields['FROM_USER_ID'] = intval($arFields['FROM_USER_ID']);
             $chatId = 0;
             $systemMessage = false;
             if (isset($arFields['SYSTEM']) && $arFields['SYSTEM'] == 'Y') {
                 $strSql = "\n\t\t\t\t\tSELECT C.ID CHAT_ID, C.TITLE CHAT_TITLE, C.AUTHOR_ID CHAT_AUTHOR_ID, C.TYPE CHAT_TYPE, '1' RID\n\t\t\t\t\tFROM b_im_chat C\n\t\t\t\t\tWHERE C.ID = " . intval($arFields['TO_CHAT_ID']) . "\n\t\t\t\t";
                 $systemMessage = true;
             } else {
                 $strSql = "\n\t\t\t\t\tSELECT C.ID CHAT_ID, C.TITLE CHAT_TITLE, C.AUTHOR_ID CHAT_AUTHOR_ID, C.TYPE CHAT_TYPE, R.USER_ID RID\n\t\t\t\t\tFROM b_im_chat C\n\t\t\t\t\tLEFT JOIN b_im_relation R ON R.CHAT_ID = C.ID AND R.USER_ID = " . $arFields['FROM_USER_ID'] . "\n\t\t\t\t\tWHERE C.ID = " . intval($arFields['TO_CHAT_ID']) . "\n\t\t\t\t";
             }
             $dbRes = $DB->Query($strSql, false, "File: " . __FILE__ . "<br>Line: " . __LINE__);
             if ($arRes = $dbRes->Fetch()) {
                 $chatId = intval($arRes['CHAT_ID']);
                 $chatTitle = htmlspecialcharsbx($arRes['CHAT_TITLE']);
                 $chatAuthorId = intval($arRes['CHAT_AUTHOR_ID']);
                 $arRes['CHAT_TYPE'] = trim($arRes['CHAT_TYPE']);
                 $arFields['MESSAGE_TYPE'] = $arRes['CHAT_TYPE'];
                 if ($arRes['CHAT_TYPE'] == IM_MESSAGE_OPEN) {
                     if (!CIMMessenger::CheckEnableOpenChat()) {
                         $GLOBALS["APPLICATION"]->ThrowException(GetMessage("IM_ERROR_GROUP_CANCELED"), "CANCELED");
                         return false;
                     } else {
                         if (intval($arRes['RID']) <= 0) {
                             if (IM\User::getInstance($arFields['FROM_USER_ID'])->isExtranet()) {
                                 $GLOBALS["APPLICATION"]->ThrowException(GetMessage("IM_ERROR_GROUP_CANCELED"), "CANCELED");
                                 return false;
                             } else {
                                 $chat = new CIMChat(0);
                                 $chat->AddUser($chatId, $arFields['FROM_USER_ID']);
                             }
                         }
                     }
                 } else {
                     if (intval($arRes['RID']) <= 0) {
                         $GLOBALS["APPLICATION"]->ThrowException(GetMessage("IM_ERROR_GROUP_CANCELED"), "CANCELED");
                         return false;
                     }
                 }
             } else {
                 $GLOBALS["APPLICATION"]->ThrowException(GetMessage("IM_ERROR_GROUP_CANCELED"), "CANCELED");
                 return false;
             }
             if ($chatId > 0) {
                 $arParams = array();
                 $arParams['CHAT_ID'] = $chatId;
                 $arParams['AUTHOR_ID'] = $systemMessage ? 0 : intval($arFields['AUTHOR_ID']);
                 $arParams['MESSAGE'] = $arFields['MESSAGE'];
                 $arParams['MESSAGE_OUT'] = $arFields['MESSAGE_OUT'];
                 $arParams['NOTIFY_MODULE'] = 'im';
                 $arParams['NOTIFY_EVENT'] = 'group';
                 if (isset($arFields['MESSAGE_DATE'])) {
                     $arParams['DATE_CREATE'] = $arFields['MESSAGE_DATE'];
                 }
                 $arFiles = array();
                 $arFields['FILES'] = array();
                 if (isset($arFields['PARAMS']['FILE_ID'])) {
                     foreach ($arFields['PARAMS']['FILE_ID'] as $fileId) {
                         $arFiles[$fileId] = $fileId;
                     }
                 }
                 $arFields['FILES'] = CIMDisk::GetFiles($chatId, $arFiles);
                 $messageFiles = self::GetFormatFilesMessageOut($arFields['FILES']);
                 if (strlen($messageFiles) > 0) {
                     $arParams['MESSAGE_OUT'] = strlen($arParams['MESSAGE_OUT']) > 0 ? $arParams['MESSAGE_OUT'] . "\n" . $messageFiles : $messageFiles;
                     $arFields['MESSAGE_OUT'] = $arParams['MESSAGE_OUT'];
                 }
                 $result = IM\MessageTable::add($arParams);
                 $messageID = IntVal($result->getId());
                 if ($messageID <= 0) {
                     return false;
                 }
                 IM\ChatTable::update($chatId, array('LAST_MESSAGE_ID' => $messageID));
                 if (!empty($arFields['PARAMS'])) {
                     CIMMessageParam::Set($messageID, $arFields['PARAMS']);
                 }
                 if (!empty($arFields['URL_ATTACH'])) {
                     if (isset($arFields['PARAMS']['ATTACH'])) {
                         $arFields['PARAMS']['ATTACH'] = array_merge($arFields['PARAMS']['ATTACH'], $arFields['URL_ATTACH']);
                     } else {
                         $arFields['PARAMS']['ATTACH'] = $arFields['URL_ATTACH'];
                     }
                 }
                 //$sqlCounter = "SELECT USER_ID as ID, 1 as CNT, '**' as SITE_ID, 'im_chat_v2' as CODE, 1 as SENT
                 //				FROM b_im_relation R1
                 //				WHERE CHAT_ID = ".$chatId." AND USER_ID <> ".$arFields['FROM_USER_ID'];
                 //CUserCounter::IncrementWithSelect($sqlCounter, false);
                 $arRel = CIMChat::GetRelationById($chatId);
                 foreach ($arRel as $relation) {
                     CIMContactList::SetRecent(array('ENTITY_ID' => $chatId, 'MESSAGE_ID' => $messageID, 'CHAT_TYPE' => $arFields['MESSAGE_TYPE'], 'USER_ID' => $relation['USER_ID']));
                     if ($relation["USER_ID"] == $arFields["FROM_USER_ID"]) {
                         IM\RelationTable::update($relation["ID"], array("STATUS" => IM_STATUS_READ, "LAST_ID" => $messageID, "LAST_SEND_ID" => $messageID, "LAST_READ" => new Bitrix\Main\Type\DateTime()));
                     } else {
                         if ($relation['STATUS'] != IM_STATUS_UNREAD) {
                             IM\RelationTable::update($relation["ID"], array("STATUS" => IM_STATUS_UNREAD));
                         }
                     }
                 }
                 CIMStatus::SetIdle($arFields['FROM_USER_ID'], false);
                 if (CModule::IncludeModule("pull")) {
                     $arParams['FROM_USER_ID'] = $arFields['FROM_USER_ID'];
                     $arParams['TO_CHAT_ID'] = $arFields['TO_CHAT_ID'];
                     $pullMessage = array('module_id' => 'im', 'command' => 'messageChat', 'params' => CIMMessage::GetFormatMessage(array('ID' => $messageID, 'CHAT_ID' => $chatId, 'TO_CHAT_ID' => $arParams['TO_CHAT_ID'], 'FROM_USER_ID' => $arParams['FROM_USER_ID'], 'MESSAGE' => $arParams['MESSAGE'], 'SYSTEM' => $arFields['SYSTEM'] == 'Y' ? 'Y' : 'N', 'DATE_CREATE' => time(), 'PARAMS' => self::PrepareParamsForPull($arFields['PARAMS']), 'FILES' => $arFields['FILES'])));
                     if (CPullOptions::GetPushStatus() && (!isset($arFields['PUSH']) || $arFields['PUSH'] == 'Y')) {
                         $pushParams = self::PreparePushForChat(array('CHAT_ID' => $chatId, 'CHAT_TITLE' => $chatTitle, 'FROM_USER_ID' => $arParams['FROM_USER_ID'], 'MESSAGE' => $arParams['MESSAGE'], 'SYSTEM' => $arFields['SYSTEM'], 'FILES' => $arFields['FILES'], 'ATTACH' => isset($arFields['PARAMS']['ATTACH']) ? true : false));
                         $pullMessage = array_merge($pullMessage, $pushParams);
                     }
                     $pullUsers = array();
                     $pullUsersSkip = array();
                     foreach ($arRel as $rel) {
                         $pullUsers[] = $rel['USER_ID'];
                         if ($rel['USER_ID'] == $arParams['FROM_USER_ID']) {
                             $pullUsersSkip[] = $rel['USER_ID'];
                             CPushManager::DeleteFromQueueBySubTag($arParams['FROM_USER_ID'], 'IM_MESS');
                         } else {
                             if ($rel['NOTIFY_BLOCK'] == 'Y' || !CIMSettings::GetNotifyAccess($rel['USER_ID'], 'im', $arFields['MESSAGE_TYPE'] == IM_MESSAGE_OPEN ? 'openChat' : 'chat', CIMSettings::CLIENT_PUSH)) {
                                 $pullUsersSkip[] = $rel['USER_ID'];
                             }
                         }
                     }
                     $pullMessage['push']['skip_users'] = $pullUsersSkip;
                     CPullStack::AddByUsers($pullUsers, $pullMessage);
                     if ($arRes['CHAT_TYPE'] == IM_MESSAGE_OPEN) {
                         $pullMessageToWatch = $pullMessage;
                         unset($pullMessageToWatch['push']);
                         CPullWatch::AddToStack('IM_PUBLIC_' . $chatId, $pullMessageToWatch);
                     }
                     self::SendMention(array('CHAT_ID' => $chatId, 'CHAT_TITLE' => $chatTitle, 'CHAT_RELATION' => $arRel, 'CHAT_TYPE' => $arFields['MESSAGE_TYPE'], 'MESSAGE' => $arParams['MESSAGE'], 'FILES' => $arFields['FILES'], 'FROM_USER_ID' => $arParams['FROM_USER_ID']));
                     //self::SendBadges($usersForBadges);
                 }
                 foreach (GetModuleEvents("im", "OnAfterMessagesAdd", true) as $arEvent) {
                     ExecuteModuleEventEx($arEvent, array(intval($messageID), $arFields));
                 }
                 return $messageID;
             } else {
                 $GLOBALS["APPLICATION"]->ThrowException(GetMessage("IM_ERROR_MESSAGE_CREATE"), "CHAT_ID");
                 return false;
             }
         } else {
             if ($arFields['MESSAGE_TYPE'] == IM_MESSAGE_SYSTEM) {
                 $arFields['TO_USER_ID'] = intval($arFields['TO_USER_ID']);
                 $orm = \Bitrix\Main\UserTable::getById($arFields['TO_USER_ID']);
                 $userData = $orm->fetch();
                 if (!$userData || $userData['ACTIVE'] == 'N' || $userData['EXTERNAL_AUTH_ID'] == 'email') {
                     $GLOBALS["APPLICATION"]->ThrowException(GetMessage("IM_ERROR_MESSAGE_CREATE"), "TO_USER_ID");
                     return false;
                 }
                 $chatId = 0;
                 $strSql = "\n\t\t\t\tSELECT C.ID CHAT_ID\n\t\t\t\tFROM b_im_chat C\n\t\t\t\tWHERE C.AUTHOR_ID = " . $arFields['TO_USER_ID'] . " AND C.TYPE = '" . IM_MESSAGE_SYSTEM . "'\n\t\t\t";
                 $dbRes = $DB->Query($strSql, false, "File: " . __FILE__ . "<br>Line: " . __LINE__);
                 if ($arRes = $dbRes->Fetch()) {
                     $chatId = intval($arRes['CHAT_ID']);
                 } else {
                     $result = IM\ChatTable::add(array('TYPE' => IM_MESSAGE_SYSTEM, 'AUTHOR_ID' => $arFields['TO_USER_ID']));
                     $chatId = $result->getId();
                     if ($chatId <= 0) {
                         $GLOBALS["APPLICATION"]->ThrowException(GetMessage("IM_ERROR_MESSAGE_CREATE"), "CHAT_ID");
                         return false;
                     }
                     IM\RelationTable::add(array("CHAT_ID" => $chatId, "MESSAGE_TYPE" => IM_MESSAGE_SYSTEM, "USER_ID" => intval($arFields['TO_USER_ID']), "STATUS" => $bConvert ? 2 : 0));
                 }
                 if ($chatId > 0) {
                     $arParams = array();
                     $arParams['CHAT_ID'] = $chatId;
                     $arParams['AUTHOR_ID'] = intval($arFields['AUTHOR_ID']);
                     $arParams['MESSAGE'] = $arFields['MESSAGE'];
                     $arParams['MESSAGE_OUT'] = $arFields['MESSAGE_OUT'];
                     $arParams['NOTIFY_TYPE'] = intval($arFields['NOTIFY_TYPE']);
                     $arParams['NOTIFY_MODULE'] = $arFields['NOTIFY_MODULE'];
                     $arParams['NOTIFY_EVENT'] = $arFields['NOTIFY_EVENT'];
                     //if (strlen($arParams['MESSAGE']) <= 0 && strlen($arParams['MESSAGE_OUT']) <= 0)
                     //	return false;
                     $sendToSite = true;
                     if ($arParams['NOTIFY_TYPE'] != IM_NOTIFY_CONFIRM) {
                         $sendToSite = CIMSettings::GetNotifyAccess($arFields["TO_USER_ID"], $arFields["NOTIFY_MODULE"], $arFields["NOTIFY_EVENT"], CIMSettings::CLIENT_SITE);
                     }
                     if (!$sendToSite) {
                         $arParams['NOTIFY_READ'] = 'Y';
                     }
                     if (isset($arFields['IMPORT_ID'])) {
                         $arParams['IMPORT_ID'] = intval($arFields['IMPORT_ID']);
                     }
                     if (isset($arFields['MESSAGE_DATE'])) {
                         $arParams['DATE_CREATE'] = $arFields['MESSAGE_DATE'];
                     }
                     if (isset($arFields['EMAIL_TEMPLATE']) && strlen(trim($arFields['EMAIL_TEMPLATE'])) > 0) {
                         $arParams['EMAIL_TEMPLATE'] = trim($arFields['EMAIL_TEMPLATE']);
                     }
                     $arParams['NOTIFY_TAG'] = isset($arFields['NOTIFY_TAG']) ? $arFields['NOTIFY_TAG'] : '';
                     $arParams['NOTIFY_SUB_TAG'] = isset($arFields['NOTIFY_SUB_TAG']) ? $arFields['NOTIFY_SUB_TAG'] : '';
                     if (isset($arFields['NOTIFY_TITLE']) && strlen(trim($arFields['NOTIFY_TITLE'])) > 0) {
                         $arParams['NOTIFY_TITLE'] = trim($arFields['NOTIFY_TITLE']);
                     }
                     if ($arParams['NOTIFY_TYPE'] == IM_NOTIFY_CONFIRM) {
                         if (isset($arFields['NOTIFY_BUTTONS'])) {
                             foreach ($arFields['NOTIFY_BUTTONS'] as $key => $arButtons) {
                                 if (is_array($arButtons)) {
                                     if (isset($arButtons['TITLE']) && strlen($arButtons['TITLE']) > 0 && isset($arButtons['VALUE']) && strlen($arButtons['VALUE']) > 0 && isset($arButtons['TYPE']) && strlen($arButtons['TYPE']) > 0) {
                                         $arButtons['TITLE'] = htmlspecialcharsbx($arButtons['TITLE']);
                                         $arButtons['VALUE'] = htmlspecialcharsbx($arButtons['VALUE']);
                                         $arButtons['TYPE'] = htmlspecialcharsbx($arButtons['TYPE']);
                                         $arFields['NOTIFY_BUTTONS'][$key] = $arButtons;
                                     } else {
                                         unset($arFields['NOTIFY_BUTTONS'][$key]);
                                     }
                                 } else {
                                     unset($arFields['NOTIFY_BUTTONS'][$key]);
                                 }
                             }
                         } else {
                             $arFields['NOTIFY_BUTTONS'] = array(array('TITLE' => GetMessage('IM_ERROR_BUTTON_ACCEPT'), 'VALUE' => 'Y', 'TYPE' => 'accept'), array('TITLE' => GetMessage('IM_ERROR_BUTTON_CANCEL'), 'VALUE' => 'N', 'TYPE' => 'cancel'));
                         }
                         $arParams['NOTIFY_BUTTONS'] = serialize($arFields["NOTIFY_BUTTONS"]);
                         if (isset($arParams['NOTIFY_TAG']) && strlen($arParams['NOTIFY_TAG']) > 0) {
                             CIMNotify::DeleteByTag($arParams['NOTIFY_TAG']);
                         }
                     }
                     if ($sendToSite) {
                         $result = IM\MessageTable::add($arParams);
                         $messageID = IntVal($result->getId());
                         if ($messageID <= 0) {
                             return false;
                         }
                     } else {
                         $messageID = time();
                     }
                     if (!$bConvert) {
                         if (CModule::IncludeModule('pull')) {
                             $CPushManager = new CPushManager();
                             if (isset($arFields['PUSH_MESSAGE']) && CIMSettings::GetNotifyAccess($arFields["TO_USER_ID"], $arFields['NOTIFY_MODULE'], $arFields['NOTIFY_EVENT'], CIMSettings::CLIENT_PUSH) && CModule::IncludeModule('pull')) {
                                 $CPushManager->AddQueue(array('USER_ID' => $arFields['TO_USER_ID'], 'MESSAGE' => str_replace("\n", " ", trim($arFields['PUSH_MESSAGE'])), 'PARAMS' => isset($arFields['PUSH_PARAMS']) ? $arFields['PUSH_PARAMS'] : '', 'TAG' => $arParams['NOTIFY_TAG'], 'SUB_TAG' => $arParams['NOTIFY_SUB_TAG'], 'APP_ID' => isset($arParams['PUSH_APP_ID']) ? $arParams['PUSH_APP_ID'] : ''));
                             } else {
                                 $CPushManager->AddQueue(array('USER_ID' => $arFields['TO_USER_ID'], 'APP_ID' => isset($arParams['PUSH_APP_ID']) ? $arParams['PUSH_APP_ID'] : ''));
                             }
                         }
                         foreach (GetModuleEvents("im", "OnAfterNotifyAdd", true) as $arEvent) {
                             ExecuteModuleEventEx($arEvent, array(intval($messageID), $arFields));
                         }
                     }
                     if (!$sendToSite) {
                         return false;
                     }
                     if (!empty($arFields['PARAMS'])) {
                         CIMMessageParam::Set($messageID, $arFields['PARAMS']);
                     }
                     IM\ChatTable::update($chatId, array('LAST_MESSAGE_ID' => $messageID));
                     CIMMessenger::SpeedFileDelete($arFields['TO_USER_ID'], IM_SPEED_NOTIFY);
                     if (!$bConvert) {
                         //CUserCounter::Increment($arFields['TO_USER_ID'], 'im_notify_v2', '**', false);
                         $strSql = "UPDATE b_im_relation SET STATUS = '" . IM_STATUS_UNREAD . "' WHERE USER_ID = " . intval($arFields['TO_USER_ID']) . " AND MESSAGE_TYPE = '" . IM_MESSAGE_SYSTEM . "' AND CHAT_ID = " . $chatId;
                         $DB->Query($strSql, false, "File: " . __FILE__ . "<br>Line: " . __LINE__);
                         if (CModule::IncludeModule("pull")) {
                             CPullStack::AddByUser(intval($arFields['TO_USER_ID']), array('module_id' => 'im', 'command' => 'notify', 'params' => CIMNotify::GetFormatNotify(array('ID' => $messageID, 'DATE_CREATE' => time(), 'FROM_USER_ID' => intval($arFields['FROM_USER_ID']), 'MESSAGE' => $arParams['MESSAGE'], 'PARAMS' => self::PrepareParamsForPull($arFields['PARAMS']), 'NOTIFY_MODULE' => $arParams['NOTIFY_MODULE'], 'NOTIFY_EVENT' => $arParams['NOTIFY_EVENT'], 'NOTIFY_TAG' => $arParams['NOTIFY_TAG'], 'NOTIFY_TYPE' => $arParams['NOTIFY_TYPE'], 'NOTIFY_BUTTONS' => isset($arParams['NOTIFY_BUTTONS']) ? $arParams['NOTIFY_BUTTONS'] : serialize(array()), 'NOTIFY_TITLE' => isset($arParams['NOTIFY_TITLE']) ? $arParams['NOTIFY_TITLE'] : ''))));
                             self::SendBadges($arFields['TO_USER_ID']);
                         }
                     }
                     return $messageID;
                 } else {
                     $GLOBALS["APPLICATION"]->ThrowException(GetMessage("IM_ERROR_MESSAGE_CREATE"), "CHAT_ID");
                     return false;
                 }
             } else {
                 $GLOBALS["APPLICATION"]->ThrowException(GetMessage("IM_ERROR_MESSAGE_TYPE"), "MESSAGE_TYPE");
                 return false;
             }
         }
     }
 }
Beispiel #11
0
 /**
  * Sanitizes string and converts it to the site's charset.
  *
  * @param string $str Input string.
  * @return string
  */
 protected function filterString($str)
 {
     $sanitizer = new \CBXSanitizer();
     $sanitizer->SetLevel(\CBXSanitizer::SECURE_LEVEL_HIGH);
     $sanitizer->ApplyHtmlSpecChars(false);
     $str = html_entity_decode($str, ENT_QUOTES, $this->getEncoding());
     $str = Encoding::convertEncoding($str, $this->getEncoding(), Context::getCurrent()->getCulture()->getCharset());
     $str = trim($str);
     $str = $sanitizer->SanitizeHtml($str);
     return $str;
 }
Beispiel #12
0
 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 function AddHtml($html)
 {
     if (!isset($html)) {
         return false;
     }
     $sanitizer = new CBXSanitizer();
     $sanitizer->SetLevel(CBXSanitizer::SECURE_LEVEL_MIDDLE);
     $sanitizer->ApplyHtmlSpecChars(false);
     $html = preg_replace('/<script\\b[^>]*>(.*?)<\\/script>/is', "", $html);
     $this->result['BLOCKS'][]['HTML'] = $sanitizer->SanitizeHtml($html);
     return true;
 }
Beispiel #14
0
 /**
  * Sanitize tasks description if sanitizer enabled in task module options
  */
 public static function SanitizeHtmlDescriptionIfNeed($rawHtml)
 {
     static $bUseHtmlSanitizer = null;
     static $oSanitizer = null;
     // Init sanitizer (if we need it) only once at hit
     if ($bUseHtmlSanitizer === null) {
         $bSanitizeLevel = COption::GetOptionString('tasks', 'sanitize_level');
         if ($bSanitizeLevel >= 0) {
             $bUseHtmlSanitizer = true;
             if (!in_array($bSanitizeLevel, array(CBXSanitizer::SECURE_LEVEL_HIGH, CBXSanitizer::SECURE_LEVEL_MIDDLE, CBXSanitizer::SECURE_LEVEL_LOW))) {
                 $bSanitizeLevel = CBXSanitizer::SECURE_LEVEL_HIGH;
             }
             $oSanitizer = new CBXSanitizer();
             $oSanitizer->SetLevel($bSanitizeLevel);
             $oSanitizer->AddTags(array('blockquote' => array('style', 'class', 'id'), 'colgroup' => array('style', 'class', 'id'), 'col' => array('style', 'class', 'id', 'width', 'height', 'span', 'style')));
             $oSanitizer->ApplyHtmlSpecChars(true);
             // if we don't disable this, than text such as "df 1 < 2 dasfa and 5 > 4 will be partially lost"
             $oSanitizer->DeleteSanitizedTags(false);
         } else {
             $bUseHtmlSanitizer = false;
         }
     }
     if (!$bUseHtmlSanitizer) {
         return $rawHtml;
     }
     return $oSanitizer->SanitizeHtml(htmlspecialcharsback($rawHtml));
 }
Beispiel #15
0
********************************************************************/
if (!empty($arResult["ERROR_MESSAGE"])) {
    ShowError($arResult["ERROR_MESSAGE"]);
}
if (!empty($arResult["NOTIFY_MESSAGE"])) {
    ShowNote($arResult["NOTIFY_MESSAGE"]);
}
$uploadUrl = $arResult["ELEMENT"]["URL"]["UPLOAD"];
__prepare_item_info($arResult["ELEMENT"], $arParams);
$arResult["ELEMENT"]["URL"]["UPLOAD"] = $uploadUrl;
$aCols = __build_item_info($arResult["ELEMENT"], $arParams);
$aCols = $aCols["columns"];
$arCustomFields = array();
$elementPreviewText = "";
if (isset($arResult["ELEMENT"]["PREVIEW_TEXT"])) {
    $Sanitizer = new CBXSanitizer();
    $Sanitizer->SetLevel(CBXSanitizer::SECURE_LEVEL_LOW);
    $elementPreviewText = $Sanitizer->SanitizeHtml($arResult["ELEMENT"]["PREVIEW_TEXT"]);
}
//$arResult["ELEMENT"]["~PREVIEW_TEXT"]
if ($arParams["ACTION"] == "CLONE") {
    $arFields = array(array("id" => "FILE_TITLE", "name" => GetMessage("WD_ORIGINAL"), "type" => "label", "value" => $aCols["NAME"]));
    $arFields[] = array("id" => "NAME", "name" => GetMessage("WD_NAME"), "required" => true, "type" => "text", "value" => $arResult["ELEMENT"]["NAME"]);
    $arFields[] = array("id" => $arParams["NAME_FILE_PROPERTY"], "name" => GetMessage("WD_FILE_REPLACE"), "type" => "custom", "value" => '<input type="file" name="' . $arParams["NAME_FILE_PROPERTY"] . '" value="" />');
    $arFields[] = array("id" => "PREVIEW_TEXT", "name" => GetMessage("WD_DESCRIPTION"), "type" => "textarea", "value" => $elementPreviewText);
    $arTabs = array(array("id" => "tab_main", "name" => GetMessage("WD_VERSION"), "title" => GetMessage("WD_VERSION_ALT"), "fields" => $arFields));
    if ($arParams["OBJECT"]->workflow == "bizproc") {
        $bizProcIndex = $bizProcCounter = 0;
        $arDocumentStates = CBPDocument::GetDocumentStates($arParams["DOCUMENT_TYPE"], null);
        if (!empty($arDocumentStates)) {
            $arCurrentUserGroups[] = "Author";
Beispiel #16
0
     $arFields['SOURCE_ID'] = trim($_POST['SOURCE_ID']);
 }
 if (isset($_POST['TYPE_ID'])) {
     $arFields['TYPE_ID'] = trim($_POST['TYPE_ID']);
 }
 if (isset($_POST['COMPANY_ID'])) {
     $companyID = intval($_POST['COMPANY_ID']);
     if ($companyID <= 0 || !CCrmCompany::CheckReadPermission($companyID)) {
         $companyID = 0;
     }
     $arFields['COMPANY_ID'] = $companyID;
 }
 if (isset($_POST['COMMENTS'])) {
     $comments = trim($_POST['COMMENTS']);
     if ($comments !== '' && strpos($comments, '<') !== false) {
         $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()));
         $comments = $sanitizer->SanitizeHtml($comments);
     }
     $arFields['COMMENTS'] = $comments;
 }
 if (isset($_FILES['PHOTO'])) {
     $arFields['PHOTO'] = $_FILES['PHOTO'];
 }
 if (isset($_POST['PHOTO_del'])) {
     $arFields['PHOTO_del'] = $_POST['PHOTO_del'];
 }
 if (isset($_POST['EXPORT'])) {
Beispiel #17
0
 protected function saveCommentsAction()
 {
     if (!isset($this->request['orderId']) || intval($this->request['orderId']) <= 0) {
         throw new SystemException("Wrong order id!");
     }
     if (!isset($this->request['comments'])) {
         throw new SystemException("Can't find the comments content!");
     }
     $res = Sale\Internals\OrderTable::update($this->request['orderId'], array("COMMENTS" => $this->request['comments']));
     if (!$res->isSuccess()) {
         $this->addResultError(join("\n", $res->getErrorMessages()));
     }
     $CBXSanitizer = new \CBXSanitizer();
     $CBXSanitizer->SetLevel(\CBXSanitizer::SECURE_LEVEL_MIDDLE);
     $this->addResultData("COMMENTS", $CBXSanitizer->SanitizeHtml($this->request['comments']));
 }
 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']);
         }
     }
 }
Beispiel #19
0
 public function Answer($id, $text)
 {
     global $DB;
     $id = intval($id);
     $text = trim($text);
     if ($id <= 0 || strlen($text) <= 0) {
         return false;
     }
     $strSql = "\n\t\t\tSELECT M.*\n\t\t\tFROM b_im_relation R, b_im_message M\n\t\t\tWHERE M.ID = " . $id . " AND R.USER_ID = " . $this->user_id . " AND R.MESSAGE_TYPE = '" . IM_MESSAGE_SYSTEM . "' AND R.CHAT_ID = M.CHAT_ID\n\t\t";
     $dbRes = $DB->Query($strSql, false, "File: " . __FILE__ . "<br>Line: " . __LINE__);
     if (!($arRes = $dbRes->Fetch())) {
         return false;
     }
     $CBXSanitizer = new CBXSanitizer();
     $CBXSanitizer->AddTags(array('a' => array('href', 'style', 'target'), 'b' => array(), 'u' => array(), 'i' => array(), 'br' => array(), 'span' => array('style')));
     foreach (GetModuleEvents("im", "OnAnswerNotify", true) as $arEvent) {
         $resultEvent = ExecuteModuleEventEx($arEvent, array($arRes['NOTIFY_MODULE'], $arRes['NOTIFY_TAG'], $text, $arRes));
         if ($resultEvent === false || is_array($resultEvent) && $resultEvent['result'] === false) {
             $resultMessages = array();
             if (is_array($resultEvent) && $resultEvent['text']) {
                 $resultMessages[] = $CBXSanitizer->SanitizeHtml($resultEvent['text']);
             }
             break;
         } else {
             if (is_array($resultEvent) && $resultEvent['text'] || is_string($resultEvent) && strlen($resultEvent) > 0) {
                 $resultMessages[] = $CBXSanitizer->SanitizeHtml(is_string($resultEvent) ? $resultEvent : $resultEvent['text']);
             }
         }
     }
     if (empty($resultMessages)) {
         $resultMessages[] = GetMessage('IM_ANSWER_DONE');
     }
     return $resultMessages;
 }
Beispiel #20
0
 public static function Add($arFields)
 {
     global $DB;
     if (isset($arFields['TITLE']) && !isset($arFields['NOTIFY_TITLE'])) {
         $arFields['NOTIFY_TITLE'] = $arFields['TITLE'];
     }
     if (isset($arFields['NOTIFY_MESSAGE']) && !isset($arFields['MESSAGE'])) {
         $arFields['MESSAGE'] = $arFields['NOTIFY_MESSAGE'];
     }
     if (isset($arFields['NOTIFY_MESSAGE_OUT']) && !isset($arFields['MESSAGE_OUT'])) {
         $arFields['MESSAGE_OUT'] = $arFields['NOTIFY_MESSAGE_OUT'];
     }
     $bConvert = false;
     if (isset($arFields['CONVERT']) && $arFields['CONVERT'] == 'Y') {
         $bConvert = true;
     }
     if (!isset($arFields['MESSAGE_OUT'])) {
         $arFields['MESSAGE_OUT'] = "";
     }
     if (!isset($arFields['MESSAGE_TYPE'])) {
         $arFields['MESSAGE_TYPE'] = "";
     }
     if (!isset($arFields['NOTIFY_MODULE'])) {
         $arFields['NOTIFY_MODULE'] = 'im';
     }
     if (!isset($arFields['NOTIFY_EVENT'])) {
         $arFields['NOTIFY_EVENT'] = 'default';
     }
     if (!isset($arFields['PARAMS'])) {
         $arFields['PARAMS'] = array();
     }
     if ($arFields['MESSAGE_TYPE'] == IM_MESSAGE_SYSTEM) {
         if (!isset($arFields['NOTIFY_TYPE']) && intval($arFields['FROM_USER_ID']) > 0) {
             $arFields['NOTIFY_TYPE'] = IM_NOTIFY_FROM;
         } else {
             if (!isset($arFields['NOTIFY_TYPE'])) {
                 $arFields['NOTIFY_TYPE'] = IM_NOTIFY_SYSTEM;
             }
         }
     }
     if (isset($arFields['NOTIFY_EMAIL_TEMPLATE']) && !isset($arFields['EMAIL_TEMPLATE'])) {
         $arFields['EMAIL_TEMPLATE'] = $arFields['NOTIFY_EMAIL_TEMPLATE'];
     }
     if (isset($arFields['EMAIL_TEMPLATE']) && strlen(trim($arFields['EMAIL_TEMPLATE'])) > 0) {
         $arParams['EMAIL_TEMPLATE'] = trim($arFields['EMAIL_TEMPLATE']);
     }
     if (!isset($arFields['AUTHOR_ID'])) {
         $arFields['AUTHOR_ID'] = intval($arFields['FROM_USER_ID']);
     }
     foreach (GetModuleEvents("im", "OnBeforeMessageNotifyAdd", true) as $arEvent) {
         $result = ExecuteModuleEventEx($arEvent, array(&$arFields));
         if ($result === false || isset($result['result']) && $result['result'] === false) {
             if (isset($result['reason'])) {
                 $CBXSanitizer = new CBXSanitizer();
                 $CBXSanitizer->AddTags(array('a' => array('href', 'style', 'target'), 'b' => array(), 'u' => array(), 'i' => array(), 'br' => array(), 'span' => array('style')));
                 $reason = $CBXSanitizer->SanitizeHtml($result['reason']);
             } else {
                 if ($arFields['MESSAGE_TYPE'] == IM_MESSAGE_PRIVATE) {
                     $reason = GetMessage("IM_ERROR_MESSAGE_CANCELED");
                 } else {
                     if ($arFields['MESSAGE_TYPE'] == IM_MESSAGE_SYSTEM) {
                         $reason = GetMessage("IM_ERROR_NOTIFY_CANCELED");
                     } else {
                         $reason = GetMessage("IM_ERROR_GROUP_CANCELED");
                     }
                 }
             }
             $GLOBALS["APPLICATION"]->ThrowException($reason, "ERROR_FROM_OTHER_MODULE");
             return false;
         }
     }
     if (!self::CheckFields($arFields)) {
         return false;
     }
     if ($arFields['MESSAGE_TYPE'] == IM_MESSAGE_PRIVATE) {
         if (isset($arFields['TO_CHAT_ID'])) {
             $chatId = $arFields['TO_CHAT_ID'];
             $arRel = CIMChat::GetRelationById($chatId);
             foreach ($arRel as $rel) {
                 if ($rel['USER_ID'] == $arFields['FROM_USER_ID']) {
                     continue;
                 }
                 $arFields['TO_USER_ID'] = $rel['USER_ID'];
             }
             if (!IsModuleInstalled('intranet')) {
                 if (CIMSettings::GetPrivacy(CIMSettings::PRIVACY_MESSAGE) == CIMSettings::PRIVACY_RESULT_CONTACT && CModule::IncludeModule('socialnetwork') && CSocNetUser::IsFriendsAllowed() && !CSocNetUserRelations::IsFriends($arFields['FROM_USER_ID'], $arFields['TO_USER_ID'])) {
                     $GLOBALS["APPLICATION"]->ThrowException(GetMessage('IM_ERROR_MESSAGE_PRIVACY_SELF'), "ERROR_FROM_PRIVACY_SELF");
                     return false;
                 } else {
                     if (CIMSettings::GetPrivacy(CIMSettings::PRIVACY_MESSAGE, $arFields['TO_USER_ID']) == CIMSettings::PRIVACY_RESULT_CONTACT && CModule::IncludeModule('socialnetwork') && CSocNetUser::IsFriendsAllowed() && !CSocNetUserRelations::IsFriends($arFields['FROM_USER_ID'], $arFields['TO_USER_ID'])) {
                         $GLOBALS["APPLICATION"]->ThrowException(GetMessage('IM_ERROR_MESSAGE_PRIVACY'), "ERROR_FROM_PRIVACY");
                         return false;
                     }
                 }
             }
         } else {
             $arFields['FROM_USER_ID'] = intval($arFields['FROM_USER_ID']);
             $arFields['TO_USER_ID'] = intval($arFields['TO_USER_ID']);
             if (!IsModuleInstalled('intranet')) {
                 if (CIMSettings::GetPrivacy(CIMSettings::PRIVACY_MESSAGE) == CIMSettings::PRIVACY_RESULT_CONTACT && CModule::IncludeModule('socialnetwork') && CSocNetUser::IsFriendsAllowed() && !CSocNetUserRelations::IsFriends($arFields['FROM_USER_ID'], $arFields['TO_USER_ID'])) {
                     $GLOBALS["APPLICATION"]->ThrowException(GetMessage('IM_ERROR_MESSAGE_PRIVACY_SELF'), "ERROR_FROM_PRIVACY_SELF");
                     return false;
                 } else {
                     if (CIMSettings::GetPrivacy(CIMSettings::PRIVACY_MESSAGE, $arFields['TO_USER_ID']) == CIMSettings::PRIVACY_RESULT_CONTACT && CModule::IncludeModule('socialnetwork') && CSocNetUser::IsFriendsAllowed() && !CSocNetUserRelations::IsFriends($arFields['FROM_USER_ID'], $arFields['TO_USER_ID'])) {
                         $GLOBALS["APPLICATION"]->ThrowException(GetMessage('IM_ERROR_MESSAGE_PRIVACY'), "ERROR_FROM_PRIVACY");
                         return false;
                     }
                 }
             }
             $chatId = CIMMessage::GetChatId($arFields['FROM_USER_ID'], $arFields['TO_USER_ID']);
         }
         if ($chatId > 0) {
             $arParams = array();
             $arParams['CHAT_ID'] = $chatId;
             $arParams['AUTHOR_ID'] = intval($arFields['AUTHOR_ID']);
             $arParams['MESSAGE'] = trim($arFields['MESSAGE']);
             $arParams['MESSAGE_OUT'] = trim($arFields['MESSAGE_OUT']);
             $arParams['NOTIFY_MODULE'] = $arFields['NOTIFY_MODULE'];
             $arParams['NOTIFY_EVENT'] = $arFields['SYSTEM'] == 'Y' ? 'private_system' : 'private';
             if (isset($arFields['IMPORT_ID'])) {
                 $arParams['IMPORT_ID'] = intval($arFields['IMPORT_ID']);
             }
             if (isset($arFields['MESSAGE_DATE'])) {
                 $arParams['DATE_CREATE'] = $arFields['MESSAGE_DATE'];
             }
             $arFiles = array();
             $arFields['FILES'] = array();
             if (isset($arFields['PARAMS']['FILE_ID'])) {
                 foreach ($arFields['PARAMS']['FILE_ID'] as $fileId) {
                     $arFiles[$fileId] = $fileId;
                 }
             }
             $arFields['FILES'] = CIMDisk::GetFiles($chatId, $arFiles);
             $messageFiles = self::GetFormatFilesMessageOut($arFields['FILES']);
             if (strlen($messageFiles) > 0) {
                 $arParams['MESSAGE_OUT'] = strlen($arParams['MESSAGE_OUT']) > 0 ? $arParams['MESSAGE_OUT'] . "\n" . $messageFiles : $messageFiles;
                 $arFields['MESSAGE_OUT'] = $arParams['MESSAGE_OUT'];
             }
             $result = IM\MessageTable::add($arParams);
             $messageID = IntVal($result->getId());
             if ($messageID <= 0) {
                 return false;
             }
             IM\ChatTable::update($chatId, array('LAST_MESSAGE_ID' => $messageID));
             if (!empty($arFields['PARAMS'])) {
                 CIMMessageParam::Set($messageID, $arFields['PARAMS']);
             }
             //CUserCounter::Increment($arFields['TO_USER_ID'], 'im_message_v2', '**', false);
             CIMContactList::SetRecent(array('ENTITY_ID' => $arFields['TO_USER_ID'], 'MESSAGE_ID' => $messageID, 'CHAT_TYPE' => IM_MESSAGE_PRIVATE, 'USER_ID' => $arFields['FROM_USER_ID']));
             CIMContactList::SetRecent(array('ENTITY_ID' => $arFields['FROM_USER_ID'], 'MESSAGE_ID' => $messageID, 'CHAT_TYPE' => IM_MESSAGE_PRIVATE, 'USER_ID' => $arFields['TO_USER_ID']));
             CIMStatus::SetIdle($arFields['FROM_USER_ID'], false);
             if (!$bConvert) {
                 $arRel = CIMChat::GetRelationById($chatId);
                 foreach ($arRel as $relation) {
                     if ($relation["USER_ID"] == $arFields["TO_USER_ID"]) {
                         if ($relation['STATUS'] != IM_STATUS_UNREAD) {
                             IM\RelationTable::update($relation["ID"], array("STATUS" => IM_STATUS_UNREAD));
                         }
                     } else {
                         IM\RelationTable::update($relation["ID"], array("STATUS" => IM_STATUS_READ, "LAST_ID" => $messageID, "LAST_SEND_ID" => $messageID, "LAST_READ" => new Bitrix\Main\Type\DateTime()));
                     }
                 }
                 if (CModule::IncludeModule("pull")) {
                     $arParams['FROM_USER_ID'] = $arFields['FROM_USER_ID'];
                     $arParams['TO_USER_ID'] = $arFields['TO_USER_ID'];
                     $arPullTo = array('module_id' => 'im', 'command' => 'message', 'params' => CIMMessage::GetFormatMessage(array('ID' => $messageID, 'CHAT_ID' => $chatId, 'TO_USER_ID' => $arParams['TO_USER_ID'], 'FROM_USER_ID' => $arParams['FROM_USER_ID'], 'SYSTEM' => $arFields['SYSTEM'] == 'Y' ? 'Y' : 'N', 'MESSAGE' => $arParams['MESSAGE'], 'DATE_CREATE' => time(), 'PARAMS' => $arFields['PARAMS'], 'FILES' => $arFields['FILES'])));
                     $arPullFrom = $arPullTo;
                     $pushText = '';
                     if (CPullOptions::GetPushStatus() && (!isset($arFields['PUSH']) || $arFields['PUSH'] == 'Y')) {
                         $arSelect = array("ID", "LAST_NAME", "NAME", "LOGIN", "SECOND_NAME");
                         $dbUsers = CUser::GetList($sort_by = false, $dummy = '', array('ID' => $arParams['FROM_USER_ID']), array('FIELDS' => $arSelect));
                         if ($arUser = $dbUsers->GetNext(true, false)) {
                             $sName = CUser::FormatName(CSite::GetNameFormat(false), $arUser, true, false);
                             $pushText = $sName . ': ' . $arParams['MESSAGE'];
                             if (count($arFields['FILES']) > 0 && strlen($pushText) < 200) {
                                 foreach ($arFields['FILES'] as $file) {
                                     $file = " [" . GetMessage('IM_MESSAGE_FILE') . ": " . $file['name'] . "]";
                                     if (strlen($pushText . $file) > 200) {
                                         break;
                                     }
                                     $pushText = trim($pushText) . $file;
                                 }
                             }
                         }
                         if (CIMSettings::GetNotifyAccess($arParams["TO_USER_ID"], 'im', 'message', CIMSettings::CLIENT_PUSH)) {
                             $arPullTo['push_params'] = array('TAG' => 'IM_MESS_' . $arParams['FROM_USER_ID'], 'CATEGORY' => 'ANSWER', 'URL' => SITE_DIR . 'mobile/ajax.php?mobile_action=im_answer', 'PARAMS' => array('RECIPIENT_ID' => $arParams['FROM_USER_ID']));
                             $arPullTo['push_tag'] = 'IM_MESS_' . $arParams['FROM_USER_ID'];
                             $arPullTo['push_sub_tag'] = 'IM_MESS';
                             $arPullTo['push_app_id'] = 'Bitrix24';
                             $arPullTo['push_text'] = preg_replace("/\\[s\\].*?\\[\\/s\\]/i", "", $pushText);
                             $arPullTo['push_text'] = preg_replace("/\\[[bui]\\](.*?)\\[\\/[bui]\\]/i", "\$1", $arPullTo['push_text']);
                             $arPullTo['push_text'] = preg_replace("/\\[PCH=([0-9]{1,})\\](.*?)\\[\\/PCH\\]/i", "\$2", $arPullTo['push_text']);
                             $arPullTo['push_text'] = preg_replace("/\\[USER=([0-9]{1,})\\](.*?)\\[\\/USER\\]/i", "\$2", $arPullTo['push_text']);
                             $arPullTo['push_text'] = preg_replace('#\\-{54}.+?\\-{54}#s', " [" . GetMessage('IM_QUOTE') . "] ", str_replace(array("#BR#"), array(" "), $arPullTo['push_text']));
                         }
                     }
                     CPullStack::AddByUser($arParams['TO_USER_ID'], $arPullTo);
                     CPullStack::AddByUser($arParams['FROM_USER_ID'], $arPullFrom);
                     CPushManager::DeleteFromQueueBySubTag($arParams['FROM_USER_ID'], 'IM_MESS');
                     self::SendBadges($arParams['TO_USER_ID']);
                 }
                 foreach (GetModuleEvents("im", "OnAfterMessagesAdd", true) as $arEvent) {
                     ExecuteModuleEventEx($arEvent, array(intval($messageID), $arFields));
                 }
             }
             return $messageID;
         } else {
             $GLOBALS["APPLICATION"]->ThrowException(GetMessage("IM_ERROR_MESSAGE_CREATE"), "CHAT_ID");
             return false;
         }
     } else {
         if ($arFields['MESSAGE_TYPE'] == IM_MESSAGE_CHAT || $arFields['MESSAGE_TYPE'] == IM_MESSAGE_OPEN) {
             $arFields['FROM_USER_ID'] = intval($arFields['FROM_USER_ID']);
             $chatId = 0;
             $systemMessage = false;
             if (isset($arFields['SYSTEM']) && $arFields['SYSTEM'] == 'Y') {
                 $strSql = "\n\t\t\t\t\tSELECT C.ID CHAT_ID, C.TITLE CHAT_TITLE, C.AUTHOR_ID CHAT_AUTHOR_ID, C.TYPE CHAT_TYPE, '1' RID\n\t\t\t\t\tFROM b_im_chat C\n\t\t\t\t\tWHERE C.ID = " . intval($arFields['TO_CHAT_ID']) . "\n\t\t\t\t";
                 $systemMessage = true;
             } else {
                 $strSql = "\n\t\t\t\t\tSELECT C.ID CHAT_ID, C.TITLE CHAT_TITLE, C.AUTHOR_ID CHAT_AUTHOR_ID, C.TYPE CHAT_TYPE, R.USER_ID RID\n\t\t\t\t\tFROM b_im_chat C\n\t\t\t\t\tLEFT JOIN b_im_relation R ON R.CHAT_ID = C.ID AND R.USER_ID = " . $arFields['FROM_USER_ID'] . "\n\t\t\t\t\tWHERE C.ID = " . intval($arFields['TO_CHAT_ID']) . "\n\t\t\t\t";
             }
             $dbRes = $DB->Query($strSql, false, "File: " . __FILE__ . "<br>Line: " . __LINE__);
             if ($arRes = $dbRes->Fetch()) {
                 $chatId = intval($arRes['CHAT_ID']);
                 $chatTitle = htmlspecialcharsbx($arRes['CHAT_TITLE']);
                 $chatAuthorId = intval($arRes['CHAT_AUTHOR_ID']);
                 $arFields['MESSAGE_TYPE'] = $arRes['CHAT_TYPE'];
                 if ($arRes['CHAT_TYPE'] == IM_MESSAGE_OPEN) {
                     if (intval($arRes['RID']) <= 0) {
                         if (IM\User::getInstance($arFields['FROM_USER_ID'])->isExtranet()) {
                             $GLOBALS["APPLICATION"]->ThrowException(GetMessage("IM_ERROR_GROUP_CANCELED"), "CANCELED");
                             return false;
                         } else {
                             $chat = new CIMChat(0);
                             $chat->AddUser($chatId, $arFields['FROM_USER_ID']);
                         }
                     }
                 } else {
                     if (intval($arRes['RID']) <= 0) {
                         $GLOBALS["APPLICATION"]->ThrowException(GetMessage("IM_ERROR_GROUP_CANCELED"), "CANCELED");
                         return false;
                     }
                 }
             } else {
                 $GLOBALS["APPLICATION"]->ThrowException(GetMessage("IM_ERROR_GROUP_CANCELED"), "CANCELED");
                 return false;
             }
             if ($chatId > 0) {
                 $arParams = array();
                 $arParams['CHAT_ID'] = $chatId;
                 $arParams['AUTHOR_ID'] = $systemMessage ? 0 : intval($arFields['AUTHOR_ID']);
                 $arParams['MESSAGE'] = trim($arFields['MESSAGE']);
                 $arParams['MESSAGE_OUT'] = trim($arFields['MESSAGE_OUT']);
                 $arParams['NOTIFY_MODULE'] = 'im';
                 $arParams['NOTIFY_EVENT'] = 'group';
                 if (isset($arFields['MESSAGE_DATE'])) {
                     $arParams['DATE_CREATE'] = $arFields['MESSAGE_DATE'];
                 }
                 $arFiles = array();
                 $arFields['FILES'] = array();
                 if (isset($arFields['PARAMS']['FILE_ID'])) {
                     foreach ($arFields['PARAMS']['FILE_ID'] as $fileId) {
                         $arFiles[$fileId] = $fileId;
                     }
                 }
                 $arFields['FILES'] = CIMDisk::GetFiles($chatId, $arFiles);
                 $messageFiles = self::GetFormatFilesMessageOut($arFields['FILES']);
                 if (strlen($messageFiles) > 0) {
                     $arParams['MESSAGE_OUT'] = strlen($arParams['MESSAGE_OUT']) > 0 ? $arParams['MESSAGE_OUT'] . "\n" . $messageFiles : $messageFiles;
                     $arFields['MESSAGE_OUT'] = $arParams['MESSAGE_OUT'];
                 }
                 $result = IM\MessageTable::add($arParams);
                 $messageID = IntVal($result->getId());
                 if ($messageID <= 0) {
                     return false;
                 }
                 IM\ChatTable::update($chatId, array('LAST_MESSAGE_ID' => $messageID));
                 if (!empty($arFields['PARAMS'])) {
                     CIMMessageParam::Set($messageID, $arFields['PARAMS']);
                 }
                 //$sqlCounter = "SELECT USER_ID as ID, 1 as CNT, '**' as SITE_ID, 'im_chat_v2' as CODE, 1 as SENT
                 //				FROM b_im_relation R1
                 //				WHERE CHAT_ID = ".$chatId." AND USER_ID <> ".$arFields['FROM_USER_ID'];
                 //CUserCounter::IncrementWithSelect($sqlCounter, false);
                 $arRel = CIMChat::GetRelationById($chatId);
                 foreach ($arRel as $relation) {
                     CIMContactList::SetRecent(array('ENTITY_ID' => $chatId, 'MESSAGE_ID' => $messageID, 'CHAT_TYPE' => $arFields['MESSAGE_TYPE'], 'USER_ID' => $relation['USER_ID']));
                     if ($relation["USER_ID"] == $arFields["FROM_USER_ID"]) {
                         IM\RelationTable::update($relation["ID"], array("STATUS" => IM_STATUS_READ, "LAST_ID" => $messageID, "LAST_SEND_ID" => $messageID, "LAST_READ" => new Bitrix\Main\Type\DateTime()));
                     } else {
                         if ($relation['STATUS'] != IM_STATUS_UNREAD) {
                             IM\RelationTable::update($relation["ID"], array("STATUS" => IM_STATUS_UNREAD));
                         }
                     }
                 }
                 CIMStatus::SetIdle($arFields['FROM_USER_ID'], false);
                 if (CModule::IncludeModule("pull")) {
                     $arParams['FROM_USER_ID'] = $arFields['FROM_USER_ID'];
                     $arParams['TO_CHAT_ID'] = $arFields['TO_CHAT_ID'];
                     $arPullTo = array('module_id' => 'im', 'command' => 'messageChat', 'params' => CIMMessage::GetFormatMessage(array('ID' => $messageID, 'CHAT_ID' => $chatId, 'TO_CHAT_ID' => $arParams['TO_CHAT_ID'], 'FROM_USER_ID' => $arParams['FROM_USER_ID'], 'MESSAGE' => $arParams['MESSAGE'], 'SYSTEM' => $arFields['SYSTEM'] == 'Y' ? 'Y' : 'N', 'DATE_CREATE' => time(), 'PARAMS' => $arFields['PARAMS'], 'FILES' => $arFields['FILES'])));
                     $pushText = '';
                     if ($arFields['MESSAGE_TYPE'] == IM_MESSAGE_CHAT && CPullOptions::GetPushStatus() && (!isset($arFields['PUSH']) || $arFields['PUSH'] == 'Y')) {
                         if ($arFields['SYSTEM'] == 'Y') {
                             $pushText = substr(htmlspecialcharsback($chatTitle), 0, 32) . ': ' . $arParams['MESSAGE'];
                         } else {
                             $arSelect = array("ID", "LAST_NAME", "NAME", "LOGIN", "SECOND_NAME");
                             $dbUsers = CUser::GetList($sort_by = false, $dummy = '', array('ID' => $arParams['FROM_USER_ID']), array('FIELDS' => $arSelect));
                             if ($arUser = $dbUsers->GetNext(true, false)) {
                                 $sName = CUser::FormatName(CSite::GetNameFormat(false), $arUser, true, false);
                                 $pushText = GetMessage('IM_PUSH_GROUP_TITLE', array('#USER#' => $sName, '#GROUP#' => substr(htmlspecialcharsback($chatTitle), 0, 32))) . ': ' . $arParams['MESSAGE'];
                             }
                         }
                         if (count($arFields['FILES']) > 0 && strlen($pushText) < 200 && strlen($pushText) > 0) {
                             foreach ($arFields['FILES'] as $file) {
                                 $file = " [" . GetMessage('IM_MESSAGE_FILE') . ": " . $file['name'] . "]";
                                 if (strlen($pushText . $file) > 200) {
                                     break;
                                 }
                                 $pushText = trim($pushText) . $file;
                             }
                         }
                         $arPullTo['push_params'] = array('TAG' => 'IM_CHAT_' . $chatId, 'CATEGORY' => 'ANSWER', 'URL' => SITE_DIR . 'mobile/ajax.php?mobile_action=im_answer', 'PARAMS' => array('RECIPIENT_ID' => 'chat' . $chatId));
                         $arPullTo['push_tag'] = 'IM_CHAT_' . $chatId;
                         $arPullTo['push_sub_tag'] = 'IM_MESS';
                         $arPullTo['push_app_id'] = 'Bitrix24';
                         $arPullTo['push_text'] = preg_replace("/\\[s\\].*?\\[\\/s\\]/i", "-", $pushText);
                         $arPullTo['push_text'] = preg_replace("/\\[[bui]\\](.*?)\\[\\/[bui]\\]/i", "\$1", $arPullTo['push_text']);
                         $arPullTo['push_text'] = preg_replace("/\\[USER=([0-9]{1,})\\](.*?)\\[\\/USER\\]/i", "\$2", $arPullTo['push_text']);
                         $arPullTo['push_text'] = preg_replace("/\\[PCH=([0-9]{1,})\\](.*?)\\[\\/PCH\\]/i", "\$2", $arPullTo['push_text']);
                         $arPullTo['push_text'] = preg_replace('#\\-{54}.+?\\-{54}#s', " [" . GetMessage('IM_QUOTE') . "] ", str_replace(array("#BR#"), array(" "), $arPullTo['push_text']));
                     }
                     $arPullFrom = $arPullTo;
                     unset($arPullFrom['push_text']);
                     foreach ($arRel as $rel) {
                         if ($rel['USER_ID'] == $arParams['FROM_USER_ID']) {
                             CPullStack::AddByUser($arParams['FROM_USER_ID'], $arPullFrom);
                             CPushManager::DeleteFromQueueBySubTag($arParams['FROM_USER_ID'], 'IM_MESS');
                         } else {
                             $arPullUser = $arPullTo;
                             if ($rel['NOTIFY_BLOCK'] == 'Y' || !CIMSettings::GetNotifyAccess($rel['USER_ID'], 'im', 'chat', CIMSettings::CLIENT_PUSH)) {
                                 unset($arPullUser['push_text']);
                             }
                             CPullStack::AddByUser($rel['USER_ID'], $arPullUser);
                             //$usersForBadges[] = $rel['USER_ID'];
                         }
                     }
                     if ($arRes['CHAT_TYPE'] == IM_MESSAGE_OPEN) {
                         CPullWatch::AddToStack('IM_PUBLIC_' . $chatId, $arPullFrom);
                         $forUsers = array();
                         if (preg_match_all("/\\[USER=([0-9]{1,})\\](.*?)\\[\\/USER\\]/i", $arParams['MESSAGE'], $matches)) {
                             foreach ($matches[1] as $userId) {
                                 if (!isset($arRel[$userId])) {
                                     $forUsers[$userId] = $userId;
                                 }
                             }
                         }
                         if (count($forUsers)) {
                             $arSelect = array("ID", "LAST_NAME", "NAME", "LOGIN", "SECOND_NAME");
                             $dbUsers = CUser::GetList($sort_by = false, $dummy = '', array('ID' => $arParams['FROM_USER_ID']), array('FIELDS' => $arSelect));
                             if ($arUser = $dbUsers->GetNext(true, false)) {
                                 $sName = CUser::FormatName(CSite::GetNameFormat(false), $arUser, true, false);
                                 $notifyMail = GetMessage('IM_MESSAGE_MENTION', array('#TITLE#' => substr(htmlspecialcharsback($chatTitle), 0, 32)));
                                 $notifyText = GetMessage('IM_MESSAGE_MENTION', array('#TITLE#' => '[CHAT=' . $chatId . ']' . substr(htmlspecialcharsback($chatTitle), 0, 32) . '[/CHAT]'));
                                 $pushText = GetMessage('IM_MESSAGE_MENTION_PUSH', array('#USER#' => $sName, '#TITLE#' => substr(htmlspecialcharsback($chatTitle), 0, 32)));
                             }
                             if (strlen($notifyText) > 0) {
                                 $arMessageFields = array("TO_USER_ID" => $userId, "FROM_USER_ID" => $arParams['FROM_USER_ID'], "NOTIFY_TYPE" => IM_NOTIFY_FROM, "NOTIFY_MODULE" => "im", "NOTIFY_EVENT" => "mention", "NOTIFY_TAG" => 'IM|MENTION|' . $chatId, "NOTIFY_SUB_TAG" => "IM_MESS", "NOTIFY_MESSAGE" => $notifyText, "NOTIFY_MESSAGE_OUT" => $notifyMail, "PUSH_MESSAGE" => $pushText, "PUSH_PARAMS" => array('TAG' => 'IM_CHAT_' . $chatId, 'CATEGORY' => 'ANSWER', 'URL' => SITE_DIR . 'mobile/ajax.php?mobile_action=im_answer', 'PARAMS' => array('RECIPIENT_ID' => 'chat' . $chatId)), "PUSH_APP_ID" => 'Bitirx24');
                                 CIMNotify::Add($arMessageFields);
                             }
                         }
                     }
                     //self::SendBadges($usersForBadges);
                 }
                 foreach (GetModuleEvents("im", "OnAfterMessagesAdd", true) as $arEvent) {
                     ExecuteModuleEventEx($arEvent, array(intval($messageID), $arFields));
                 }
                 return $messageID;
             } else {
                 $GLOBALS["APPLICATION"]->ThrowException(GetMessage("IM_ERROR_MESSAGE_CREATE"), "CHAT_ID");
                 return false;
             }
         } else {
             if ($arFields['MESSAGE_TYPE'] == IM_MESSAGE_SYSTEM) {
                 $arFields['TO_USER_ID'] = intval($arFields['TO_USER_ID']);
                 $chatId = 0;
                 $strSql = "\n\t\t\t\tSELECT CHAT_ID\n\t\t\t\tFROM b_im_relation\n\t\t\t\tWHERE USER_ID = " . $arFields['TO_USER_ID'] . " AND MESSAGE_TYPE = '" . IM_MESSAGE_SYSTEM . "'";
                 $dbRes = $DB->Query($strSql, false, "File: " . __FILE__ . "<br>Line: " . __LINE__);
                 if ($arRes = $dbRes->Fetch()) {
                     $chatId = intval($arRes['CHAT_ID']);
                 } else {
                     $result = IM\ChatTable::add(array('TYPE' => IM_MESSAGE_SYSTEM, 'AUTHOR_ID' => $arFields['TO_USER_ID']));
                     $chatId = $result->getId();
                     if ($chatId <= 0) {
                         $GLOBALS["APPLICATION"]->ThrowException(GetMessage("IM_ERROR_MESSAGE_CREATE"), "CHAT_ID");
                         return false;
                     }
                     IM\RelationTable::add(array("CHAT_ID" => $chatId, "MESSAGE_TYPE" => IM_MESSAGE_SYSTEM, "USER_ID" => intval($arFields['TO_USER_ID']), "STATUS" => $bConvert ? 2 : 0));
                 }
                 if ($chatId > 0) {
                     $arParams = array();
                     $arParams['CHAT_ID'] = $chatId;
                     $arParams['AUTHOR_ID'] = intval($arFields['AUTHOR_ID']);
                     $arParams['MESSAGE'] = trim($arFields['MESSAGE']);
                     $arParams['MESSAGE_OUT'] = trim($arFields['MESSAGE_OUT']);
                     $arParams['NOTIFY_TYPE'] = intval($arFields['NOTIFY_TYPE']);
                     $arParams['NOTIFY_MODULE'] = $arFields['NOTIFY_MODULE'];
                     $arParams['NOTIFY_EVENT'] = $arFields['NOTIFY_EVENT'];
                     //if (strlen($arParams['MESSAGE']) <= 0 && strlen($arParams['MESSAGE_OUT']) <= 0)
                     //	return false;
                     $sendToSite = true;
                     if ($arParams['NOTIFY_TYPE'] != IM_NOTIFY_CONFIRM) {
                         $sendToSite = CIMSettings::GetNotifyAccess($arFields["TO_USER_ID"], $arFields["NOTIFY_MODULE"], $arFields["NOTIFY_EVENT"], CIMSettings::CLIENT_SITE);
                     }
                     if (!$sendToSite) {
                         $arParams['NOTIFY_READ'] = 'Y';
                     }
                     if (isset($arFields['IMPORT_ID'])) {
                         $arParams['IMPORT_ID'] = intval($arFields['IMPORT_ID']);
                     }
                     if (isset($arFields['MESSAGE_DATE'])) {
                         $arParams['DATE_CREATE'] = $arFields['MESSAGE_DATE'];
                     }
                     if (isset($arFields['EMAIL_TEMPLATE']) && strlen(trim($arFields['EMAIL_TEMPLATE'])) > 0) {
                         $arParams['EMAIL_TEMPLATE'] = trim($arFields['EMAIL_TEMPLATE']);
                     }
                     $arParams['NOTIFY_TAG'] = isset($arFields['NOTIFY_TAG']) ? $arFields['NOTIFY_TAG'] : '';
                     $arParams['NOTIFY_SUB_TAG'] = isset($arFields['NOTIFY_SUB_TAG']) ? $arFields['NOTIFY_SUB_TAG'] : '';
                     if (isset($arFields['NOTIFY_TITLE']) && strlen(trim($arFields['NOTIFY_TITLE'])) > 0) {
                         $arParams['NOTIFY_TITLE'] = trim($arFields['NOTIFY_TITLE']);
                     }
                     if ($arParams['NOTIFY_TYPE'] == IM_NOTIFY_CONFIRM) {
                         if (isset($arFields['NOTIFY_BUTTONS'])) {
                             foreach ($arFields['NOTIFY_BUTTONS'] as $key => $arButtons) {
                                 if (is_array($arButtons)) {
                                     if (isset($arButtons['TITLE']) && strlen($arButtons['TITLE']) > 0 && isset($arButtons['VALUE']) && strlen($arButtons['VALUE']) > 0 && isset($arButtons['TYPE']) && strlen($arButtons['TYPE']) > 0) {
                                         $arButtons['TITLE'] = htmlspecialcharsbx($arButtons['TITLE']);
                                         $arButtons['VALUE'] = htmlspecialcharsbx($arButtons['VALUE']);
                                         $arButtons['TYPE'] = htmlspecialcharsbx($arButtons['TYPE']);
                                         $arFields['NOTIFY_BUTTONS'][$key] = $arButtons;
                                     } else {
                                         unset($arFields['NOTIFY_BUTTONS'][$key]);
                                     }
                                 } else {
                                     unset($arFields['NOTIFY_BUTTONS'][$key]);
                                 }
                             }
                         } else {
                             $arFields['NOTIFY_BUTTONS'] = array(array('TITLE' => GetMessage('IM_ERROR_BUTTON_ACCEPT'), 'VALUE' => 'Y', 'TYPE' => 'accept'), array('TITLE' => GetMessage('IM_ERROR_BUTTON_CANCEL'), 'VALUE' => 'N', 'TYPE' => 'cancel'));
                         }
                         $arParams['NOTIFY_BUTTONS'] = serialize($arFields["NOTIFY_BUTTONS"]);
                         if (isset($arParams['NOTIFY_TAG']) && strlen($arParams['NOTIFY_TAG']) > 0) {
                             CIMNotify::DeleteByTag($arParams['NOTIFY_TAG']);
                         }
                     }
                     if (!$bConvert) {
                         if (isset($arFields['PUSH_MESSAGE']) && CIMSettings::GetNotifyAccess($arFields["TO_USER_ID"], $arFields['NOTIFY_MODULE'], $arFields['NOTIFY_EVENT'], CIMSettings::CLIENT_PUSH) && CModule::IncludeModule('pull')) {
                             $CPushManager = new CPushManager();
                             $CPushManager->AddQueue(array('USER_ID' => $arFields['TO_USER_ID'], 'MESSAGE' => str_replace("\n", " ", trim($arFields['PUSH_MESSAGE'])), 'PARAMS' => isset($arFields['PUSH_PARAMS']) ? $arFields['PUSH_PARAMS'] : '', 'TAG' => $arParams['NOTIFY_TAG'], 'SUB_TAG' => $arParams['NOTIFY_SUB_TAG'], 'APP_ID' => isset($arParams['PUSH_APP_ID']) ? $arParams['PUSH_APP_ID'] : ''));
                         }
                         foreach (GetModuleEvents("im", "OnAfterNotifyAdd", true) as $arEvent) {
                             ExecuteModuleEventEx($arEvent, array(intval($messageID), $arFields));
                         }
                     }
                     if (!$sendToSite) {
                         return 0;
                     }
                     $result = IM\MessageTable::add($arParams);
                     $messageID = IntVal($result->getId());
                     if ($messageID <= 0) {
                         return false;
                     }
                     IM\ChatTable::update($chatId, array('LAST_MESSAGE_ID' => $messageID));
                     CIMMessenger::SpeedFileDelete($arFields['TO_USER_ID'], IM_SPEED_NOTIFY);
                     if (!$bConvert) {
                         //CUserCounter::Increment($arFields['TO_USER_ID'], 'im_notify_v2', '**', false);
                         $strSql = "UPDATE b_im_relation SET STATUS = '" . IM_STATUS_UNREAD . "' WHERE USER_ID = " . intval($arFields['TO_USER_ID']) . " AND MESSAGE_TYPE = '" . IM_MESSAGE_SYSTEM . "' AND CHAT_ID = " . $chatId;
                         $DB->Query($strSql, false, "File: " . __FILE__ . "<br>Line: " . __LINE__);
                         if (CModule::IncludeModule("pull")) {
                             CPullStack::AddByUser(intval($arFields['TO_USER_ID']), array('module_id' => 'im', 'command' => 'notify', 'params' => CIMNotify::GetFormatNotify(array('ID' => $messageID, 'DATE_CREATE' => time(), 'FROM_USER_ID' => intval($arFields['FROM_USER_ID']), 'MESSAGE' => $arParams['MESSAGE'], 'NOTIFY_MODULE' => $arParams['NOTIFY_MODULE'], 'NOTIFY_EVENT' => $arParams['NOTIFY_EVENT'], 'NOTIFY_TAG' => $arParams['NOTIFY_TAG'], 'NOTIFY_TYPE' => $arParams['NOTIFY_TYPE'], 'NOTIFY_BUTTONS' => isset($arParams['NOTIFY_BUTTONS']) ? $arParams['NOTIFY_BUTTONS'] : serialize(array()), 'NOTIFY_TITLE' => isset($arParams['NOTIFY_TITLE']) ? $arParams['NOTIFY_TITLE'] : ''))));
                             self::SendBadges($arFields['TO_USER_ID']);
                         }
                     }
                     return $messageID;
                 } else {
                     $GLOBALS["APPLICATION"]->ThrowException(GetMessage("IM_ERROR_MESSAGE_CREATE"), "CHAT_ID");
                     return false;
                 }
             } else {
                 $GLOBALS["APPLICATION"]->ThrowException(GetMessage("IM_ERROR_MESSAGE_TYPE"), "MESSAGE_TYPE");
                 return false;
             }
         }
     }
 }
Beispiel #21
0
    ShowError("MAPP_ML_MOBILEAPP_NOT_INSTALLED");
    return;
}
if (empty($arParams["ITEMS"]) || !is_array($arParams["ITEMS"])) {
    return;
}
$arResult["ITEMS"] = $arParams["ITEMS"];
if (isset($_REQUEST['ajax_mode']) && $_REQUEST['ajax_mode'] == 'Y') {
    $arResult["AJAX_MODE"] = true;
} else {
    $arResult["AJAX_MODE"] = false;
    $arResult["AJAX_PATH"] = $componentPath . "/ajax.php";
    $arResult["JS_EVENT_ITEM_CHANGE"] = isset($arParams["JS_EVENT_ITEM_CHANGE"]) ? $arParams["JS_EVENT_ITEM_CHANGE"] : false;
    $arResult["JS_EVENT_BOTTOM_REACHED"] = isset($arParams["JS_EVENT_BOTTOM_REACHED"]) ? $arParams["JS_EVENT_BOTTOM_REACHED"] : 'mappJsEventListBottomReached';
    $arResult["MAPP_LIST_PRELOAD_START"] = $arResult["MAPP_LIST_PRELOAD_START"] ? $arParams["MAPP_LIST_PRELOAD_START"] : 1;
}
$Sanitizer = new CBXSanitizer();
$Sanitizer->SetLevel(CBXSanitizer::SECURE_LEVEL_LOW);
array_walk_recursive($arResult["ITEMS"], 'sanitizeInputData', $Sanitizer);
$this->IncludeComponentTemplate();
function sanitizeInputData(&$item, $key, $Sanitizer)
{
    if ($key === 'DETAIL_LINK') {
        $linkItem = '<a href="' . $item . '">test</a>';
        if ($linkItem != $Sanitizer->SanitizeHtml($linkItem)) {
            $item = '';
        }
    } else {
        $item = $Sanitizer->SanitizeHtml($item);
    }
}
     if (!$res) {
         $strWarning .= $ib->LAST_ERROR . "<br>";
         $bVarsFromForm = true;
     }
 }
 $arCatalog = CCatalog::GetSkuInfoByProductID($IBLOCK_ID);
 if (is_array($arCatalog) && CIBlock::GetArrayByID($arCatalog["IBLOCK_ID"], "SECTION_PROPERTY") != "Y") {
     $ib = new CIBlock();
     $res = $ib->Update($arCatalog["IBLOCK_ID"], array("SECTION_PROPERTY" => "Y"));
     if (!$res) {
         $strWarning .= $ib->LAST_ERROR . "<br>";
         $bVarsFromForm = true;
     }
 }
 if ($strWarning === "") {
     $TextParser = new CBXSanitizer();
     $TextParser->SetLevel(CBXSanitizer::SECURE_LEVEL_LOW);
     $TextParser->ApplyHtmlSpecChars(false);
     $props = CIBlockProperty::GetList(array(), array("IBLOCK_ID" => $IBLOCK_ID, "CHECK_PERMISSIONS" => "N"));
     while ($p = $props->Fetch()) {
         if (isset($_POST["SECTION_PROPERTY"]) && is_array($_POST["SECTION_PROPERTY"]) && array_key_exists($p["ID"], $_POST["SECTION_PROPERTY"]) && $_POST["SECTION_PROPERTY"][$p["ID"]]["SHOW"] === "Y") {
             $filterHint = trim($_POST["SECTION_PROPERTY"][$p["ID"]]["FILTER_HINT"]);
             if ($filterHint) {
                 $filterHint = $TextParser->SanitizeHtml($filterHint);
             }
             CIBlockSectionPropertyLink::Set(0, $p["ID"], array("SMART_FILTER" => $_POST["SECTION_PROPERTY"][$p["ID"]]["SMART_FILTER"], "DISPLAY_TYPE" => $_POST["SECTION_PROPERTY"][$p["ID"]]["DISPLAY_TYPE"], "DISPLAY_EXPANDED" => $_POST["SECTION_PROPERTY"][$p["ID"]]["DISPLAY_EXPANDED"], "FILTER_HINT" => $filterHint));
         } else {
             CIBlockSectionPropertyLink::Delete(0, $p["ID"]);
         }
     }
     if (is_array($arCatalog)) {
	public static function Add($arFields)
	{
		global $DB;

		if (isset($arFields['TITLE']) && !isset($arFields['NOTIFY_TITLE']))
			$arFields['NOTIFY_TITLE'] = $arFields['TITLE'];

		if (isset($arFields['NOTIFY_MESSAGE']) && !isset($arFields['MESSAGE']))
			$arFields['MESSAGE'] = $arFields['NOTIFY_MESSAGE'];

		if (isset($arFields['NOTIFY_MESSAGE_OUT']) && !isset($arFields['MESSAGE_OUT']))
			$arFields['MESSAGE_OUT'] = $arFields['NOTIFY_MESSAGE_OUT'];

		$bConvert = false;
		if (isset($arFields['CONVERT']) && $arFields['CONVERT'] == 'Y')
			$bConvert = true;

		if (!isset($arFields['MESSAGE_OUT']))
			$arFields['MESSAGE_OUT'] = "";

		if (!isset($arFields['MESSAGE_TYPE']))
			$arFields['MESSAGE_TYPE'] = "";

		if (!isset($arFields['NOTIFY_MODULE']))
			$arFields['NOTIFY_MODULE'] = 'im';

		if (!isset($arFields['NOTIFY_EVENT']))
			$arFields['NOTIFY_EVENT'] = 'default';

		if (!isset($arFields['PARAMS']))
			$arFields['PARAMS'] = Array();

		if ($arFields['MESSAGE_TYPE'] == IM_MESSAGE_SYSTEM)
		{
			if (!isset($arFields['NOTIFY_TYPE']) && intval($arFields['FROM_USER_ID']) > 0)
				$arFields['NOTIFY_TYPE'] = IM_NOTIFY_FROM;
			else if (!isset($arFields['NOTIFY_TYPE']))
				$arFields['NOTIFY_TYPE'] = IM_NOTIFY_SYSTEM;
		}

		if (isset($arFields['NOTIFY_EMAIL_TEMPLATE']) && !isset($arFields['EMAIL_TEMPLATE']))
			$arFields['EMAIL_TEMPLATE'] = $arFields['NOTIFY_EMAIL_TEMPLATE'];

		if (isset($arFields['EMAIL_TEMPLATE']) && strlen(trim($arFields['EMAIL_TEMPLATE']))>0)
			$arParams['EMAIL_TEMPLATE'] = trim($arFields['EMAIL_TEMPLATE']);

		if (!isset($arFields['AUTHOR_ID']))
			$arFields['AUTHOR_ID'] = intval($arFields['FROM_USER_ID']);

		foreach(GetModuleEvents("im", "OnBeforeMessageNotifyAdd", true) as $arEvent)
		{
			$result = ExecuteModuleEventEx($arEvent, array(&$arFields));
			if($result===false || isset($result['result']) && $result['result'] === false)
			{
				if (isset($result['reason']))
				{
					$CBXSanitizer = new CBXSanitizer;
					$CBXSanitizer->AddTags(array(
						'a' => array('href','style', 'target'),
						'b' => array(), 'u' => array(),
						'i' => array(), 'br' => array(),
						'span' => array('style'),
					));
					$reason = $CBXSanitizer->SanitizeHtml($result['reason']);
				}
				else
				{
					$reason = $arFields['MESSAGE_TYPE'] == IM_MESSAGE_PRIVATE? GetMessage("IM_ERROR_MESSAGE_CANCELED"): ($arFields['MESSAGE_TYPE'] == IM_MESSAGE_GROUP? GetMessage("IM_ERROR_GROUP_CANCELED"): GetMessage("IM_ERROR_NOTIFY_CANCELED"));
				}

				$GLOBALS["APPLICATION"]->ThrowException($reason, "ERROR_FROM_OTHER_MODULE");

				return false;
			}
		}

		if (!self::CheckFields($arFields))
			return false;

		if ($arFields['MESSAGE_TYPE'] == IM_MESSAGE_PRIVATE)
		{
			if (isset($arFields['TO_CHAT_ID']))
			{
				$chatId = $arFields['TO_CHAT_ID'];
				$arRel = CIMChat::GetRelationById($chatId);
				foreach ($arRel as $rel)
				{
					if ($rel['USER_ID'] == $arFields['FROM_USER_ID'])
						continue;

					$arFields['TO_USER_ID'] = $rel['USER_ID'];
				}

				if (!IsModuleInstalled('intranet'))
				{
					if (CIMSettings::GetPrivacy(CIMSettings::PRIVACY_MESSAGE) == CIMSettings::PRIVACY_RESULT_CONTACT && CModule::IncludeModule('socialnetwork') && CSocNetUser::IsFriendsAllowed() && !CSocNetUserRelations::IsFriends($arFields['FROM_USER_ID'], $arFields['TO_USER_ID']))
					{
						$GLOBALS["APPLICATION"]->ThrowException(GetMessage('IM_ERROR_MESSAGE_PRIVACY_SELF'), "ERROR_FROM_PRIVACY_SELF");
						return false;
					}
					else if (CIMSettings::GetPrivacy(CIMSettings::PRIVACY_MESSAGE, $arFields['TO_USER_ID']) == CIMSettings::PRIVACY_RESULT_CONTACT && CModule::IncludeModule('socialnetwork') && CSocNetUser::IsFriendsAllowed() && !CSocNetUserRelations::IsFriends($arFields['FROM_USER_ID'], $arFields['TO_USER_ID']))
					{
						$GLOBALS["APPLICATION"]->ThrowException(GetMessage('IM_ERROR_MESSAGE_PRIVACY'), "ERROR_FROM_PRIVACY");
						return false;
					}
				}
			}
			else
			{
				$arFields['FROM_USER_ID'] = intval($arFields['FROM_USER_ID']);
				$arFields['TO_USER_ID'] = intval($arFields['TO_USER_ID']);

				if (!IsModuleInstalled('intranet'))
				{
					if (CIMSettings::GetPrivacy(CIMSettings::PRIVACY_MESSAGE) == CIMSettings::PRIVACY_RESULT_CONTACT && CModule::IncludeModule('socialnetwork') && CSocNetUser::IsFriendsAllowed() && !CSocNetUserRelations::IsFriends($arFields['FROM_USER_ID'], $arFields['TO_USER_ID']))
					{
						$GLOBALS["APPLICATION"]->ThrowException(GetMessage('IM_ERROR_MESSAGE_PRIVACY_SELF'), "ERROR_FROM_PRIVACY_SELF");
						return false;
					}
					else if (CIMSettings::GetPrivacy(CIMSettings::PRIVACY_MESSAGE, $arFields['TO_USER_ID']) == CIMSettings::PRIVACY_RESULT_CONTACT && CModule::IncludeModule('socialnetwork') && CSocNetUser::IsFriendsAllowed() && !CSocNetUserRelations::IsFriends($arFields['FROM_USER_ID'], $arFields['TO_USER_ID']))
					{
						$GLOBALS["APPLICATION"]->ThrowException(GetMessage('IM_ERROR_MESSAGE_PRIVACY'), "ERROR_FROM_PRIVACY");
						return false;
					}
				}
				$chatId = CIMMessage::GetChatId($arFields['FROM_USER_ID'], $arFields['TO_USER_ID']);
			}

			if ($chatId > 0)
			{
				$arParams = Array();
				$arParams['CHAT_ID'] = $chatId;
				$arParams['AUTHOR_ID'] = intval($arFields['AUTHOR_ID']);
				$arParams['MESSAGE'] = trim($arFields['MESSAGE']);
				$arParams['MESSAGE_OUT'] = trim($arFields['MESSAGE_OUT']);
				$arParams['NOTIFY_MODULE'] = $arFields['NOTIFY_MODULE'];
				$arParams['NOTIFY_EVENT'] = $arFields['SYSTEM'] == 'Y'? 'private_system': 'private';

				if (isset($arFields['IMPORT_ID']))
					$arParams['IMPORT_ID'] = intval($arFields['IMPORT_ID']);

				if (isset($arFields['MESSAGE_DATE']))
					$arParams['DATE_CREATE'] = $arFields['MESSAGE_DATE'];
				else
					$arParams['~DATE_CREATE'] = $DB->CurrentTimeFunction();


				$arFiles = Array();
				$arFields['FILES'] = Array();
				if (isset($arFields['PARAMS']['FILE_ID']))
				{
					foreach ($arFields['PARAMS']['FILE_ID'] as $fileId)
					{
						$arFiles[$fileId] = $fileId;
					}
				}
				$arFields['FILES'] = CIMDisk::GetFiles($chatId, $arFiles);

				$messageFiles = self::GetFormatFilesMessageOut($arFields['FILES']);
				if (strlen($messageFiles) > 0)
				{
					$arParams['MESSAGE_OUT'] = strlen($arParams['MESSAGE_OUT'])>0? $arParams['MESSAGE_OUT']."\n".$messageFiles: $messageFiles;
					$arFields['MESSAGE_OUT'] = $arParams['MESSAGE_OUT'];
				}

				$messageID = IntVal($DB->Add("b_im_message", $arParams, Array('MESSAGE','MESSAGE_OUT')));
				if ($messageID <= 0)
					return false;

				if (!empty($arFields['PARAMS']))
					CIMMessageParam::Set($messageID, $arFields['PARAMS']);

				//CUserCounter::Increment($arFields['TO_USER_ID'], 'im_message_v2', '**', false);
				CIMContactList::SetRecent($arFields['TO_USER_ID'], $messageID, false, $arFields['FROM_USER_ID']);
				CIMContactList::SetRecent($arFields['FROM_USER_ID'], $messageID, false, $arFields['TO_USER_ID']);

				CIMStatus::SetIdle($arFields['FROM_USER_ID'], false);

				if (!$bConvert)
				{
					$strSql = "
						UPDATE b_im_relation
						SET STATUS = (case when USER_ID = ".$arFields['TO_USER_ID']." then '".IM_STATUS_UNREAD."' else '".IM_STATUS_READ."' end),
						LAST_ID = (case when USER_ID = ".$arFields['TO_USER_ID']." then LAST_ID else ".$messageID." end),
						LAST_SEND_ID = (case when USER_ID = ".$arFields['TO_USER_ID']." then LAST_SEND_ID else ".$messageID." end),
						LAST_READ = (case when USER_ID = ".$arFields['TO_USER_ID']." then LAST_READ else ".$DB->CurrentTimeFunction()." end)
						WHERE CHAT_ID = ".$chatId;
					$DB->Query($strSql, false, "File: ".__FILE__."<br>Line: ".__LINE__);

					if (CModule::IncludeModule("pull"))
					{
						$arParams['FROM_USER_ID'] = $arFields['FROM_USER_ID'];
						$arParams['TO_USER_ID'] = $arFields['TO_USER_ID'];

						$pushText = '';
						if (CPullOptions::GetPushStatus() && (!isset($arFields['PUSH']) || $arFields['PUSH'] == 'Y'))
						{
							$arSelect = Array("ID", "LAST_NAME", "NAME", "LOGIN", "SECOND_NAME");
							$dbUsers = CUser::GetList(($sort_by = false), ($dummy=''), array('ID' => $arParams['FROM_USER_ID']), array('FIELDS' => $arSelect));
							if ($arUser = $dbUsers->GetNext(true, false))
							{
								$sName = CUser::FormatName(CSite::GetNameFormat(false), $arUser, true, false);
								$pushText = $sName.': '.$arParams['MESSAGE'];

								if (count($arFields['FILES']) > 0 && strlen($pushText) < 200)
								{
									foreach ($arFields['FILES'] as $file)
									{
										$file = " [".GetMessage('IM_MESSAGE_FILE').": ".$file['name']."]";
										if (strlen($pushText.$file) > 200)
											break;

										$pushText = trim($pushText).$file;
									}
								}
							}
						}

						$arPullTo = Array(
							'module_id' => 'im',
							'command' => 'message',
							'params' => CIMMessage::GetFormatMessage(Array(
								'ID' => $messageID,
								'CHAT_ID' => $chatId,
								'TO_USER_ID' => $arParams['TO_USER_ID'],
								'FROM_USER_ID' => $arParams['FROM_USER_ID'],
								'SYSTEM' => $arFields['SYSTEM'] == 'Y'? 'Y': 'N',
								'MESSAGE' => $arParams['MESSAGE'],
								'DATE_CREATE' => time(),
								'PARAMS' => $arFields['PARAMS'],
								'FILES' => $arFields['FILES'],
							)),
						);
						$arPullFrom = $arPullTo;

						$arPullTo['push_params'] = 'IM_MESS_'.$arParams['FROM_USER_ID'];
						$arPullTo['push_tag'] = 'IM_MESS_'.$arParams['FROM_USER_ID'];
						$arPullTo['push_sub_tag'] = 'IM_MESS';
						$arPullTo['push_app_id'] = 'Bitrix24';
						$arPullTo['push_text'] = preg_replace("/\[s\].*?\[\/s\]/i", "", $pushText);
						$arPullTo['push_text'] = preg_replace("/\[[bui]\](.*?)\[\/[bui]\]/i", "$1", $arPullTo['push_text']);
						$arPullTo['push_text'] = preg_replace("/------------------------------------------------------(.*)------------------------------------------------------/mi", " [".GetMessage('IM_QUOTE')."] ", str_replace(array("#BR#"), Array(" "), $arPullTo['push_text']));

						CPullStack::AddByUser($arParams['TO_USER_ID'], $arPullTo);
						CPullStack::AddByUser($arParams['FROM_USER_ID'], $arPullFrom);

						CPushManager::DeleteFromQueueBySubTag($arParams['FROM_USER_ID'], 'IM_MESS');

						self::SendBadges($arParams['TO_USER_ID']);
					}
					foreach(GetModuleEvents("im", "OnAfterMessagesAdd", true) as $arEvent)
						ExecuteModuleEventEx($arEvent, array(intval($messageID), $arFields));
				}

				return $messageID;
			}
			else
			{
				$GLOBALS["APPLICATION"]->ThrowException(GetMessage("IM_ERROR_MESSAGE_CREATE"), "CHAT_ID");
				return false;
			}
		}
		else if ($arFields['MESSAGE_TYPE'] == IM_MESSAGE_GROUP)
		{
			$arFields['FROM_USER_ID'] = intval($arFields['FROM_USER_ID']);
			$chatId = 0;
			$systemMessage = false;
			if (isset($arFields['SYSTEM']) && $arFields['SYSTEM'] == 'Y')
			{
				$strSql = "
					SELECT C.ID CHAT_ID, C.TITLE CHAT_TITLE, C.AUTHOR_ID CHAT_AUTHOR_ID
					FROM b_im_chat C
					WHERE C.ID = ".intval($arFields['TO_CHAT_ID'])."
				";
				$systemMessage = true;
			}
			else
			{
				$strSql = "
					SELECT R.CHAT_ID, C.TITLE CHAT_TITLE, C.AUTHOR_ID CHAT_AUTHOR_ID
					FROM b_im_relation R LEFT JOIN b_im_chat C ON R.CHAT_ID = C.ID
					WHERE R.USER_ID = ".$arFields['FROM_USER_ID']." AND R.CHAT_ID = ".intval($arFields['TO_CHAT_ID'])."
				";
			}
			$dbRes = $DB->Query($strSql, false, "File: ".__FILE__."<br>Line: ".__LINE__);
			if ($arRes = $dbRes->Fetch())
			{
				$chatId = intval($arRes['CHAT_ID']);
				$chatTitle = htmlspecialcharsbx($arRes['CHAT_TITLE']);
				$chatAuthorId = intval($arRes['CHAT_AUTHOR_ID']);
			}
			else
			{
				$GLOBALS["APPLICATION"]->ThrowException(GetMessage("IM_ERROR_GROUP_CANCELED"), "CANCELED");
				return false;
			}

			if ($chatId > 0)
			{
				$arParams = Array();
				$arParams['CHAT_ID'] = $chatId;
				$arParams['AUTHOR_ID'] = $systemMessage? 0: intval($arFields['AUTHOR_ID']);
				$arParams['MESSAGE'] = trim($arFields['MESSAGE']);
				$arParams['MESSAGE_OUT'] = trim($arFields['MESSAGE_OUT']);
				$arParams['NOTIFY_MODULE'] = 'im';
				$arParams['NOTIFY_EVENT'] = 'group';

				if (isset($arFields['MESSAGE_DATE']))
					$arParams['DATE_CREATE'] = $arFields['MESSAGE_DATE'];
				else
					$arParams['~DATE_CREATE'] = $DB->CurrentTimeFunction();

				$arFiles = Array();
				$arFields['FILES'] = Array();
				if (isset($arFields['PARAMS']['FILE_ID']))
				{
					foreach ($arFields['PARAMS']['FILE_ID'] as $fileId)
					{
						$arFiles[$fileId] = $fileId;
					}
				}
				$arFields['FILES'] = CIMDisk::GetFiles($chatId, $arFiles);

				$messageFiles = self::GetFormatFilesMessageOut($arFields['FILES']);
				if (strlen($messageFiles) > 0)
				{
					$arParams['MESSAGE_OUT'] = strlen($arParams['MESSAGE_OUT'])>0? $arParams['MESSAGE_OUT']."\n".$messageFiles: $messageFiles;
					$arFields['MESSAGE_OUT'] = $arParams['MESSAGE_OUT'];
				}

				$messageID = IntVal($DB->Add("b_im_message", $arParams, Array('MESSAGE','MESSAGE_OUT')));
				if ($messageID <= 0)
					return false;

				if (!empty($arFields['PARAMS']))
					CIMMessageParam::Set($messageID, $arFields['PARAMS']);

				$sqlCounter = "SELECT USER_ID as ID, 1 as CNT, '**' as SITE_ID, 'im_chat_v2' as CODE, 1 as SENT
								FROM b_im_relation R1
								WHERE CHAT_ID = ".$chatId." AND USER_ID <> ".$arFields['FROM_USER_ID'];
				//CUserCounter::IncrementWithSelect($sqlCounter, false);

				$arRel = CIMChat::GetRelationById($chatId);
				foreach ($arRel as $rel)
					CIMContactList::SetRecent($chatId, $messageID, true, $rel['USER_ID']);

				$strSql = "
					UPDATE b_im_relation
					SET STATUS = (case when USER_ID = ".$arFields['FROM_USER_ID']." then '".IM_STATUS_READ."' else '".IM_STATUS_UNREAD."' end),
					LAST_ID = (case when USER_ID = ".$arFields['FROM_USER_ID']." then ".$messageID." else LAST_ID end),
					LAST_SEND_ID = (case when USER_ID = ".$arFields['FROM_USER_ID']." then ".$messageID." else LAST_SEND_ID end),
					LAST_READ = (case when USER_ID = ".$arFields['FROM_USER_ID']." then ".$DB->CurrentTimeFunction()." else LAST_READ end)
					WHERE CHAT_ID = ".$chatId;
				$DB->Query($strSql, false, "File: ".__FILE__."<br>Line: ".__LINE__);

				CIMStatus::SetIdle($arFields['FROM_USER_ID'], false);

				if (CModule::IncludeModule("pull"))
				{
					$arParams['FROM_USER_ID'] = $arFields['FROM_USER_ID'];
					$arParams['TO_CHAT_ID'] = $arFields['TO_CHAT_ID'];

					$arPullTo = Array(
						'module_id' => 'im',
						'command' => 'messageChat',
						'params' => CIMMessage::GetFormatMessage(Array(
							'ID' => $messageID,
							'CHAT_ID' => $chatId,
							'TO_CHAT_ID' => $arParams['TO_CHAT_ID'],
							'FROM_USER_ID' => $arParams['FROM_USER_ID'],
							'MESSAGE' => $arParams['MESSAGE'],
							'SYSTEM' => $arFields['SYSTEM'] == 'Y'? 'Y': 'N',
							'DATE_CREATE' => time(),
							'PARAMS' => $arFields['PARAMS'],
							'FILES' => $arFields['FILES'],
						)),
					);
					$arPullFrom = $arPullTo;
					unset($arPullFrom['push_text']);

					foreach ($arRel as $rel)
					{
						if ($rel['USER_ID'] == $arParams['FROM_USER_ID'])
						{
							CPullStack::AddByUser($arParams['FROM_USER_ID'], $arPullFrom);
							CPushManager::DeleteFromQueueBySubTag($arParams['FROM_USER_ID'], 'IM_MESS');
						}
					}

					$usersForBadges = Array();
					foreach ($arRel as $rel)
					{
						if ($rel['USER_ID'] != $arParams['FROM_USER_ID'])
						{
							CPullStack::AddByUser($rel['USER_ID'], $arPullTo);
							$usersForBadges[] = $rel['USER_ID'];
						}
					}
					self::SendBadges($usersForBadges);
				}
				foreach(GetModuleEvents("im", "OnAfterMessagesAdd", true) as $arEvent)
					ExecuteModuleEventEx($arEvent, array(intval($messageID), $arFields));

				return $messageID;
			}
			else
			{
				$GLOBALS["APPLICATION"]->ThrowException(GetMessage("IM_ERROR_MESSAGE_CREATE"), "CHAT_ID");
				return false;
			}

		}
		else if ($arFields['MESSAGE_TYPE'] == IM_MESSAGE_SYSTEM)
		{
			$arFields['TO_USER_ID'] = intval($arFields['TO_USER_ID']);
			$chatId = 0;
			$strSql = "
				SELECT CHAT_ID
				FROM b_im_relation
				WHERE USER_ID = ".$arFields['TO_USER_ID']." AND MESSAGE_TYPE = '".IM_MESSAGE_SYSTEM."'";
			$dbRes = $DB->Query($strSql, false, "File: ".__FILE__."<br>Line: ".__LINE__);
			if ($arRes = $dbRes->Fetch())
				$chatId = intval($arRes['CHAT_ID']);
			else
			{
				$chatId = IntVal($DB->Add("b_im_chat", Array('AUTHOR_ID' => $arFields['TO_USER_ID']), Array()));
				if ($chatId <= 0)
				{
					$GLOBALS["APPLICATION"]->ThrowException(GetMessage("IM_ERROR_MESSAGE_CREATE"), "CHAT_ID");
					return false;
				}

				$strSql = "INSERT INTO b_im_relation (CHAT_ID, MESSAGE_TYPE, USER_ID, STATUS) VALUES (".$chatId.",'".IM_MESSAGE_SYSTEM."',".intval($arFields['TO_USER_ID']).", ".($bConvert? 2: 0).")";
				$DB->Query($strSql, false, "File: ".__FILE__."<br>Line: ".__LINE__);
			}

			if ($chatId > 0)
			{
				$arParams = Array();
				$arParams['CHAT_ID'] = $chatId;
				$arParams['AUTHOR_ID'] = intval($arFields['AUTHOR_ID']);
				$arParams['MESSAGE'] = trim($arFields['MESSAGE']);
				$arParams['MESSAGE_OUT'] = trim($arFields['MESSAGE_OUT']);
				$arParams['NOTIFY_TYPE'] = intval($arFields['NOTIFY_TYPE']);
				$arParams['NOTIFY_MODULE'] = $arFields['NOTIFY_MODULE'];
				$arParams['NOTIFY_EVENT'] = $arFields['NOTIFY_EVENT'];

				//if (strlen($arParams['MESSAGE']) <= 0 && strlen($arParams['MESSAGE_OUT']) <= 0)
				//	return false;

				$sendToSite = true;
				if ($arParams['NOTIFY_TYPE'] != IM_NOTIFY_CONFIRM)
					$sendToSite = CIMSettings::GetNotifyAccess($arFields["TO_USER_ID"], $arFields["NOTIFY_MODULE"], $arFields["NOTIFY_EVENT"], CIMSettings::CLIENT_SITE);

				if (!$sendToSite)
					$arParams['NOTIFY_READ'] = 'Y';

				if (isset($arFields['IMPORT_ID']))
					$arParams['IMPORT_ID'] = intval($arFields['IMPORT_ID']);

				if (isset($arFields['MESSAGE_DATE']))
					$arParams['DATE_CREATE'] = $arFields['MESSAGE_DATE'];
				else
					$arParams['~DATE_CREATE'] = $DB->CurrentTimeFunction();

				if (isset($arFields['EMAIL_TEMPLATE']) && strlen(trim($arFields['EMAIL_TEMPLATE']))>0)
					$arParams['EMAIL_TEMPLATE'] = trim($arFields['EMAIL_TEMPLATE']);

				if (isset($arFields['NOTIFY_TAG']))
					$arParams['NOTIFY_TAG'] = $arFields['NOTIFY_TAG'];

				if (isset($arFields['NOTIFY_SUB_TAG']))
					$arParams['NOTIFY_SUB_TAG'] = $arFields['NOTIFY_SUB_TAG'];

				if (isset($arFields['NOTIFY_TITLE']) && strlen(trim($arFields['NOTIFY_TITLE']))>0)
					$arParams['NOTIFY_TITLE'] = trim($arFields['NOTIFY_TITLE']);

				if ($arParams['NOTIFY_TYPE'] == IM_NOTIFY_CONFIRM)
				{
					if (isset($arFields['NOTIFY_BUTTONS']))
					{
						foreach ($arFields['NOTIFY_BUTTONS'] as $key => $arButtons)
						{
							if (is_array($arButtons))
							{
								if (isset($arButtons['TITLE']) && strlen($arButtons['TITLE']) > 0
								&& isset($arButtons['VALUE']) && strlen($arButtons['VALUE']) > 0
								&& isset($arButtons['TYPE']) && strlen($arButtons['TYPE']) > 0)
								{
									$arButtons['TITLE'] = htmlspecialcharsbx($arButtons['TITLE']);
									$arButtons['VALUE'] = htmlspecialcharsbx($arButtons['VALUE']);
									$arButtons['TYPE'] = htmlspecialcharsbx($arButtons['TYPE']);
									$arFields['NOTIFY_BUTTONS'][$key] = $arButtons;
								}
								else
									unset($arFields['NOTIFY_BUTTONS'][$key]);
							}
							else
								unset($arFields['NOTIFY_BUTTONS'][$key]);
						}
					}
					else
					{
						$arFields['NOTIFY_BUTTONS'] = Array(
							Array('TITLE' => GetMessage('IM_ERROR_BUTTON_ACCEPT'), 'VALUE' => 'Y', 'TYPE' => 'accept'),
							Array('TITLE' => GetMessage('IM_ERROR_BUTTON_CANCEL'), 'VALUE' => 'N', 'TYPE' => 'cancel'),
						);
					}
					$arParams['NOTIFY_BUTTONS'] = serialize($arFields["NOTIFY_BUTTONS"]);

					if (isset($arParams['NOTIFY_TAG']) && strlen($arParams['NOTIFY_TAG'])>0)
						CIMNotify::DeleteByTag($arParams['NOTIFY_TAG']);
				}

				$messageID = IntVal($DB->Add("b_im_message", $arParams, Array('MESSAGE', 'MESSAGE_OUT', 'NOTIFY_BUTTONS')));
				if ($messageID <= 0)
					return false;

				if ($sendToSite)
					CIMMessenger::SpeedFileDelete($arFields['TO_USER_ID'], IM_SPEED_NOTIFY);

				if (!$bConvert)
				{
					//CUserCounter::Increment($arFields['TO_USER_ID'], 'im_notify_v2', '**', false);
					$strSql = "UPDATE b_im_relation SET STATUS = '".IM_STATUS_UNREAD."' WHERE USER_ID = ".intval($arFields['TO_USER_ID'])." AND MESSAGE_TYPE = '".IM_MESSAGE_SYSTEM."' AND CHAT_ID = ".$chatId;
					$DB->Query($strSql, false, "File: ".__FILE__."<br>Line: ".__LINE__);

					if (CModule::IncludeModule("pull"))
					{
						CPullStack::AddByUser(intval($arFields['TO_USER_ID']), Array(
							'module_id' => 'im',
							'command' => 'notify',
							'params' => CIMNotify::GetFormatNotify(Array(
								'ID' => $messageID,
								'DATE_CREATE' => time(),
								'FROM_USER_ID' => intval($arFields['FROM_USER_ID']),
								'MESSAGE' => $arParams['MESSAGE'],
								'NOTIFY_MODULE' => $arParams['NOTIFY_MODULE'],
								'NOTIFY_EVENT' => $arParams['NOTIFY_EVENT'],
								'NOTIFY_TAG' => $arParams['NOTIFY_TAG'],
								'NOTIFY_TYPE' => $arParams['NOTIFY_TYPE'],
								'NOTIFY_BUTTONS' => isset($arParams['NOTIFY_BUTTONS'])? $arParams['NOTIFY_BUTTONS']: serialize(Array()),
								'NOTIFY_TITLE' => isset($arParams['NOTIFY_TITLE'])? $arParams['NOTIFY_TITLE']: '',
								'NOTIFY_SILENT' => $sendToSite? false: true,
							)),
						));
						self::SendBadges($arFields['TO_USER_ID']);
					}
					foreach(GetModuleEvents("im", "OnAfterNotifyAdd", true) as $arEvent)
						ExecuteModuleEventEx($arEvent, array(intval($messageID), $arFields));
				}

				return $messageID;
			}
			else
			{
				$GLOBALS["APPLICATION"]->ThrowException(GetMessage("IM_ERROR_MESSAGE_CREATE"), "CHAT_ID");
				return false;
			}
		}
		else
		{
			$GLOBALS["APPLICATION"]->ThrowException(GetMessage("IM_ERROR_MESSAGE_TYPE"), "MESSAGE_TYPE");
			return false;
		}

		return false;
	}
 public static function Add($arFields)
 {
     global $DB;
     if (isset($arFields['TITLE']) && !isset($arFields['NOTIFY_TITLE'])) {
         $arFields['NOTIFY_TITLE'] = $arFields['TITLE'];
     }
     if (isset($arFields['NOTIFY_MESSAGE']) && !isset($arFields['MESSAGE'])) {
         $arFields['MESSAGE'] = $arFields['NOTIFY_MESSAGE'];
     }
     if (isset($arFields['NOTIFY_MESSAGE_OUT']) && !isset($arFields['MESSAGE_OUT'])) {
         $arFields['MESSAGE_OUT'] = $arFields['NOTIFY_MESSAGE_OUT'];
     }
     $bConvert = false;
     if (isset($arFields['CONVERT']) && $arFields['CONVERT'] == 'Y') {
         $bConvert = true;
     }
     if (!isset($arFields['MESSAGE_OUT'])) {
         $arFields['MESSAGE_OUT'] = "";
     }
     if (!isset($arFields['MESSAGE_TYPE'])) {
         $arFields['MESSAGE_TYPE'] = "";
     }
     if (!isset($arFields['NOTIFY_MODULE'])) {
         $arFields['NOTIFY_MODULE'] = 'im';
     }
     if (!isset($arFields['NOTIFY_EVENT'])) {
         $arFields['NOTIFY_EVENT'] = 'default';
     }
     if ($arFields['MESSAGE_TYPE'] == IM_MESSAGE_SYSTEM) {
         if (!isset($arFields['NOTIFY_TYPE']) && intval($arFields['FROM_USER_ID']) > 0) {
             $arFields['NOTIFY_TYPE'] = IM_NOTIFY_FROM;
         } else {
             if (!isset($arFields['NOTIFY_TYPE'])) {
                 $arFields['NOTIFY_TYPE'] = IM_NOTIFY_SYSTEM;
             }
         }
     }
     if (isset($arFields['NOTIFY_EMAIL_TEMPLATE']) && !isset($arFields['EMAIL_TEMPLATE'])) {
         $arFields['EMAIL_TEMPLATE'] = $arFields['NOTIFY_EMAIL_TEMPLATE'];
     }
     if (isset($arFields['EMAIL_TEMPLATE']) && strlen(trim($arFields['EMAIL_TEMPLATE'])) > 0) {
         $arParams['EMAIL_TEMPLATE'] = trim($arFields['EMAIL_TEMPLATE']);
     }
     if (!isset($arFields['AUTHOR_ID'])) {
         $arFields['AUTHOR_ID'] = intval($arFields['FROM_USER_ID']);
     }
     foreach (GetModuleEvents("im", "OnBeforeMessageNotifyAdd", true) as $arEvent) {
         $result = ExecuteModuleEventEx($arEvent, array(&$arFields));
         if ($result === false || isset($result['result']) && $result['result'] === false) {
             if (isset($result['reason'])) {
                 $CBXSanitizer = new CBXSanitizer();
                 $CBXSanitizer->AddTags(array('a' => array('href', 'style', 'target'), 'b' => array(), 'u' => array(), 'i' => array(), 'br' => array(), 'span' => array('style')));
                 $reason = $CBXSanitizer->SanitizeHtml($result['reason']);
             } else {
                 $reason = $arFields['MESSAGE_TYPE'] == IM_MESSAGE_PRIVATE ? GetMessage("IM_ERROR_MESSAGE_CANCELED") : ($arFields['MESSAGE_TYPE'] == IM_MESSAGE_GROUP ? GetMessage("IM_ERROR_GROUP_CANCELED") : GetMessage("IM_ERROR_NOTIFY_CANCELED"));
             }
             $GLOBALS["APPLICATION"]->ThrowException($reason, "ERROR_FROM_OTHER_MODULE");
             return false;
         }
     }
     if (!self::CheckFields($arFields)) {
         return false;
     }
     if ($arFields['MESSAGE_TYPE'] == IM_MESSAGE_PRIVATE) {
         $arFields['FROM_USER_ID'] = intval($arFields['FROM_USER_ID']);
         $arFields['TO_USER_ID'] = intval($arFields['TO_USER_ID']);
         $chatId = 0;
         $strSql = "\n\t\t\t\tSELECT RF.CHAT_ID\n\t\t\t\tFROM\n\t\t\t\t\tb_im_relation RF\n\t\t\t\t\tINNER JOIN b_im_relation RT on RF.CHAT_ID = RT.CHAT_ID\n\t\t\t\tWHERE\n\t\t\t\t\tRF.USER_ID = " . $arFields['FROM_USER_ID'] . "\n\t\t\t\tand RT.USER_ID = " . $arFields['TO_USER_ID'] . "\n\t\t\t\tand RF.MESSAGE_TYPE = '" . IM_MESSAGE_PRIVATE . "'\n\t\t\t";
         $dbRes = $DB->Query($strSql, false, "File: " . __FILE__ . "<br>Line: " . __LINE__);
         if ($arRes = $dbRes->Fetch()) {
             $chatId = intval($arRes['CHAT_ID']);
         } else {
             $chatId = IntVal($DB->Add("b_im_chat", array('AUTHOR_ID' => $arFields['AUTHOR_ID']), array()));
             if ($chatId <= 0) {
                 $GLOBALS["APPLICATION"]->ThrowException(GetMessage("IM_ERROR_MESSAGE_CREATE"), "CHAT_ID");
                 return false;
             }
             $strSql = "INSERT INTO b_im_relation (CHAT_ID, MESSAGE_TYPE, USER_ID, STATUS) VALUES (" . $chatId . ",'" . IM_MESSAGE_PRIVATE . "'," . $arFields['FROM_USER_ID'] . ", " . ($bConvert ? 2 : 0) . ")";
             $DB->Query($strSql, false, "File: " . __FILE__ . "<br>Line: " . __LINE__);
             $strSql = "INSERT INTO b_im_relation (CHAT_ID, MESSAGE_TYPE, USER_ID, STATUS) VALUES (" . $chatId . ",'" . IM_MESSAGE_PRIVATE . "'," . $arFields['TO_USER_ID'] . ", " . ($bConvert ? 2 : 0) . ")";
             $DB->Query($strSql, false, "File: " . __FILE__ . "<br>Line: " . __LINE__);
         }
         if ($chatId > 0) {
             $arParams = array();
             $arParams['CHAT_ID'] = $chatId;
             $arParams['AUTHOR_ID'] = intval($arFields['AUTHOR_ID']);
             $arParams['MESSAGE'] = trim($arFields['MESSAGE']);
             $arParams['MESSAGE_OUT'] = trim($arFields['MESSAGE_OUT']);
             $arParams['NOTIFY_MODULE'] = $arFields['NOTIFY_MODULE'];
             $arParams['NOTIFY_EVENT'] = 'private';
             if (isset($arFields['IMPORT_ID'])) {
                 $arParams['IMPORT_ID'] = intval($arFields['IMPORT_ID']);
             }
             if (isset($arFields['MESSAGE_DATE'])) {
                 $arParams['DATE_CREATE'] = $arFields['MESSAGE_DATE'];
             } else {
                 $arParams['~DATE_CREATE'] = $DB->CurrentTimeFunction();
             }
             $messageID = IntVal($DB->Add("b_im_message", $arParams, array('MESSAGE', 'MESSAGE_OUT')));
             CIMContactList::SetRecent($arFields['TO_USER_ID'], $messageID, false, $arFields['FROM_USER_ID']);
             CIMContactList::UpdateRecent($arFields['FROM_USER_ID'], $messageID, false, $arFields['TO_USER_ID']);
             if (!$bConvert) {
                 if (CModule::IncludeModule("pull")) {
                     $arParams['FROM_USER_ID'] = $arFields['FROM_USER_ID'];
                     $arParams['TO_USER_ID'] = $arFields['TO_USER_ID'];
                     $pushText = '';
                     if (CPullOptions::GetPushStatus()) {
                         $arSelect = array("ID", "LAST_NAME", "NAME", "LOGIN", "SECOND_NAME");
                         $dbUsers = CUser::GetList($sort_by = false, $dummy = '', array('ID' => $arParams['FROM_USER_ID']), array('FIELDS' => $arSelect));
                         if ($arUser = $dbUsers->GetNext(true, false)) {
                             $sName = CUser::FormatName(CSite::GetNameFormat(false), $arUser, true, false);
                             $pushText = $sName . ': ' . $arParams['MESSAGE'];
                         }
                     }
                     $arPullTo = array('module_id' => 'im', 'command' => 'message', 'params' => CIMMessage::GetFormatMessage(array('ID' => $messageID, 'TO_USER_ID' => $arParams['TO_USER_ID'], 'FROM_USER_ID' => $arParams['FROM_USER_ID'], 'MESSAGE' => $arParams['MESSAGE'], 'DATE_CREATE' => time())), 'push_params' => 'IM_MESS_' . $arParams['FROM_USER_ID'], 'push_tag' => 'IM_MESS_' . $arParams['FROM_USER_ID'], 'push_text' => $pushText);
                     $arPullFrom = $arPullTo;
                     unset($arPullFrom['push_text']);
                     CPullStack::AddByUser($arParams['TO_USER_ID'], $arPullTo);
                     CPullStack::AddByUser($arParams['FROM_USER_ID'], $arPullFrom);
                 }
                 $strSql = "\n\t\t\t\t\t\tUPDATE b_im_relation SET STATUS = '" . IM_STATUS_UNREAD . "'\n\t\t\t\t\t\tWHERE USER_ID = " . $arFields['TO_USER_ID'] . " AND MESSAGE_TYPE = '" . IM_MESSAGE_PRIVATE . "' AND CHAT_ID = " . $chatId;
                 $dbRes = $DB->Query($strSql, false, "File: " . __FILE__ . "<br>Line: " . __LINE__);
                 foreach (GetModuleEvents("im", "OnAfterMessagesAdd", true) as $arEvent) {
                     ExecuteModuleEventEx($arEvent, array(intval($messageID), $arFields));
                 }
             }
             return $messageID;
         } else {
             $GLOBALS["APPLICATION"]->ThrowException(GetMessage("IM_ERROR_MESSAGE_CREATE"), "CHAT_ID");
             return false;
         }
     } else {
         if ($arFields['MESSAGE_TYPE'] == IM_MESSAGE_GROUP) {
             $chatId = 0;
             $systemMessage = false;
             if (isset($arFields['SYSTEM']) && $arFields['SYSTEM'] == 'Y' && intval($arFields['FROM_USER_ID']) <= 0) {
                 $strSql = "\n\t\t\t\t\tSELECT C.ID CHAT_ID, C.TITLE CHAT_TITLE, C.AUTHOR_ID CHAT_AUTHOR_ID\n\t\t\t\t\tFROM b_im_chat C\n\t\t\t\t\tWHERE C.ID = " . intval($arFields['TO_CHAT_ID']) . "\n\t\t\t\t";
                 $systemMessage = true;
             } else {
                 $strSql = "\n\t\t\t\t\tSELECT R.CHAT_ID, C.TITLE CHAT_TITLE, C.AUTHOR_ID CHAT_AUTHOR_ID\n\t\t\t\t\tFROM b_im_relation R LEFT JOIN b_im_chat C ON R.CHAT_ID = C.ID\n\t\t\t\t\tWHERE R.USER_ID = " . intval($arFields['FROM_USER_ID']) . " AND R.MESSAGE_TYPE = '" . IM_MESSAGE_GROUP . "' AND R.CHAT_ID = " . intval($arFields['TO_CHAT_ID']) . "\n\t\t\t\t";
             }
             $dbRes = $DB->Query($strSql, false, "File: " . __FILE__ . "<br>Line: " . __LINE__);
             if ($arRes = $dbRes->Fetch()) {
                 $chatId = intval($arRes['CHAT_ID']);
                 $chatTitle = htmlspecialcharsbx($arRes['CHAT_TITLE']);
                 $chatAuthorId = intval($arRes['CHAT_AUTHOR_ID']);
             } else {
                 $GLOBALS["APPLICATION"]->ThrowException(GetMessage("IM_ERROR_GROUP_CANCELED"), "CANCELED");
                 return false;
             }
             if ($chatId > 0) {
                 $arParams = array();
                 $arParams['CHAT_ID'] = $chatId;
                 $arParams['AUTHOR_ID'] = intval($arFields['AUTHOR_ID']);
                 $arParams['MESSAGE'] = trim($arFields['MESSAGE']);
                 $arParams['MESSAGE_OUT'] = trim($arFields['MESSAGE_OUT']);
                 $arParams['NOTIFY_MODULE'] = 'im';
                 $arParams['NOTIFY_EVENT'] = 'group';
                 if (isset($arFields['MESSAGE_DATE'])) {
                     $arParams['DATE_CREATE'] = $arFields['MESSAGE_DATE'];
                 } else {
                     $arParams['~DATE_CREATE'] = $DB->CurrentTimeFunction();
                 }
                 $messageID = IntVal($DB->Add("b_im_message", $arParams, array('MESSAGE', 'MESSAGE_OUT')));
                 //if(!$systemMessage)
                 CIMContactList::SetRecent($chatId, $messageID, true, $arFields['FROM_USER_ID']);
                 CIMContactList::UpdateRecent($chatId, $messageID, true);
                 if (CModule::IncludeModule("pull")) {
                     $arParams['FROM_USER_ID'] = $arFields['FROM_USER_ID'];
                     $arParams['TO_CHAT_ID'] = $arFields['TO_CHAT_ID'];
                     $arPullTo = array('module_id' => 'im', 'command' => 'messageChat', 'params' => CIMMessage::GetFormatMessage(array('ID' => $messageID, 'TO_CHAT_ID' => $arParams['TO_CHAT_ID'], 'FROM_USER_ID' => $arParams['FROM_USER_ID'], 'MESSAGE' => $arParams['MESSAGE'], 'DATE_CREATE' => time())));
                     $arPullFrom = $arPullTo;
                     unset($arPullFrom['push_text']);
                     CPullStack::AddByUser($arParams['FROM_USER_ID'], $arPullFrom);
                     $arRel = CIMChat::GetRelationById($chatId);
                     foreach ($arRel as $rel) {
                         if ($rel['USER_ID'] != $arParams['FROM_USER_ID']) {
                             CPullStack::AddByUser($rel['USER_ID'], $arPullTo);
                         }
                     }
                 }
                 if (!$systemMessage) {
                     $strSql = "\n\t\t\t\t\t\tUPDATE b_im_relation SET STATUS = '" . IM_STATUS_UNREAD . "'\n\t\t\t\t\t\tWHERE USER_ID <> " . $arFields['FROM_USER_ID'] . " AND MESSAGE_TYPE = '" . IM_MESSAGE_GROUP . "' AND CHAT_ID = " . $chatId;
                     $dbRes = $DB->Query($strSql, false, "File: " . __FILE__ . "<br>Line: " . __LINE__);
                 }
                 foreach (GetModuleEvents("im", "OnAfterMessagesAdd", true) as $arEvent) {
                     ExecuteModuleEventEx($arEvent, array(intval($messageID), $arFields));
                 }
                 return $messageID;
             } else {
                 $GLOBALS["APPLICATION"]->ThrowException(GetMessage("IM_ERROR_MESSAGE_CREATE"), "CHAT_ID");
                 return false;
             }
         } else {
             if ($arFields['MESSAGE_TYPE'] == IM_MESSAGE_SYSTEM) {
                 $chatId = 0;
                 $strSql = "\n\t\t\t\tSELECT CHAT_ID\n\t\t\t\tFROM b_im_relation\n\t\t\t\tWHERE USER_ID = " . intval($arFields['TO_USER_ID']) . " AND MESSAGE_TYPE = '" . IM_MESSAGE_SYSTEM . "'";
                 $dbRes = $DB->Query($strSql, false, "File: " . __FILE__ . "<br>Line: " . __LINE__);
                 if ($arRes = $dbRes->Fetch()) {
                     $chatId = intval($arRes['CHAT_ID']);
                 } else {
                     $chatId = IntVal($DB->Add("b_im_chat", array('AUTHOR_ID' => intval($arFields['TO_USER_ID'])), array()));
                     if ($chatId <= 0) {
                         $GLOBALS["APPLICATION"]->ThrowException(GetMessage("IM_ERROR_MESSAGE_CREATE"), "CHAT_ID");
                         return false;
                     }
                     $strSql = "INSERT INTO b_im_relation (CHAT_ID, MESSAGE_TYPE, USER_ID, STATUS) VALUES (" . $chatId . ",'" . IM_MESSAGE_SYSTEM . "'," . intval($arFields['TO_USER_ID']) . ", " . ($bConvert ? 2 : 0) . ")";
                     $DB->Query($strSql, false, "File: " . __FILE__ . "<br>Line: " . __LINE__);
                 }
                 if ($chatId > 0) {
                     $arParams = array();
                     $arParams['CHAT_ID'] = $chatId;
                     $arParams['AUTHOR_ID'] = intval($arFields['AUTHOR_ID']);
                     $arParams['MESSAGE'] = trim($arFields['MESSAGE']);
                     $arParams['MESSAGE_OUT'] = trim($arFields['MESSAGE_OUT']);
                     $arParams['NOTIFY_TYPE'] = intval($arFields['NOTIFY_TYPE']);
                     $arParams['NOTIFY_MODULE'] = $arFields['NOTIFY_MODULE'];
                     $arParams['NOTIFY_EVENT'] = $arFields['NOTIFY_EVENT'];
                     if (isset($arFields['IMPORT_ID'])) {
                         $arParams['IMPORT_ID'] = intval($arFields['IMPORT_ID']);
                     }
                     if (isset($arFields['MESSAGE_DATE'])) {
                         $arParams['DATE_CREATE'] = $arFields['MESSAGE_DATE'];
                     } else {
                         $arParams['~DATE_CREATE'] = $DB->CurrentTimeFunction();
                     }
                     if (isset($arFields['EMAIL_TEMPLATE']) && strlen(trim($arFields['EMAIL_TEMPLATE'])) > 0) {
                         $arParams['EMAIL_TEMPLATE'] = trim($arFields['EMAIL_TEMPLATE']);
                     }
                     if (isset($arFields['NOTIFY_TAG'])) {
                         $arParams['NOTIFY_TAG'] = $arFields['NOTIFY_TAG'];
                     }
                     if (isset($arFields['NOTIFY_SUB_TAG'])) {
                         $arParams['NOTIFY_SUB_TAG'] = $arFields['NOTIFY_SUB_TAG'];
                     }
                     if (isset($arFields['NOTIFY_TITLE']) && strlen(trim($arFields['NOTIFY_TITLE'])) > 0) {
                         $arParams['NOTIFY_TITLE'] = trim($arFields['NOTIFY_TITLE']);
                     }
                     if ($arParams['NOTIFY_TYPE'] == IM_NOTIFY_CONFIRM) {
                         if (isset($arFields['NOTIFY_BUTTONS'])) {
                             foreach ($arFields['NOTIFY_BUTTONS'] as $key => $arButtons) {
                                 if (is_array($arButtons)) {
                                     if (isset($arButtons['TITLE']) && strlen($arButtons['TITLE']) > 0 && isset($arButtons['VALUE']) && strlen($arButtons['VALUE']) > 0 && isset($arButtons['TYPE']) && strlen($arButtons['TYPE']) > 0) {
                                         $arButtons['TITLE'] = htmlspecialcharsbx($arButtons['TITLE']);
                                         $arButtons['VALUE'] = htmlspecialcharsbx($arButtons['VALUE']);
                                         $arButtons['TYPE'] = htmlspecialcharsbx($arButtons['TYPE']);
                                         $arFields['NOTIFY_BUTTONS'][$key] = $arButtons;
                                     } else {
                                         unset($arFields['NOTIFY_BUTTONS'][$key]);
                                     }
                                 } else {
                                     unset($arFields['NOTIFY_BUTTONS'][$key]);
                                 }
                             }
                         } else {
                             $arFields['NOTIFY_BUTTONS'] = array(array('TITLE' => GetMessage('IM_ERROR_BUTTON_ACCEPT'), 'VALUE' => 'Y', 'TYPE' => 'accept'), array('TITLE' => GetMessage('IM_ERROR_BUTTON_CANCEL'), 'VALUE' => 'N', 'TYPE' => 'cancel'));
                         }
                         $arParams['NOTIFY_BUTTONS'] = serialize($arFields["NOTIFY_BUTTONS"]);
                         if (isset($arParams['NOTIFY_TAG']) && strlen($arParams['NOTIFY_TAG']) > 0) {
                             CIMNotify::DeleteByTag($arParams['NOTIFY_TAG']);
                         }
                     }
                     $messageID = IntVal($DB->Add("b_im_message", $arParams, array('MESSAGE', 'MESSAGE_OUT', 'NOTIFY_BUTTONS')));
                     CIMMessenger::SpeedFileDelete(intval($arFields['TO_USER_ID']), IM_SPEED_NOTIFY);
                     if (!$bConvert) {
                         if (CModule::IncludeModule("pull")) {
                             CPullStack::AddByUser(intval($arFields['TO_USER_ID']), array('module_id' => 'im', 'command' => 'notify', 'params' => CIMNotify::GetFormatNotify(array('ID' => $messageID, 'TIMESTAMP' => time(), 'FROM_USER_ID' => intval($arFields['FROM_USER_ID']), 'MESSAGE' => $arParams['MESSAGE'], 'NOTIFY_TAG' => $arParams['NOTIFY_TAG'], 'NOTIFY_TYPE' => $arParams['NOTIFY_TYPE'], 'NOTIFY_BUTTONS' => isset($arParams['NOTIFY_BUTTONS']) ? $arParams['NOTIFY_BUTTONS'] : serialize(array()), 'NOTIFY_TITLE' => isset($arParams['NOTIFY_TITLE']) ? $arParams['NOTIFY_TITLE'] : ''))));
                         }
                         $strSql = "\n\t\t\t\t\t\tUPDATE b_im_relation SET STATUS = '" . IM_STATUS_UNREAD . "'\n\t\t\t\t\t\tWHERE USER_ID = " . intval($arFields['TO_USER_ID']) . " AND MESSAGE_TYPE = '" . IM_MESSAGE_SYSTEM . "' AND CHAT_ID = " . $chatId;
                         $dbRes = $DB->Query($strSql, false, "File: " . __FILE__ . "<br>Line: " . __LINE__);
                         foreach (GetModuleEvents("im", "OnAfterNotifyAdd", true) as $arEvent) {
                             ExecuteModuleEventEx($arEvent, array(intval($messageID), $arFields));
                         }
                     }
                     return $messageID;
                 } else {
                     $GLOBALS["APPLICATION"]->ThrowException(GetMessage("IM_ERROR_MESSAGE_CREATE"), "CHAT_ID");
                     return false;
                 }
             } else {
                 $GLOBALS["APPLICATION"]->ThrowException(GetMessage("IM_ERROR_MESSAGE_TYPE"), "MESSAGE_TYPE");
                 return false;
             }
         }
     }
     return false;
 }
Beispiel #25
0
 			$_POST['apply'] = $_REQUEST['apply'] = "Y";
 			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);
Beispiel #26
0
 function Clear($text)
 {
     $arWhiteTags = array('a' => array('href', 'title', 'name', 'style', 'id', 'class', 'shape', 'coords', 'alt', 'target'), 'b' => array('style', 'id', 'class'), 'br' => array('style', 'id', 'class'), 'big' => array('style', 'id', 'class'), 'caption' => array('style', 'id', 'class'), 'code' => array('style', 'id', 'class'), 'color' => array(), 'del' => array('title', 'style', 'id', 'class'), 'div' => array('title', 'style', 'id', 'class', 'align'), 'dt' => array('style', 'id', 'class'), 'dd' => array('style', 'id', 'class'), 'font' => array('color', 'size', 'face', 'style', 'id', 'class'), 'h1' => array('style', 'id', 'class', 'align'), 'h2' => array('style', 'id', 'class', 'align'), 'h3' => array('style', 'id', 'class', 'align'), 'h4' => array('style', 'id', 'class', 'align'), 'h5' => array('style', 'id', 'class', 'align'), 'h6' => array('style', 'id', 'class', 'align'), 'hr' => array('style', 'id', 'class'), 'i' => array('style', 'id', 'class'), 'img' => array('src', 'alt', 'height', 'width', 'title'), 'ins' => array('title', 'style', 'id', 'class'), 'li' => array('style', 'id', 'class'), 'list' => array(), 'map' => array('shape', 'coords', 'href', 'alt', 'title', 'style', 'id', 'class', 'name'), 'nowiki' => array(), 'ol' => array('style', 'id', 'class'), 'p' => array('style', 'id', 'class', 'align'), 'pre' => array('style', 'id', 'class'), 's' => array('style', 'id', 'class'), 'small' => array('style', 'id', 'class'), 'strong' => array('style', 'id', 'class'), 'span' => array('title', 'style', 'id', 'class', 'align'), 'sub' => array('style', 'id', 'class'), 'sup' => array('style', 'id', 'class'), 'table' => array('border', 'width', 'style', 'id', 'class', 'cellspacing', 'cellpadding'), 'tbody' => array('align', 'valign', 'style', 'id', 'class'), 'td' => array('width', 'height', 'style', 'id', 'class', 'align', 'valign', 'colspan', 'rowspan'), 'tfoot' => array('align', 'valign', 'style', 'id', 'class', 'align', 'valign'), 'th' => array('width', 'height', 'style', 'id', 'class', 'colspan', 'rowspan'), 'thead' => array('align', 'valign', 'style', 'id', 'class'), 'tr' => array('align', 'valign', 'style', 'id', 'class'), 'ul' => array('style', 'id', 'class'), 'blockquote' => array(), 'u' => array('style', 'id', 'class'));
     /* TODO:erase CBXSanitizer::SetTags($arWhiteTags);
     		$text=CBXSanitizer::Sanitize($text,'CUSTOM',true,true); */
     $Sanitizer = new CBXSanitizer();
     $Sanitizer->AddTags($arWhiteTags);
     //TODO: delete condition, after main update
     if (method_exists($Sanitizer, "ApplyDoubleEncode")) {
         $Sanitizer->ApplyDoubleEncode(false);
     }
     $text = $Sanitizer->SanitizeHtml($text);
     return $text;
 }
Beispiel #27
0
     $currentItem = $dbRes->GetNext();
     if (!is_array($currentItem)) {
         __CrmMobileDealEditEndResonse(array('ERROR' => GetMessage('CRM_DEAL_NOT_FOUND', array('#ID#' => $ID))));
     }
 }
 $title = isset($data['TITLE']) ? $data['TITLE'] : '';
 if ($title === '') {
     __CrmMobileDealEditEndResonse(array('ERROR' => GetMessage('CRM_DEAL_TITLE_NOT_ASSIGNED')));
 }
 $opportunity = isset($data['OPPORTUNITY']) ? $data['OPPORTUNITY'] : '';
 if ($opportunity === '') {
     $opportunity = 0.0;
 }
 $comments = isset($data['COMMENTS']) ? $data['COMMENTS'] : '';
 if ($comments !== '') {
     $sanitizer = new CBXSanitizer();
     $sanitizer->SetLevel(CBXSanitizer::SECURE_LEVEL_HIGH);
     $comments = $sanitizer->SanitizeHtml($comments);
 }
 $fields = array('TITLE' => $title, 'OPPORTUNITY' => $opportunity, 'PROBABILITY' => isset($data['PROBABILITY']) ? $data['PROBABILITY'] : 0, 'STAGE_ID' => isset($data['STAGE_ID']) ? $data['STAGE_ID'] : '', 'TYPE_ID' => isset($data['TYPE_ID']) ? $data['TYPE_ID'] : '', 'COMPANY_ID' => isset($data['COMPANY_ID']) ? $data['COMPANY_ID'] : 0, 'CONTACT_ID' => isset($data['CONTACT_ID']) ? $data['CONTACT_ID'] : 0, 'COMMENTS' => $comments);
 $currencyID = isset($data['CURRENCY_ID']) ? $data['CURRENCY_ID'] : '';
 if ($currencyID === '') {
     $currencyID = CCrmCurrency::GetBaseCurrencyID();
 }
 $fields['CURRENCY_ID'] = $currencyID;
 $productDataFieldName = 'PRODUCT_ROWS';
 $processProductRows = isset($data['PROCESS_PRODUCT_ROWS']) ? $data['PROCESS_PRODUCT_ROWS'] === 'Y' : false;
 $productRows = array();
 if ($processProductRows) {
     $productRows = isset($data[$productDataFieldName]) ? $data[$productDataFieldName] : array();
     if (!empty($productRows)) {
Beispiel #28
0
 protected function parseCalcResult($jsonInfo)
 {
     global $APPLICATION;
     $arInfo = json_decode($jsonInfo, true);
     if (is_array($arInfo) && !empty($arInfo)) {
         if (strtolower(SITE_CHARSET) != 'utf-8') {
             $arInfo = \Bitrix\Main\Text\Encoding::convertEncodingArray($arInfo, 'UTF-8', SITE_CHARSET);
         }
         if (isset($arInfo[$this->profileId][2])) {
             $price = 0;
             $price += intval($arInfo[$this->profileId][2]);
             if (isset($arInfo["take"][2]) && \CDeliveryPecom::isConfCheckedVal($this->arConfig, 'SERVICE_TAKE_ENABLED')) {
                 $price += intval($arInfo["take"][2]);
             }
             if (isset($arInfo["deliver"][2]) && \CDeliveryPecom::isConfCheckedVal($this->arConfig, 'SERVICE_DELIVERY_ENABLED')) {
                 $price += intval($arInfo["deliver"][2]);
             }
             foreach ($arInfo as $key => $value) {
                 if (substr($key, 0, 3) == "ADD") {
                     $price += intval($arInfo[$key][2]);
                 }
             }
             $arResult = array('RESULT' => 'OK', 'VALUE' => $price, 'PACKS_COUNT' => $this->packsCount);
             $period = "";
             if ($this->profileId == "auto" && !empty($arInfo["periods"])) {
                 $period = $arInfo["periods"];
             } elseif ($this->profileId == "avia" && !empty($arInfo["aperiods"])) {
                 $period = $arInfo["aperiods"];
             }
             if (strlen($period) > 0) {
                 $pos = strpos($period, ':');
                 if ($pos !== false) {
                     $CBXSanitizer = new \CBXSanitizer();
                     $CBXSanitizer->DelAllTags();
                     $arResult["TRANSIT"] = " (" . GetMessage("SALE_DH_PECOM_PERIOD_DAYS") . ") " . $CBXSanitizer->SanitizeHtml(substr($period, $pos + 1));
                 }
             }
         } else {
             if (isset($arInfo["error"])) {
                 $error = implode("<br>", $arInfo["error"]);
                 if (strtolower(SITE_CHARSET) != 'utf-8') {
                     $error = $APPLICATION->ConvertCharset($error, 'utf-8', SITE_CHARSET);
                 }
             } else {
                 $error = GetMessage("SALE_DH_PECOM_ERROR");
             }
             $arResult = array('RESULT' => 'ERROR', 'TEXT' => $error);
         }
     } else {
         $arResult = array('RESULT' => 'ERROR', 'TEXT' => GetMessage("SALE_DH_PECOM_ERROR_NO_RESULTS"));
     }
     return $arResult;
 }
     $arProperty['FILTER_HINT'] = $_POST['PROPERTY_FILTER_HINT'];
 } else {
     $arProperty['FILTER_HINT'] = $arDefPropInfo['FILTER_HINT'];
 }
 $arProperty['MULTIPLE'] = 'Y' == $arProperty['MULTIPLE'] ? 'Y' : 'N';
 $arProperty['IS_REQUIRED'] = 'Y' == $arProperty['IS_REQUIRED'] ? 'Y' : 'N';
 $arProperty['FILTRABLE'] = 'Y' == $arProperty['FILTRABLE'] ? 'Y' : 'N';
 $arProperty['SEARCHABLE'] = 'Y' == $arProperty['SEARCHABLE'] ? 'Y' : 'N';
 $arProperty['ACTIVE'] = 'Y' == $arProperty['ACTIVE'] ? 'Y' : 'N';
 $arProperty['SECTION_PROPERTY'] = 'N' == $arProperty['SECTION_PROPERTY'] ? 'N' : 'Y';
 $arProperty['SMART_FILTER'] = 'Y' == $arProperty['SMART_FILTER'] ? 'Y' : 'N';
 $arProperty['DISPLAY_TYPE'] = substr($arProperty['DISPLAY_TYPE'], 0, 1);
 $arProperty['DISPLAY_EXPANDED'] = 'Y' == $arProperty['DISPLAY_EXPANDED'] ? 'Y' : 'N';
 $arProperty['FILTER_HINT'] = trim($arProperty['FILTER_HINT']);
 if ($arProperty['FILTER_HINT']) {
     $TextParser = new CBXSanitizer();
     $TextParser->SetLevel(CBXSanitizer::SECURE_LEVEL_LOW);
     $TextParser->ApplyHtmlSpecChars(false);
     $arProperty['FILTER_HINT'] = $TextParser->SanitizeHtml($arProperty['FILTER_HINT']);
 }
 $arProperty['MULTIPLE_CNT'] = intval($arProperty['MULTIPLE_CNT']);
 if (0 >= $arProperty['MULTIPLE_CNT']) {
     $arProperty['MULTIPLE_CNT'] = DEF_LIST_VALUE_COUNT;
 }
 $arProperty['WITH_DESCRIPTION'] = 'Y' == $arProperty['WITH_DESCRIPTION'] ? 'Y' : 'N';
 if (!empty($arListValues)) {
     $arProperty["VALUES"] = $arListValues;
 }
 $arHidden = array();
 foreach ($arHiddenPropFields as &$strPropField) {
     if (isset($arProperty[$strPropField])) {
 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;
 }