Esempio n. 1
0
 public static function ExtractEmail($str)
 {
     if (!(IsModuleInstalled('mail') && CModule::IncludeModule('mail'))) {
         $result = self::ParseEmail($str);
         return $result['EMAIL'];
     }
     return CMailUtil::ExtractMailAddress($str);
 }
Esempio n. 2
0
 function __ProcessCommand($command, $arg = '')
 {
     switch (strtoupper($command)) {
         case "HELO":
             $this->Send('250', 'domain name should be qualified');
             if (trim($arg) == '') {
                 $this->host = $this->ip;
             } else {
                 $this->host = $arg;
             }
             //500, 501, 504, 421
             break;
         case "SEND":
         case "SOML":
         case "SAML":
         case "MAIL":
             if (!preg_match('#FROM[ ]*:[ ]*(.+)#i', $arg, $arMatches)) {
                 $this->Send('501', 'Unrecognized parameter ' . $arg);
             } elseif ($this->arMsg["FROM"]) {
                 $this->Send('503', 'Sender already specified');
             } else {
                 $email = $arMatches[1];
                 $email = CMailUtil::ExtractMailAddress($email);
                 if ($email == '' || !check_email($email)) {
                     $this->Send('501', '<' . $email . '> Invalid Address');
                 } else {
                     $this->arMsg["FROM"] = $email;
                     $this->arMsg["TO"] = array();
                     $this->Send('250', '<' . $email . '> Sender ok');
                 }
             }
             //F: 552, 451, 452
             //E: 500, 501, 421
             break;
         case "RCPT":
             if (!preg_match('#TO[ ]*:[ ]*(.+)#i', $arg, $arMatches)) {
                 $this->Send('501', 'Unrecognized parameter ' . $arg);
             } else {
                 $email = $arMatches[1];
                 $email = CMailUtil::ExtractMailAddress($email);
                 if ($email == '' || !check_email($email)) {
                     $this->Send('501', '<' . $email . '> Invalid Address');
                 } elseif (false) {
                     $this->Send('550', '<' . $email . '> User unknown');
                 } elseif (!$this->CheckRelaying($email)) {
                     $this->Send('550', '<' . $email . '>... Relaying denied.');
                 } elseif (!$this->arMsg["FROM"]) {
                     $this->Send('503', 'Sender is not specified');
                 } else {
                     $this->arMsg["TO"][] = $email;
                     $this->Send('250', '<' . $email . '> ok');
                     //S: 250, 251
                     //F: 550, 551, 552, 553, 450, 451, 452
                     //E: 500, 501, 503, 421
                 }
             }
             break;
         case "DATA":
             if (!$this->arMsg["FROM"] || !$this->arMsg["TO"] || count($this->arMsg["TO"]) == 0) {
                 $this->Send('503');
             } else {
                 $this->Send('354');
                 $this->__listenFunc = '__DataHandler';
             }
             // I: 354 -> data -> S: 250
             //                      F: 552, 554, 451, 452
             //   F: 451, 554
             //   E: 500, 501, 503, 421
             break;
         case "RSET":
             $this->Send('250', 'Resetting');
             $this->arMsg = array('LOCAL_ID' => md5(uniqid()));
             //E: 500, 501, 504, 421
             break;
         case "QUIT":
             $this->Send('221');
             $this->Disconnect();
             //E: 500
             break;
         case "EHLO":
             if (trim($arg) == '') {
                 $this->host = $this->ip;
             } else {
                 $this->host = $arg;
             }
             $this->Send('250-ehlo', '');
             $this->Send('250-AUTH LOGIN PLAIN', '');
             //$this->Send('250-SIZE', '');
             $this->Send('250-HELP', '');
             $this->Send('250', 'EHLO');
             /*
             250-mail.company2.tld is pleased to meet you
             250-DSN
             250-SIZE
             250-STARTTLS
             250-AUTH LOGIN PLAIN CRAM-MD5 DIGEST-MD5 GSSAPI MSN NTLM
             250-ETRN
             250-TURN
             250-ATRN
             250-NO-SOLICITING
             250-HELP
             250-PIPELINING
             250 EHLO
             */
             break;
         case "AUTH":
             if ($this->authorized) {
                 $this->Send('503', 'Already authorized');
             } elseif (count($this->arMsg) > 1) {
                 $this->Send('503', 'Mail transaction is active');
             } elseif (!preg_match('#^([A-Z0-9-_]+)[ ]*(\\S*)$#i', $arg, $arMatches)) {
                 $this->Send('501', 'Unrecognized parameter ' . $arg);
             } else {
                 switch (strtoupper($arMatches[1])) {
                     case "LOGIN":
                         $this->Send('334', 'VXNlcm5hbWU6');
                         $this->__listenFunc = '__AuthLoginHandler';
                         $this->__login = false;
                         break;
                     case "PLAIN":
                         if ($arMatches[2] && trim($arMatches[2]) != '') {
                             $pwd = base64_decode($arMatches[2]);
                             $this->Authorize($pwd, $pwd);
                         } else {
                             $this->Send('334', '');
                             $this->__listenFunc = '__AuthPlainHandler';
                         }
                         break;
                     default:
                         $this->Send('504', 'Unrecognized authentication type.');
                 }
             }
             break;
         case "NOOP":
             $this->Send('250');
             //E: 500, 421
             break;
         case "HELP":
             //       S: 211, 214
             //       E: 500, 501, 502, 504, 421
             break;
         case "EXPN":
             //<string>
             //       S: 250
             //       F: 550
             //       E: 500, 501, 502, 504, 421
             break;
         case "VRFY":
             //       S: 250, 251
             //       F: 550, 551, 553
             //       E: 500, 501, 502, 504, 421
             break;
         default:
             $this->Send('500', $command . ' command unrecognized');
     }
     return true;
 }
Esempio n. 3
0
 foreach ($arParams['OPTIONS'] as $option) {
     if (empty($arResult['SETTINGS'][$option])) {
         unset($error);
         $arResult['SETTINGS'][$option] = isset($_REQUEST[$option]) ? $_REQUEST[$option] : null;
         $arResult['SETTINGS'][$option] = CheckOption($option, $arResult['SETTINGS'][$option], $error);
         if (!empty($error)) {
             $arResult['ERRORS'][] = $error;
         }
     }
 }
 if (!check_bitrix_sessid()) {
     $arResult['ERRORS'][] = GetMessage('INTR_MAIL_CSRF');
 }
 if (empty($arResult['ERRORS'])) {
     $error = false;
     $unseen = CMailUtil::CheckImapMailbox($arResult['SETTINGS']['server'], $arResult['SETTINGS']['port'], $arResult['SETTINGS']['encryption'], $arResult['SETTINGS']['login'], $arResult['SETTINGS']['password'], $error, 30);
     if ($error !== false) {
         $arResult['ERRORS'][] = $error;
     }
 }
 if (empty($arResult['ERRORS'])) {
     $arFields = array('LID' => SITE_ID, 'ACTIVE' => 'Y', 'SERVICE_ID' => $arResult['SERVICE'], 'NAME' => $arResult['SETTINGS']['name'], 'SERVER' => $arResult['SETTINGS']['server'], 'PORT' => $arResult['SETTINGS']['port'], 'LINK' => $arResult['SETTINGS']['link'], 'LOGIN' => $arResult['SETTINGS']['login'], 'PASSWORD' => $arResult['SETTINGS']['password'], 'USE_TLS' => $arResult['SETTINGS']['encryption'] == 'Y' ? 'Y' : 'N', 'SERVER_TYPE' => 'imap', 'USER_ID' => $USER->GetID());
     if (!empty($arResult['ID'])) {
         $res = CMailbox::Update($arResult['ID'], $arFields);
     } else {
         $arResult['ID'] = CMailbox::Add($arFields);
         $res = $arResult['ID'] > 0;
     }
     if (!$res) {
         $arResult['ERRORS'][] = GetMessage('INTR_MAIL_SAVE_ERROR');
     } else {
Esempio n. 4
0
require_once $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/main/include/prolog_before.php';
if (!is_object($USER) || !$USER->IsAuthorized()) {
    return;
}
$userId = $USER->GetID();
session_write_close();
CModule::IncludeModule('mail');
$siteId = isset($_REQUEST['SITE_ID']) ? $_REQUEST['SITE_ID'] : SITE_ID;
$error = false;
$dbAcc = CMailbox::GetList(array('TIMESTAMP_X' => 'DESC'), array('LID' => SITE_ID, 'ACTIVE' => 'Y', 'USER_ID' => $USER->GetID()));
while (($acc = $dbAcc->fetch()) !== false && !in_array($acc['SERVER_TYPE'], array('imap', 'controller', 'domain', 'crdomain'))) {
}
if (!empty($acc)) {
    switch ($acc['SERVER_TYPE']) {
        case 'imap':
            $unseen = CMailUtil::CheckImapMailbox($acc['SERVER'], $acc['PORT'], $acc['USE_TLS'], $acc['LOGIN'], $acc['PASSWORD'], $error, 30);
            break;
        case 'controller':
            list($acc['login'], $acc['domain']) = explode('@', $acc['LOGIN'], 2);
            $crCheckMailbox = CControllerClient::ExecuteEvent('OnMailControllerCheckMailbox', array('DOMAIN' => $acc['domain'], 'NAME' => $acc['login']));
            if (isset($crCheckMailbox['result'])) {
                $unseen = intval($crCheckMailbox['result']);
            } else {
                $unseen = -1;
                $error = empty($crCheckMailbox['error']) ? GetMessage('INTR_MAIL_CONTROLLER_INVALID') : CMail::getErrorMessage($crCheckMailbox['error']);
            }
            break;
        case 'crdomain':
            list($acc['login'], $acc['domain']) = explode('@', $acc['LOGIN'], 2);
            $crCheckMailbox = CControllerClient::ExecuteEvent('OnMailControllerCheckMemberMailbox', array('DOMAIN' => $acc['domain'], 'NAME' => $acc['login']));
            if (isset($crCheckMailbox['result'])) {
Esempio n. 5
0
 function EMailMessageAdd($arMessageFields, $ACTION_VARS)
 {
     $arActionVars = explode("&", $ACTION_VARS);
     $countAr = count($arActionVars);
     for ($i = 0; $i < $countAr; $i++) {
         $v = $arActionVars[$i];
         if ($pos = strpos($v, "=")) {
             ${substr($v, 0, $pos)} = urldecode(substr($v, $pos + 1));
         }
     }
     if (!CModule::IncludeModule("support")) {
         return false;
     }
     if (strlen($W_SUPPORT_SITE_ID) > 0) {
         $rs = CSite::GetByID($W_SUPPORT_SITE_ID);
         if ($ar = $rs->Fetch()) {
             $SITE_ID = $ar["LID"];
         }
     }
     if (strlen($SITE_ID) <= 0) {
         $SITE_ID = $arMessageFields["LID"];
     }
     $sourceMail = COption::GetOptionString("support", "SOURCE_MAIL");
     $dbr = CTicketDictionary::GetBySID($sourceMail, "SR", $SITE_ID);
     if (!($ar = $dbr->Fetch())) {
         return false;
     }
     $TICKET_SOURCE_ID = $ar["ID"];
     $ID = $arMessageFields["ID"];
     $message_email = strlen($arMessageFields["FIELD_REPLY_TO"]) > 0 ? $arMessageFields["FIELD_REPLY_TO"] : $arMessageFields["FIELD_FROM"];
     $message_email_addr = strtolower(CMailUtil::ExtractMailAddress($message_email));
     $TID = 0;
     $arSubjects = explode("\n", trim($W_SUPPORT_SUBJECT));
     $countAr = count($arSubjects);
     for ($i = 0; $i < $countAr; $i++) {
         $arSubjects[$i] = Trim($arSubjects[$i]);
         if (strlen($arSubjects[$i]) > 0) {
             if (preg_match("/" . $arSubjects[$i] . "/" . BX_UTF_PCRE_MODIFIER, $arMessageFields["SUBJECT"], $regs)) {
                 $TID = IntVal($regs[1]);
                 break;
             }
         }
     }
     if ($TID > 0) {
         $db_ticket = CTicket::GetByID($TID, $SITE_ID, "N", "N", "N");
         if ($ar_ticket = $db_ticket->Fetch()) {
             //check user email address limits
             if ($W_SUPPORT_SEC == "domain" || $W_SUPPORT_SEC == "email") {
                 $bEMailOK = false;
                 if ($TICKET_SOURCE_ID == $ar_ticket["SOURCE_ID"]) {
                     $ticket_email = strtolower(CMailUtil::ExtractMailAddress($ar_ticket["OWNER_SID"]));
                     if ($W_SUPPORT_SEC == "domain") {
                         $ticket_email = substr($ticket_email, strpos($ticket_email, "@"));
                     }
                     if (strpos($message_email_addr, $ticket_email) !== false) {
                         $bEMailOK = true;
                     }
                 }
                 if (!$bEMailOK && $ar_ticket["OWNER_USER_ID"] > 0) {
                     $db_user = CUser::GetByID($ar_ticket["OWNER_USER_ID"]);
                     if ($arUser = $db_user->Fetch()) {
                         $ticket_email = strtolower(CMailUtil::ExtractMailAddress($arUser["EMAIL"]));
                         if ($check_type == "domain") {
                             $ticket_email = substr($ticket_email, strpos($ticket_email, "@"));
                         }
                         if (strpos($message_email_addr, $ticket_email) !== false) {
                             $bEMailOK = true;
                         }
                     }
                 }
                 if (!$bEMailOK) {
                     $TID = 0;
                 }
             }
         } else {
             $TID = 0;
         }
     }
     //when message subject is empty - generate it from message body
     $title = trim($arMessageFields["SUBJECT"]);
     if (strlen($title) <= 0) {
         $title = trim($arMessageFields["BODY"]);
         $title = preg_replace("/[\n\r\t ]+/s" . BX_UTF_PCRE_MODIFIER, " ", $title);
         $title = substr($title, 0, 50);
     }
     $arFieldsTicket = array("CLOSE" => "N", "TITLE" => $title, "MESSAGE" => $arMessageFields["BODY"], "MESSAGE_AUTHOR_SID" => $message_email, "MESSAGE_SOURCE_SID" => "email", "MODIFIED_MODULE_NAME" => "mail", "EXTERNAL_ID" => $ID, "EXTERNAL_FIELD_1" => $arMessageFields["HEADER"]);
     if ($W_SUPPORT_USER_FIND == "Y") {
         $o = "LAST_LOGIN";
         $b = "DESC";
         $res = CUser::GetList($o, $b, array("ACTIVE" => "Y", "=EMAIL" => $message_email_addr));
         if (($arr = $res->Fetch()) && strtolower(CMailUtil::ExtractMailAddress($arr["EMAIL"])) == $message_email_addr) {
             $AUTHOR_USER_ID = $arr["ID"];
         }
     }
     // process attach files
     $arFILES = array();
     $rsAttach = CMailAttachment::GetList(array(), array("MESSAGE_ID" => $ID));
     while ($arAttach = $rsAttach->Fetch()) {
         // save from db to hdd
         $filename = CTempFile::GetFileName(md5(uniqid("")) . ".tmp");
         CheckDirPath($filename);
         if (file_put_contents($filename, $arAttach["FILE_DATA"]) !== false) {
             $arFILES[] = array("name" => $arAttach["FILE_NAME"], "type" => $arAttach["CONTENT_TYPE"], "size" => filesize($filename), "tmp_name" => $filename, "MODULE_ID" => "support");
         }
     }
     if (count($arFILES) > 0) {
         $arFieldsTicket["FILES"] = $arFILES;
     }
     $arFieldsTicket["CURRENT_USER_ID"] = null;
     if (intval($AUTHOR_USER_ID) > 0) {
         $resU = CUser::GetByID(intval($AUTHOR_USER_ID));
         if ($arU = $resU->Fetch()) {
             $arFieldsTicket["CURRENT_USER_ID"] = $arU["ID"];
         }
     }
     if ($TID > 0) {
         $arFieldsTicket["MESSAGE_AUTHOR_USER_ID"] = $AUTHOR_USER_ID;
         if ($W_SUPPORT_ADD_MESSAGE_AS_HIDDEN == "Y") {
             $arFieldsTicket["HIDDEN"] = "Y";
         }
         if ($arMessageFields["SPAM"] == "Y") {
             $arFieldsTicket["IS_SPAM"] = "Y";
         }
         $TID = CTicket::Set($arFieldsTicket, $MESSAGE_ID, $TID, "N");
     } else {
         $arFieldsTicket["SITE_ID"] = $SITE_ID;
         $arFieldsTicket["OWNER_USER_ID"] = $AUTHOR_USER_ID;
         $arFieldsTicket["OWNER_SID"] = $message_email;
         $arFieldsTicket["CREATED_MODULE_NAME"] = "mail";
         $arFieldsTicket["SOURCE_SID"] = "email";
         if ($arMessageFields["SPAM"] == "Y") {
             $arFieldsTicket["IS_SPAM"] = "Y";
         }
         if ($W_SUPPORT_CATEGORY > 0) {
             $arFieldsTicket["CATEGORY_ID"] = $W_SUPPORT_CATEGORY;
         }
         if ($W_SUPPORT_CRITICALITY > 0) {
             $arFieldsTicket["CRITICALITY_ID"] = $W_SUPPORT_CRITICALITY;
         }
         if (strlen(trim($arFieldsTicket["TITLE"])) <= 0) {
             $arFieldsTicket["TITLE"] = " ";
         }
         if (strlen(trim($arFieldsTicket["MESSAGE"])) <= 0) {
             $arFieldsTicket["MESSAGE"] = " ";
         }
         $TID = CTicket::Set($arFieldsTicket, $MESSAGE_ID, "", "N");
     }
 }
Esempio n. 6
0
	function ExtractAllMailAddresses($emails)
	{
		$result = array();
		$arEMails = explode(",", $emails);
		foreach($arEMails as $mail)
		{
			$result[] = CMailUtil::ExtractMailAddress($mail);
		}
		return $result;
	}
Esempio n. 7
0
 function SocnetEMailMessageAdd($arMessageFields, $ACTION_VARS)
 {
     if (!is_array($arMessageFields["FORUM_EMAIL_FILTER"])) {
         return false;
     }
     if (!CModule::IncludeModule("socialnetwork")) {
         return false;
     }
     $arParams = $arMessageFields["FORUM_EMAIL_FILTER"];
     if (!CSocNetFeatures::IsActiveFeature(SONET_ENTITY_GROUP, $arParams["SOCNET_GROUP_ID"], "forum")) {
         return false;
     }
     // Найдем кто отправитель
     $message_email = strlen($arMessageFields["FIELD_REPLY_TO"]) > 0 ? $arMessageFields["FIELD_REPLY_TO"] : $arMessageFields["FIELD_FROM"];
     $message_email_addr = strtolower(CMailUtil::ExtractMailAddress($message_email));
     $o = "LAST_LOGIN";
     $b = "DESC";
     $res = CUser::GetList($o, $b, array("ACTIVE" => "Y", "EMAIL" => $message_email_addr));
     if (($arUser = $res->Fetch()) && strtolower(CMailUtil::ExtractMailAddress($arUser["EMAIL"])) == $message_email_addr) {
         $AUTHOR_USER_ID = $arUser["ID"];
     } elseif ($arParams["NOT_MEMBER_POST"] == "Y") {
         $AUTHOR_USER_ID = false;
     } else {
         CMailLog::AddMessage(array("MAILBOX_ID" => $arMessageFields["MAILBOX_ID"], "MESSAGE_ID" => $arMessageFields["ID"], "FILTER_ID" => $arParams["MAIL_FILTER_ID"], "LOG_TYPE" => "FILTER_ERROR", "MESSAGE" => GetMessage("FORUM_MAIL_ERROR1") . ": " . $message_email_addr));
         return false;
     }
     if ($arParams["NOT_MEMBER_POST"] != "Y") {
         // Проверим права доступа
         if (CSocNetFeaturesPerms::CanPerformOperation($AUTHOR_USER_ID, SONET_ENTITY_GROUP, $arParams["SOCNET_GROUP_ID"], "forum", "full")) {
             $PERMISSION = "Y";
         } elseif (CSocNetFeaturesPerms::CanPerformOperation($AUTHOR_USER_ID, SONET_ENTITY_GROUP, $arParams["SOCNET_GROUP_ID"], "forum", "newtopic")) {
             $PERMISSION = "M";
         } elseif (CSocNetFeaturesPerms::CanPerformOperation($AUTHOR_USER_ID, SONET_ENTITY_GROUP, $arParams["SOCNET_GROUP_ID"], "forum", "answer")) {
             $PERMISSION = "I";
         } else {
             CMailLog::AddMessage(array("MAILBOX_ID" => $arMessageFields["MAILBOX_ID"], "MESSAGE_ID" => $arMessageFields["ID"], "FILTER_ID" => $arParams["MAIL_FILTER_ID"], "LOG_TYPE" => "FILTER_ERROR", "MESSAGE" => GetMessage("FORUM_MAIL_ERROR2") . " " . $arUser["LOGIN"] . " [" . $AUTHOR_USER_ID . "] (" . $message_email_addr . ")"));
             return false;
         }
     }
     $body = $arMessageFields["BODY"];
     //$body = preg_replace("/(\r\n)+/", "\r\n", $body);
     $p = strpos($body, "\r\nFrom:");
     if ($p > 0) {
         $body = substr($body, 0, $p) . "\r\n[CUT]" . substr($body, $p) . "[/CUT]";
     }
     $subject = $arMessageFields["SUBJECT"];
     // обрежем все RE и FW
     $subject = trim(preg_replace('#^\\s*((RE[0-9\\[\\]]*:\\s*)|(FW:\\s*))+(.*)$#i', '\\4', $subject));
     if ($subject == '') {
         $subject = GetMessage("FORUM_MAIL_EMPTY_TOPIC_TITLE") . " " . rand();
     }
     // Найдем какая тема
     $arFields = array();
     $FORUM_ID = IntVal($arParams["FORUM_ID"]);
     $SOCNET_GROUP_ID = IntVal($arParams["SOCNET_GROUP_ID"]);
     $TOPIC_ID = 0;
     global $DB;
     if ($arMessageFields["IN_REPLY_TO"] != '') {
         $dbTopic = $DB->Query("SELECT FT.ID FROM b_forum_topic FT INNER JOIN b_forum_message FM ON FM.TOPIC_ID=FT.ID WHERE FM.XML_ID='" . $DB->ForSQL($arMessageFields["IN_REPLY_TO"], 255) . "' AND FT.FORUM_ID=" . $FORUM_ID . " AND FT.SOCNET_GROUP_ID=" . $SOCNET_GROUP_ID);
         if ($arTopic = $dbTopic->Fetch()) {
             $TOPIC_ID = $arTopic["ID"];
         }
     }
     if ($arParams["USE_SUBJECT"] == "Y" && $TOPIC_ID <= 0) {
         $dbTopic = $DB->Query("SELECT ID FROM b_forum_topic WHERE TITLE='" . $DB->ForSQL($subject, 255) . "' AND FORUM_ID=" . $FORUM_ID . " AND SOCNET_GROUP_ID=" . $SOCNET_GROUP_ID);
         // ограничить по старости?
         if ($arTopic = $dbTopic->Fetch()) {
             $TOPIC_ID = $arTopic["ID"];
         }
     }
     if ($AUTHOR_USER_ID > 0) {
         if ($TOPIC_ID < 0 && $PERMISSION <= "I") {
             CMailLog::AddMessage(array("MAILBOX_ID" => $arMessageFields["MAILBOX_ID"], "MESSAGE_ID" => $arMessageFields["ID"], "FILTER_ID" => $arParams["MAIL_FILTER_ID"], "LOG_TYPE" => "FILTER_ERROR", "MESSAGE" => GetMessage("FORUM_MAIL_ERROR3") . " " . $arUser["LOGIN"] . " [" . $AUTHOR_USER_ID . "] (" . $message_email_addr . ")"));
             return false;
         }
         $bSHOW_NAME = true;
         $res = CForumUser::GetByUSER_ID($AUTHOR_USER_ID);
         if ($res) {
             $bSHOW_NAME = $res["SHOW_NAME"] == "Y";
         }
         if ($bSHOW_NAME) {
             $AUTHOR_NAME = $arUser["NAME"] . (strlen($arUser["NAME"]) <= 0 || strlen($arUser["LAST_NAME"]) <= 0 ? "" : " ") . $arUser["LAST_NAME"];
         }
         if (strlen(Trim($AUTHOR_NAME)) <= 0) {
             $AUTHOR_NAME = $arUser["LOGIN"];
         }
     } else {
         $AUTHOR_NAME = $arMessageFields["FIELD_FROM"];
         $arFields["AUTHOR_EMAIL"] = $arMessageFields["FIELD_FROM"];
     }
     $arFields["NEW_TOPIC"] = "N";
     if ($PERMISSION >= "Q") {
         $arFields["APPROVED"] = "Y";
     } else {
         $arFields["APPROVED"] = $arParams["MODERATION"] == "Y" ? "N" : "Y";
     }
     // Добавим новую тему
     if ($TOPIC_ID <= 0) {
         $arTopicFields = array("TITLE" => $subject, "FORUM_ID" => $FORUM_ID, "USER_START_ID" => $AUTHOR_USER_ID, "OWNER_ID" => $AUTHOR_USER_ID, "SOCNET_GROUP_ID" => $SOCNET_GROUP_ID);
         $arTopicFields["XML_ID"] = $arMessageFields["MSG_ID"];
         $arTopicFields["APPROVED"] = $arFields['APPROVED'];
         $arTopicFields["USER_START_NAME"] = $AUTHOR_NAME;
         $arTopicFields["LAST_POSTER_NAME"] = $AUTHOR_NAME;
         $TOPIC_ID = CForumTopic::Add($arTopicFields);
         if (IntVal($TOPIC_ID) <= 0) {
             CMailLog::AddMessage(array("MAILBOX_ID" => $arMessageFields["MAILBOX_ID"], "MESSAGE_ID" => $arMessageFields["ID"], "FILTER_ID" => $arParams["MAIL_FILTER_ID"], "LOG_TYPE" => "FILTER_ERROR", "MESSAGE" => GetMessage("FORUM_MAIL_ERROR4")));
             return false;
         }
         $arFields["NEW_TOPIC"] = "Y";
     }
     // Добавим сообщение
     $arFields["POST_MESSAGE"] = $body;
     // Аттаченные файлы
     $arFILES = array();
     $rsAttach = CMailAttachment::GetList(array(), array("MESSAGE_ID" => $arMessageFields["ID"]));
     while ($arAttach = $rsAttach->Fetch()) {
         $filename = CTempFile::GetFileName(md5(uniqid("")) . ".tmp");
         CheckDirPath($filename);
         if (file_put_contents($filename, $arAttach["FILE_DATA"]) !== false) {
             $arFile = array("name" => $arAttach["FILE_NAME"], "type" => $arAttach["CONTENT_TYPE"], "size" => @filesize($filename), "tmp_name" => $filename, "MODULE_ID" => "forum");
             $arFilter = array("FORUM_ID" => $FORUM_ID);
             $arFiles = array($arFile);
             if (CForumFiles::CheckFields($arFiles, $arFilter)) {
                 $arFILES[] = $arFiles[0];
             } else {
                 $oError = $GLOBALS["APPLICATION"]->GetException();
                 CMailLog::AddMessage(array("MAILBOX_ID" => $arMessageFields["MAILBOX_ID"], "MESSAGE_ID" => $arMessageFields["ID"], "FILTER_ID" => $arParams["MAIL_FILTER_ID"], "LOG_TYPE" => "FILTER_ERROR", "MESSAGE" => GetMessage("FORUM_MAIL_ERROR6") . " (" . $arAttach["FILE_NAME"] . "): " . ($oError && $oError->GetString() ? $oError->GetString() : "")));
             }
         }
     }
     if (count($arFILES) > 0) {
         $arFields["FILES"] = $arFILES;
     }
     $arFields["AUTHOR_NAME"] = $AUTHOR_NAME;
     $arFields["AUTHOR_ID"] = $AUTHOR_USER_ID;
     $arFields["FORUM_ID"] = $FORUM_ID;
     $arFields["TOPIC_ID"] = $TOPIC_ID;
     $arFields["XML_ID"] = $arMessageFields["MSG_ID"];
     $arFields["SOURCE_ID"] = "EMAIL";
     $arRes = array();
     if (!empty($arMessageFields["FIELD_FROM"])) {
         $arRes[] = "From: " . $arMessageFields["FIELD_FROM"];
     }
     if (!empty($arMessageFields["FIELD_TO"])) {
         $arRes[] = "To: " . $arMessageFields["FIELD_TO"];
     }
     if (!empty($arMessageFields["FIELD_CC"])) {
         $arRes[] = "Cc: " . $arMessageFields["FIELD_CC"];
     }
     if (!empty($arMessageFields["FIELD_BCC"])) {
         $arRes[] = "Bcc: " . $arMessageFields["FIELD_BCC"];
     }
     $arRes[] = "Subject: " . $arMessageFields["SUBJECT"];
     $arRes[] = "Date: " . $arMessageFields["FIELD_DATE"];
     $arFields["MAIL_HEADER"] = implode("\r\n", $arRes);
     preg_match_all('#Received:\\s+from\\s+(.*)by.*#i', $arMessageFields["HEADER"], $regs);
     if (is_array($regs) && is_array($regs[1])) {
         $arFields["AUTHOR_IP"] = $arFields["AUTHOR_REAL_IP"] = '<email: ' . $regs[1][count($regs[1]) - 1] . '>';
     } else {
         $arFields["AUTHOR_IP"] = $arFields["AUTHOR_REAL_IP"] = '<email: no address>';
     }
     /*
     
     $AUTHOR_IP = ForumGetRealIP();
     $AUTHOR_IP_tmp = $AUTHOR_IP;
     $AUTHOR_REAL_IP = $_SERVER['REMOTE_ADDR'];
     if (COption::GetOptionString("forum", "FORUM_GETHOSTBYADDR", "N") == "Y")
     {
     	$AUTHOR_IP = @gethostbyaddr($AUTHOR_IP);
     
     	if ($AUTHOR_IP_tmp==$AUTHOR_REAL_IP)
     		$AUTHOR_REAL_IP = $AUTHOR_IP;
     	else
     		$AUTHOR_REAL_IP = @gethostbyaddr($AUTHOR_REAL_IP);
     }
     
     $arFields["AUTHOR_IP"] = ($AUTHOR_IP!==False) ? $AUTHOR_IP : "<no address>";
     $arFields["AUTHOR_REAL_IP"] = ($AUTHOR_REAL_IP!==False) ? $AUTHOR_REAL_IP : "<no address>";
     */
     $strErrorMessage = '';
     $MESSAGE_ID = CForumMessage::Add($arFields, false);
     if (intVal($MESSAGE_ID) <= 0) {
         $str = $GLOBALS['APPLICATION']->GetException();
         if ($str && $str->GetString()) {
             $strErrorMessage .= "[" . $str->GetString() . "]";
         }
         if ($arFields["NEW_TOPIC"] == 'Y') {
             CForumTopic::Delete($TOPIC_ID);
         }
         CMailLog::AddMessage(array("MAILBOX_ID" => $arMessageFields["MAILBOX_ID"], "MESSAGE_ID" => $arMessageFields["ID"], "FILTER_ID" => $arParams["MAIL_FILTER_ID"], "LOG_TYPE" => "FILTER_ERROR", "MESSAGE" => GetMessage("FORUM_MAIL_ERROR5") . " " . $strErrorMessage));
     }
     if ($MESSAGE_ID > 0) {
         CMailLog::AddMessage(array("MAILBOX_ID" => $arMessageFields["MAILBOX_ID"], "MESSAGE_ID" => $arMessageFields["ID"], "FILTER_ID" => $arParams["MAIL_FILTER_ID"], "LOG_TYPE" => "FILTER_COMPLETE", "MESSAGE" => GetMessage("FORUM_MAIL_OK") . " " . $MESSAGE_ID . " (TID#" . $TOPIC_ID . ")"));
         CForumMessage::SendMailMessage($MESSAGE_ID, array(), false, "NEW_FORUM_MESSAGE");
         $dbSite = CSite::GetById($arMessageFields["LID"]);
         if ($arSite = $dbSite->Fetch()) {
             $lang = $arSite['LANGUAGE_ID'];
         } else {
             $lang = $LANGUAGE_ID;
         }
         $parser = new forumTextParser();
         $arForum = CForumNew::GetByID($FORUM_ID);
         $arAllow = array("HTML" => "N", "ANCHOR" => "N", "BIU" => "N", "IMG" => "N", "LIST" => "N", "QUOTE" => "N", "CODE" => "N", "FONT" => "N", "SMILES" => "N", "UPLOAD" => $arForum["ALLOW_UPLOAD"], "NL2BR" => "N", "TABLE" => "N", "ALIGN" => "N");
         if ($arFields["NEW_TOPIC"] == "Y") {
             $arFieldsForSocnet = array("ENTITY_TYPE" => SONET_ENTITY_GROUP, "ENTITY_ID" => $SOCNET_GROUP_ID, "EVENT_ID" => "forum", "=LOG_DATE" => $GLOBALS["DB"]->CurrentTimeFunction(), "TITLE_TEMPLATE" => str_replace("#AUTHOR_NAME#", $AUTHOR_NAME, CForumEmail::GetLangMessage("FORUM_MAIL_SOCNET_TITLE_TOPIC", $lang)), "TITLE" => $subject, "MESSAGE" => $parser->convert($body, $arAllow), "TEXT_MESSAGE" => $parser->convert4mail($body), "URL" => CComponentEngine::MakePathFromTemplate($arParams["URL_TEMPLATES_MESSAGE"], array("UID" => $AUTHOR_USER_ID, "FID" => $FORUM_ID, "TID" => $TOPIC_ID, "MID" => $MESSAGE_ID)), "PARAMS" => serialize(array("PATH_TO_MESSAGE" => CComponentEngine::MakePathFromTemplate($arParams["URL_TEMPLATES_MESSAGE"], array("TID" => $TOPIC_ID)))), "MODULE_ID" => false, "CALLBACK_FUNC" => false, "SOURCE_ID" => $MESSAGE_ID, "RATING_TYPE_ID" => "FORUM_TOPIC", "RATING_ENTITY_ID" => intval($TOPIC_ID));
             if (intVal($AUTHOR_USER_ID) > 0) {
                 $arFieldsForSocnet["USER_ID"] = $AUTHOR_USER_ID;
             }
             $logID = CSocNetLog::Add($arFieldsForSocnet, false);
             if (intval($logID) > 0) {
                 CSocNetLog::Update($logID, array("TMP_ID" => $logID));
                 CSocNetLogRights::SetForSonet($logID, $arFieldsForSocnet["ENTITY_TYPE"], $arFieldsForSocnet["ENTITY_ID"], "forum", "view", true);
                 CSocNetLog::SendEvent($logID, "SONET_NEW_EVENT", $logID);
             }
         } else {
             $dbForumMessage = CForumMessage::GetList(array("ID" => "ASC"), array("TOPIC_ID" => $TOPIC_ID));
             if ($arForumMessage = $dbForumMessage->Fetch()) {
                 $dbRes = CSocNetLog::GetList(array("ID" => "DESC"), array("EVENT_ID" => "forum", "SOURCE_ID" => $arForumMessage["ID"]), false, false, array("ID", "TMP_ID"));
                 if ($arRes = $dbRes->Fetch()) {
                     $log_id = $arRes["TMP_ID"];
                 } else {
                     $dbFirstMessage = CForumMessage::GetList(array("ID" => "ASC"), array("TOPIC_ID" => $arForumMessage["TOPIC_ID"]), false, 1);
                     if ($arFirstMessage = $dbFirstMessage->Fetch()) {
                         $arTopic = CForumTopic::GetByID($arFirstMessage["TOPIC_ID"]);
                         $sFirstMessageText = COption::GetOptionString("forum", "FILTER", "Y") == "Y" ? $arFirstMessage["POST_MESSAGE_FILTER"] : $arFirstMessage["POST_MESSAGE"];
                         $sFirstMessageURL = CComponentEngine::MakePathFromTemplate($arParams["URL_TEMPLATES_MESSAGE"], array("UID" => $arFirstMessage["AUTHOR_ID"], "FID" => $arFirstMessage["FORUM_ID"], "TID" => $arFirstMessage["TOPIC_ID"], "MID" => $arFirstMessage["ID"]));
                         $arFieldsForSocnet = array("ENTITY_TYPE" => SONET_ENTITY_GROUP, "ENTITY_ID" => $SOCNET_GROUP_ID, "EVENT_ID" => "forum", "LOG_DATE" => $arFirstMessage["POST_DATE"], "LOG_UPDATE" => $arFirstMessage["POST_DATE"], "TITLE_TEMPLATE" => str_replace("#AUTHOR_NAME#", $arFirstMessage["AUTHOR_NAME"], GetMessage("SONET_FORUM_LOG_TOPIC_TEMPLATE")), "TITLE" => $arTopic["TITLE"], "MESSAGE" => $parser->convert($sFirstMessageText, $arAllow), "TEXT_MESSAGE" => $parser->convert4mail($sFirstMessageText), "URL" => $sFirstMessageURL, "PARAMS" => serialize(array("PATH_TO_MESSAGE" => CComponentEngine::MakePathFromTemplate($arParams["URL_TEMPLATES_MESSAGE"], array("TID" => $arFirstMessage["TOPIC_ID"])))), "MODULE_ID" => false, "CALLBACK_FUNC" => false, "SOURCE_ID" => $arFirstMessage["ID"], "RATING_TYPE_ID" => "FORUM_TOPIC", "RATING_ENTITY_ID" => intval($arFirstMessage["TOPIC_ID"]));
                         if (intVal($arFirstMessage["AUTHOR_ID"]) > 0) {
                             $arFieldsForSocnet["USER_ID"] = $arFirstMessage["AUTHOR_ID"];
                         }
                         $log_id = CSocNetLog::Add($arFieldsForSocnet, false);
                         if (intval($log_id) > 0) {
                             CSocNetLog::Update($log_id, array("TMP_ID" => $log_id));
                             CSocNetLogRights::SetForSonet($log_id, $arFieldsForSocnet["ENTITY_TYPE"], $arFieldsForSocnet["ENTITY_ID"], "forum", "view", true);
                         }
                     }
                 }
                 if (intval($log_id) > 0) {
                     $arFieldsForSocnet = array("ENTITY_TYPE" => SONET_ENTITY_GROUP, "ENTITY_ID" => $SOCNET_GROUP_ID, "EVENT_ID" => "forum", "LOG_ID" => $log_id, "=LOG_DATE" => $GLOBALS["DB"]->CurrentTimeFunction(), "MESSAGE" => $parser->convert($body, $arAllow), "TEXT_MESSAGE" => $parser->convert4mail($body), "URL" => CComponentEngine::MakePathFromTemplate($arParams["URL_TEMPLATES_MESSAGE"], array("UID" => $AUTHOR_USER_ID, "FID" => $FORUM_ID, "TID" => $TOPIC_ID, "MID" => $MESSAGE_ID)), "MODULE_ID" => false, "SOURCE_ID" => $MESSAGE_ID, "RATING_TYPE_ID" => "FORUM_POST", "RATING_ENTITY_ID" => intval($MESSAGE_ID));
                     if (intVal($AUTHOR_USER_ID) > 0) {
                         $arFieldsForSocnet["USER_ID"] = $AUTHOR_USER_ID;
                     }
                     CSocNetLogComments::Add($arFieldsForSocnet);
                 }
             }
         }
     }
 }
Esempio n. 8
0
 function AddAttachment($arFields)
 {
     global $DB;
     $strSql = "SELECT ATTACHMENTS FROM b_mail_message WHERE ID=" . IntVal($arFields["MESSAGE_ID"]);
     $dbr = $DB->Query($strSql, false, "File: " . __FILE__ . "<br>Line: " . __LINE__);
     if (!($dbr_arr = $dbr->Fetch())) {
         return false;
     }
     $n = IntVal($dbr_arr["ATTACHMENTS"]) + 1;
     if (strlen($arFields["FILE_NAME"]) <= 0) {
         $arFields["FILE_NAME"] = $n . ".";
         if (strpos($arFields["CONTENT_TYPE"], "message/") === 0) {
             $arFields["FILE_NAME"] .= "msg";
         } else {
             $arFields["FILE_NAME"] .= "tmp";
         }
     }
     if (is_set($arFields, "CONTENT_TYPE")) {
         $arFields["CONTENT_TYPE"] = strtolower($arFields["CONTENT_TYPE"]);
     }
     if (strpos($arFields["CONTENT_TYPE"], "image/") === 0 && (!is_set($arFields, "IMAGE_WIDTH") || !is_set($arFields, "IMAGE_HEIGHT")) && is_set($arFields, "FILE_DATA")) {
         $filename = CTempFile::GetFileName(md5(uniqid("")) . '.tmp');
         CheckDirPath($filename);
         if (file_put_contents($filename, $arFields["FILE_DATA"]) !== false) {
             $img_arr = CFile::GetImageSize($filename);
             $arFields["IMAGE_WIDTH"] = $img_arr ? $img_arr[0] : 0;
             $arFields["IMAGE_HEIGHT"] = $img_arr ? $img_arr[1] : 0;
         }
     }
     if (is_set($arFields, "FILE_DATA") && !is_set($arFields, "FILE_SIZE")) {
         $arFields["FILE_SIZE"] = CUtil::BinStrlen($arFields["FILE_DATA"]);
     }
     if (!CMailUtil::IsSizeAllowed(strlen($DB->ForSQL($arFields["FILE_DATA"])) + 100)) {
         return false;
     }
     $ID = $DB->Add("b_mail_msg_attachment", $arFields, array("FILE_DATA"));
     if ($ID > 0) {
         $strSql = "UPDATE b_mail_message SET ATTACHMENTS=" . $n . " WHERE ID=" . IntVal($arFields["MESSAGE_ID"]);
         $DB->Query($strSql, false, "File: " . __FILE__ . "<br>Line: " . __LINE__);
     }
     return $ID;
     /*
     $arFile = Array(
     		"name"=>$filename,
     		"size"=>strlen($part["BODY"]),
     		"type"=>$part["CONTENT-TYPE"],
     		"content"=>$part["BODY"],
     		"MODULE_ID"=>"mail"
     	);
     $file_id = CFile::SaveFile($arFile, "mail");
     */
 }
Esempio n. 9
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']);
     if ($addresserID > 0 && Bitrix\Crm\Integration\IntranetManager::isExternalUser($addresserID)) {
         //Forget about extranet user
         $addresserID = 0;
     }
     $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 = $subject !== '' ? $subject : 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/>', htmlspecialcharsbx($body));
         }
         if ($comment === '') {
             $comment = htmlspecialcharsbx($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_DESCRIPTION' => GetMessage('CRM_MAIL_LEAD_FROM_EMAIL_SOURCE', array('%SENDER%' => $addresserInfo['ORIGINAL'])), 'OPENED' => 'Y', 'FM' => array('EMAIL' => array()));
         $sourceList = CCrmStatus::GetStatusList('SOURCE');
         $sourceID = COption::GetOptionString('crm', 'email_lead_source_id', '');
         if ($sourceID === '' || !isset($sourceList[$sourceID])) {
             if (isset($sourceList['EMAIL'])) {
                 $sourceID = 'EMAIL';
             } elseif (isset($sourceList['OTHER'])) {
                 $sourceID = 'OTHER';
             }
         }
         if ($sourceID !== '') {
             $arLeadFields['SOURCE_ID'] = $sourceID;
         }
         $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') {
                     if ($arAttachment['FILE_ID']) {
                         $arAttachment['FILE_DATA'] = CMailAttachment::getContents($arAttachment);
                     }
                     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') {
             if ($arAttachment['FILE_ID']) {
                 $arAttachment['FILE_DATA'] = CMailAttachment::getContents($arAttachment);
             }
             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;
         }
         if ($arAttachment['FILE_ID'] && empty($arAttachment['FILE_DATA'])) {
             $arAttachment['FILE_DATA'] = CMailAttachment::getContents($arAttachment);
         }
         $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);
     $encodedBody = htmlspecialcharsbx($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 .= $encodedBody;
     $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 ($elementID > 0) {
                 $arElementIDs[] = (int) $elementID;
             }
         }
     }
     $descr = preg_replace("/(\r\n|\n|\r)+/", '<br/>', $encodedBody);
     $now = ConvertTimeStamp(time() + CTimeZone::GetOffset(), 'FULL', $siteID);
     $direction = CCrmActivityDirection::Incoming;
     $completed = 'N';
     // Incomming emails must be marked as 'Not Completed'.
     if ($addresserID > 0 && ActivitySettings::getValue(ActivitySettings::MARK_FORWARDED_EMAIL_AS_OUTGOING)) {
         $direction = CCrmActivityDirection::Outgoing;
         $completed = 'Y';
     }
     $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' => $completed, 'AUTHOR_ID' => $userID, 'RESPONSIBLE_ID' => $userID, 'PRIORITY' => CCrmActivityPriority::Medium, 'DESCRIPTION' => $descr, 'DESCRIPTION_TYPE' => CCrmContentType::Html, 'DIRECTION' => $direction, '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 && $direction === CCrmActivityDirection::Incoming) {
         CCrmActivity::Notify($arActivityFields, CCrmNotifierSchemeType::IncomingEmail);
     }
     // <-- Creating new activity
     return true;
 }
Esempio n. 10
0
 private static function executeChangePassword(&$error)
 {
     global $USER;
     $error = false;
     $password = $_REQUEST['password'];
     $password2 = $_REQUEST['password2'];
     if (!check_bitrix_sessid()) {
         $error = GetMessage('INTR_MAIL_CSRF');
     }
     if ($error === false) {
         $mailbox = CIntranetMailSetupHelper::getUserMailbox($USER->GetID());
         if (empty($mailbox) || !in_array($mailbox['SERVER_TYPE'], array('controller', 'domain', 'crdomain', 'imap'))) {
             $error = GetMessage('INTR_MAIL_FORM_ERROR');
         }
     }
     if ($error === false) {
         if ($mailbox['ID'] != $_REQUEST['ID']) {
             $error = GetMessage('INTR_MAIL_FORM_ERROR');
         }
     }
     if ($error === false) {
         if (in_array($mailbox['SERVER_TYPE'], array('controller', 'domain', 'crdomain')) && $password != $password2) {
             $error = GetMessage('INTR_MAIL_INP_PASSWORD2_BAD');
         }
     }
     if ($error === false) {
         if ($mailbox['SERVER_TYPE'] == 'crdomain') {
             list($login, $domain) = explode('@', $mailbox['LOGIN'], 2);
             $crResponse = CControllerClient::ExecuteEvent('OnMailControllerChangeMemberPassword', array('DOMAIN' => $domain, 'NAME' => $login, 'PASSWORD' => $password));
             if (!isset($crResponse['result'])) {
                 $error = empty($crResponse['error']) ? GetMessage('INTR_MAIL_CONTROLLER_INVALID') : CMail::getErrorMessage($crResponse['error']);
             }
         } else {
             if ($mailbox['SERVER_TYPE'] == 'domain') {
                 $domainService = CIntranetMailSetupHelper::getDomainService($mailbox['SERVICE_ID']);
                 list($login, $domain) = explode('@', $mailbox['LOGIN'], 2);
                 $result = CMailDomain2::changePassword($domainService['token'], $domain, $login, $password, $error);
                 if (is_null($result)) {
                     $error = CMail::getErrorMessage($error);
                 }
             } else {
                 if ($mailbox['SERVER_TYPE'] == 'controller') {
                     list($login, $domain) = explode('@', $mailbox['LOGIN'], 2);
                     $crResponse = CControllerClient::ExecuteEvent('OnMailControllerChangePassword', array('DOMAIN' => $domain, 'NAME' => $login, 'PASSWORD' => $password));
                     if (!isset($crResponse['result'])) {
                         $error = empty($crResponse['error']) ? GetMessage('INTR_MAIL_CONTROLLER_INVALID') : CMail::getErrorMessage($crResponse['error']);
                     }
                 } else {
                     if ($mailbox['SERVER_TYPE'] == 'imap') {
                         $unseen = CMailUtil::CheckImapMailbox($mailbox['SERVER'], $mailbox['PORT'], $mailbox['USE_TLS'], $mailbox['LOGIN'], $password, $error, 30);
                         if ($error === false) {
                             $res = CMailbox::update($mailbox['ID'], array('PASSWORD' => $password));
                             if (!$res) {
                                 $error = GetMessage('INTR_MAIL_SAVE_ERROR');
                             }
                         }
                     }
                 }
             }
         }
     }
     return array('result' => $error === false ? 'ok' : 'error', 'error' => CharsetConverter::ConvertCharset($error, SITE_CHARSET, 'UTF-8'));
 }