Esempio n. 1
0
 /**
  * @param string $message The message to be shown in trace. If set to false, the default message for this class of exception will be used.
  * @param mixed[] $data An array of special data. Could be:
  * 		<li>AUX MESSAGE string|mixed[] String to be attached to the end of the message in round brackets
  * 		<li>AUX ERROR mixed[] An array structure to be dumped with AddMessage2Log(), accompanied with unique-exception-id to be able to establish matching
  * 		<li>ERROR \Bitrix\Tasks\Util\Error\Collection|string[] A collection or string array of high-level errors to show to user
  * @param mixed[] $additional Some additional things, usually unused
  */
 public function __construct($message = false, array $data = array(), array $additional = array())
 {
     if (!empty($data)) {
         $this->data = $data;
     }
     if (!empty($additional)) {
         $this->additional = $additional;
     }
     if ($message === false) {
         $message = $this->getDefaultMessage();
     }
     $this->messageOrigin = $message;
     if (!isset($additional['FILE'])) {
         $additional['FILE'] = '';
     }
     $additional['LINE'] = intval($additional['LINE']);
     $additional['CODE'] = intval($additional['CODE']);
     if (!isset($additional['PREVIOUS_EXCEPTION'])) {
         $additional['PREVIOUS_EXCEPTION'] = null;
     }
     $doDump = $this->dumpAuxError();
     if ($doDump) {
         $exceptionId = uniqid('', true);
         if (isset($this->data['AUX']['ERROR'])) {
             if (!is_array($this->data['AUX']['ERROR'])) {
                 $this->data['AUX']['ERROR'] = array((string) $this->data['AUX']['ERROR']);
             }
             AddMessage2Log('Exception additional data: ' . $exceptionId . ': ' . serialize($this->data['AUX']['ERROR']), 'tasks');
         }
     }
     parent::__construct(($doDump ? $exceptionId . ': ' : '') . $this->prepareMessage($message), $additional['CODE'], $additional['FILE'], $additional['LINE'], $additional['PREVIOUS_EXCEPTION']);
 }
Esempio n. 2
0
function logArray()
{
	$arArgs = func_get_args();
	$strResult = '';
	foreach ($arArgs as $arArg) {
		$strResult .= "\n\n" . print_r($arArg, true);
	}
	if (!defined('LOG_FILENAME')) {
		define('LOG_FILENAME', $_SERVER['DOCUMENT_ROOT'] . '/bitrix/log.txt');
	}
	AddMessage2Log($strResult, 'logArray -> ');
}
Esempio n. 3
0
 public static function Query($strSql, $error_position)
 {
     global $SECURITY_SESSION_DBH;
     if (!is_resource($SECURITY_SESSION_DBH)) {
         CSecurityDB::Init(true);
     }
     if (is_resource($SECURITY_SESSION_DBH)) {
         $strSql = preg_replace("/^\\s*SELECT\\s+(?!GET_LOCK|RELEASE_LOCK)/i", "SELECT SQL_NO_CACHE ", $strSql);
         $result = @mysql_query($strSql, $SECURITY_SESSION_DBH);
         if ($result) {
             return $result;
         } else {
             $db_Error = mysql_error();
             AddMessage2Log($error_position . " MySql Query Error: " . $strSql . " [" . $db_Error . "]", "security");
         }
     }
     return false;
 }
Esempio n. 4
0
function OnBeforeUserUpdateHandler(&$arFields)
{
    if (isset($arFields['UF_GROUPS']) && in_array(1, $arFields['UF_GROUPS'])) {
        $user = CUser::GetByID($arFields['ID'])->Fetch();
        if (!in_array(1, $user['UF_GROUPS'])) {
            AddMessage2Log('update users');
            CModule::IncludeModule("iblock");
            CIBlockElement::SetPropertyValues(1, 4, getKentLabUsers(), "USERS");
            $groups = CUser::GetUserGroup($user['UF_USER_PARENT']);
            $fields = array_flip(getValuesList('UF_STATUS', 'USER', 'ID'));
            if (intval($user['UF_USER_PARENT']) > 0 && $fields[$user['UF_STATUS']] == 4) {
                if (in_array(8, $groups)) {
                    changeUserStatus($user['ID'], $user['UF_USER_PARENT'], $user['UF_STATUS'], 6, "Регистрация в KENT Lab");
                }
            }
        }
    }
}
 /**
  * Called before record transformed for log writing.
  *
  * @param array &$record Database record.
  *
  * @return void
  */
 public function beforeLogFormat(array &$record)
 {
     global $USER;
     if ($record["PARAM_NAME"] !== "FILE_ID" || $record["PARAM_VALUE"] <= 0) {
         return;
     }
     if (!\Bitrix\Main\Loader::includeModule('disk')) {
         AddMessage2Log('MessageParamHandler::beforeLogFormat: failed to load disk module.');
         return;
     }
     if (!is_object($USER) || $USER->GetID() < 0) {
         AddMessage2Log('MessageParamHandler::beforeLogFormat: no user provided.');
         return;
     }
     /** @var \Bitrix\Disk\File $file */
     $fileId = $record["PARAM_VALUE"];
     $userId = $USER->GetID();
     $file = \Bitrix\Disk\File::loadById($fileId);
     if (!$file) {
         AddMessage2Log('MessageParamHandler::beforeLogFormat: file (' . $fileId . ') not found for user (' . $userId . ').');
         return;
     }
     $externalLink = $file->addExternalLink(array('CREATED_BY' => $userId, 'TYPE' => \Bitrix\Disk\Internals\ExternalLinkTable::TYPE_MANUAL));
     if (!$externalLink) {
         AddMessage2Log('MessageParamHandler::beforeLogFormat: failed to get external link for file (' . $fileId . ').');
         AddMessage2Log($file->getErrors());
         return;
     }
     $url = \Bitrix\Disk\Driver::getInstance()->getUrlManager()->getUrlExternalLink(array('hash' => $externalLink->getHash(), 'action' => 'default'), true);
     $fileName = $file->getName();
     $fileSize = $file->getSize();
     $attach = new \CIMMessageParamAttach(null, \CIMMessageParamAttach::CHAT);
     $attach->AddFiles(array(array("NAME" => $fileName, "LINK" => $url, "SIZE" => $fileSize)));
     $record["PARAM_NAME"] = 'ATTACH';
     $record["PARAM_VALUE"] = 1;
     $record["PARAM_JSON"] = $attach->GetJSON();
 }
Esempio n. 6
0
 public function call($methodName, $additionalParams = null)
 {
     global $APPLICATION;
     if (!$this->access_token) {
         $interface = Service::getEngine()->getInterface();
         if (!$interface->checkAccessToken()) {
             if ($interface->getNewAccessToken()) {
                 Service::getEngine()->setAuthSettings($interface->getResult());
             } else {
                 return $interface->getResult();
             }
         }
         $this->access_token = $interface->getToken();
     }
     if ($this->access_token) {
         if (!is_array($additionalParams)) {
             $additionalParams = array();
         } else {
             $additionalParams = $APPLICATION->ConvertCharsetArray($additionalParams, LANG_CHARSET, "utf-8");
         }
         $additionalParams['auth'] = $this->access_token;
         $http = new HttpClient(array('socketTimeout' => $this->httpTimeout));
         $result = $http->post(CBitrixSeoOAuthInterface::URL . self::SERVICE_URL . $methodName, $additionalParams);
         /*			AddMessage2Log(array(
         				CBitrixSeoOAuthInterface::URL.self::SERVICE_URL.$methodName,
         				$additionalParams,
         				$http->getStatus(),
         				$result,
         			));*/
         $res = $this->prepareAnswer($result);
         if (!$res) {
             AddMessage2Log('Strange answer from Seo! ' . $http->getStatus() . ' ' . $result);
         }
         return $res;
     } else {
         throw new SystemException("No access token");
     }
 }
Esempio n. 7
0
$arDefaultUrlTemplates404 = array("sections" => "", "section" => "#SECTION_ID#/", "element" => "#SECTION_ID#/#ELEMENT_ID#/", "compare" => "compare.php?action=COMPARE", "smart_filter" => $smartBase . "filter/#SMART_FILTER_PATH#/apply/");
$arDefaultVariableAliases404 = array();
$arDefaultVariableAliases = array();
$arComponentVariables = array("SECTION_ID", "SECTION_CODE", "ELEMENT_ID", "ELEMENT_CODE", "action");
if ($arParams["SEF_MODE"] == "Y") {
    $arVariables = array();
    $engine = new CComponentEngine($this);
    if (\Bitrix\Main\Loader::includeModule('iblock')) {
        $engine->addGreedyPart("#SECTION_CODE_PATH#");
        $engine->addGreedyPart("#SMART_FILTER_PATH#");
        $engine->setResolveCallback(array("CIBlockFindTools", "resolveComponentEngine"));
    }
    $arUrlTemplates = CComponentEngine::MakeComponentUrlTemplates($arDefaultUrlTemplates404, $arParams["SEF_URL_TEMPLATES"]);
    $arVariableAliases = CComponentEngine::MakeComponentVariableAliases($arDefaultVariableAliases404, $arParams["VARIABLE_ALIASES"]);
    $componentPage = $engine->guessComponentPath($arParams["SEF_FOLDER"], $arUrlTemplates, $arVariables);
    AddMessage2Log($componentPage);
    if ($componentPage === "smart_filter") {
        $componentPage = "section";
    }
    if (!$componentPage && isset($_REQUEST["q"])) {
        $componentPage = "search";
    }
    $b404 = false;
    if (!$componentPage) {
        $componentPage = "sections";
        $b404 = true;
    }
    if ($componentPage == "section") {
        if (isset($arVariables["SECTION_ID"])) {
            $b404 |= intval($arVariables["SECTION_ID"]) . "" !== $arVariables["SECTION_ID"];
        } else {
Esempio n. 8
0
 public function moderateBanners($campaignId, array $bannerIDs)
 {
     if (empty($campaignId)) {
         throw new ArgumentNullException("campaignId");
     }
     $queryData = array('CampaignID' => $campaignId, 'BannerIDS' => $bannerIDs);
     $result = $this->getProxy()->getInterface()->moderateBanners(static::ENGINE_ID, $queryData);
     AddMessage2Log($result);
     if (!empty($result['error'])) {
         throw new YandexDirectException($result);
     }
     return $result;
 }
Esempio n. 9
0
	function prepareFilter($arFilter, $inSelect = false)
	{
		$arWhere = array();
		if (!is_array($arFilter))
			$arFilter = array();

		$orLogic = false;
		if (array_key_exists("LOGIC", $arFilter))
		{
			$orLogic = ($arFilter["LOGIC"] == "OR");
			unset($arFilter["LOGIC"]);
		}

		foreach($arFilter as $field=>$val)
		{
			$field = strtoupper($field);
			if(
				is_array($val)
				&& count($val) == 1
				&& $field !== "URL"
				&& $field !== "PARAMS"
				&& !is_numeric($field)
			)
				$val = $val[0];

			switch($field)
			{
			case "ITEM_ID":
			case "=ITEM_ID":
				$arWhere = array_merge($arWhere, $this->filterField("item_id", $val, $inSelect));
				break;
			case "!ITEM_ID":
				if($val !== false)
					$arWhere[] = "item_id <> ".sprintf("%u", crc32($val));
				break;
			case "MODULE_ID":
			case "=MODULE_ID":
				if($val !== false && $val !== "no")
					$arWhere[] = "module_id = ".sprintf("%u", crc32($val));
				break;
			case "PARAM1":
			case "=PARAM1":
				$arWhere = array_merge($arWhere, $this->filterField("param1_id", $val, $inSelect));
				break;
			case "!PARAM1":
			case "!=PARAM1":
				if($val !== false)
					$arWhere[] = "param1_id <> ".sprintf("%u", crc32($val));
				break;
			case "PARAM2":
			case "=PARAM2":
				$arWhere = array_merge($arWhere, $this->filterField("param2_id", $val, $inSelect));
				break;
			case "!PARAM2":
			case "!=PARAM2":
				if($val !== false)
					$arWhere[] = "param2_id <> ".sprintf("%u", crc32($val));
				break;
			case "DATE_CHANGE":
				if(strlen($val) > 0)
					$arWhere[] = "date_change >= ".intval(MakeTimeStamp($val)-CTimeZone::GetOffset());
				break;
			case "<=DATE_CHANGE":
				if(strlen($val) > 0)
					$arWhere[] = "date_change <= ".intval(MakeTimeStamp($val)-CTimeZone::GetOffset());
				break;
			case ">=DATE_CHANGE":
				if(strlen($val) > 0)
					$arWhere[] = "date_change >= ".intval(MakeTimeStamp($val)-CTimeZone::GetOffset());
				break;
			case "SITE_ID":
				if($val !== false)
				{
					if ($inSelect)
						$arWhere[] = "in(site, ".sprintf("%u", crc32($val)).")";
					else
						$arWhere[] = "site = ".sprintf("%u", crc32($val));
				}
				break;
			case "CHECK_DATES":
				if($val == "Y")
				{
					$ts = time()-CTimeZone::GetOffset();
					if ($inSelect)
					{
						$arWhere[] = "if(date_from, date_from, ".$ts.") <= ".$ts;
						$arWhere[] = "if(date_to, date_to, ".$ts.") >= ".$ts;
					}
					else
					{
						$arWhere[] = "date_from_nvl <= ".$ts;
						$arWhere[] = "date_to_nvl >= ".$ts;
					}
				}
				break;
			case "TAGS":
				$arTags = explode(",", $val);
				foreach($arTags as $i => &$strTag)
				{
					$strTag = trim($strTag, " \n\r\t\"");
					if ($strTag == "")
						unset($arTags[$i]);
				}
				unset($strTag);

				$arWhere = array_merge($arWhere, $this->filterField("tags", $arTags, $inSelect));
				break;
			case "PARAMS":
				if (is_array($val))
				{
					$params = $this->params($val);
					if ($params != "")
					{
						if ($inSelect)
						{
							$arWhere[] = "in(param, ".$params.")";
						}
						else
						{
							foreach(explode(",", $params) as $param)
								$arWhere[] = "param = ".$param;
						}
					}
				}
				break;
			case "URL": //TODO
			case "QUERY":
			case "LIMIT":
			case "USE_TF_FILTER":
				break;
			default:
				if (is_numeric($field) && is_array($val))
				{
					$subFilter = $this->prepareFilter($val, true);
					if (!empty($subFilter))
					{
						if (isset($subFilter["cond1"]))
							$arWhere["cond1"][] = "(".implode(")and(", $subFilter).")";
						else
							$arWhere[] = "(".implode(")and(", $subFilter).")";
					}
				}
				else
				{
					AddMessage2Log("field: $field; val: ".$val);
				}
				break;
			}
		}

		if (isset($arWhere["cond1"]))
			$arWhere["cond1"] = "(".implode(")and(", $arWhere["cond1"]).")";

		if ($orLogic && !empty($arWhere))
		{
			$arWhere = array(
				"cond1" => "(".implode(")or(", $arWhere).")"
			);
		}

		return $arWhere;
	}
Esempio n. 10
0
 /**
  * OnBeforeRestartBuffer event handler.
  * Disables composite mode when called.
  *
  * @return void
  */
 public static function onBeforeRestartBuffer()
 {
     self::setEnable(false);
     if (defined("BX_COMPOSITE_DEBUG")) {
         AddMessage2Log("RestartBuffer method was invoked\n" . "Request URI: " . $_SERVER["REQUEST_URI"] . "\n" . "Script: " . (isset($_SERVER["REAL_FILE_PATH"]) ? $_SERVER["REAL_FILE_PATH"] : $_SERVER["SCRIPT_NAME"]), "composite");
     }
 }
Esempio n. 11
0
/**
 * Добавляет значение ко множественному свойству элемента инфоблока
 *
 * **Не работает со значениями-массивами**
 *
 * @param  integer          $elementId    ID элемента инфоблока
 * @param  integer          $iblockId     ID инфоблока
 * @param  string           $propertyCode Символьный код свойства
 * @param  string|integer   $value        Добавляемое значение
 * @return boolean                        Всегда *true*
 */
function appendValue($elementId, $iblockId, $propertyCode, $value)
{
    $failed = false;
    if (!isElementOfIblock($elementId, $iblockId)) {
        $failed = true;
    }
    if (!isPropertyOfIblock($propertyCode, $iblockId)) {
        $failed = true;
    }
    if (is_array($value)) {
        $failed = true;
    }
    if (!is_string($propertyCode)) {
        $failed = true;
    }
    if ($failed === true) {
        AddMessage2Log(print_r(array('element_id' => $elementId, 'iblock_id' => $iblockId, 'property_code' => $propertyCode, 'value' => $value), true));
        return false;
    }
    $arValues = array();
    $resCurrentValues = \CIBlockElement::GetProperty($iblockId, $elementId, 'sort', 'asc', array("CODE" => $propertyCode));
    while ($arValue = $resCurrentValues->Fetch()) {
        $arValues[$arValue["VALUE"]] = 1;
    }
    $arValues[$value] = 1;
    \CIBlockElement::SetPropertyValuesEx($elementId, $iblockId, array($propertyCode => array_keys($arValues)));
    return true;
}
Esempio n. 12
0
	public static function ReportLog( $title ='debug' , $data, $dump = false){
		ob_start();
			echo "\n$title\n\n". __FILE__ ."\n";
			
			if( $dump == true){
				var_dump ( $data);
			}else{
				print_r ( $data);
			}
			
			echo "\n ";
			$toLog = ob_get_contents();
		ob_end_clean();
		AddMessage2Log("$toLog", " client class ");
	}
Esempio n. 13
0
<?php

IncludeTemplateLangFile(__FILE__);
AddMessage2Log($APPLICATION->GetCurDir());
?>
<!DOCTYPE HTML>
<html lang="<?php 
echo LANGUAGE_ID;
?>
">
<head>
	<title><?php 
$APPLICATION->ShowTitle();
?>
 - компания «МСТ»</title>
	<meta property="og:site_name" content="Ваш сайт" />
	<meta property="og:locale" content="ru_RU" />
	<meta property="og:title" content="<?php 
$APPLICATION->ShowTitle();
?>
" />
	<meta property="og:image" content="<?php 
echo SITE_TEMPLATE_PATH;
?>
/images/logo.png" />
	<link rel="index" title="Arenda-Yamobure.com" href="/" />
	<meta name="application-name" content="Arenda-Yamobure.com" />
	<meta charset="utf-8" />
	<meta name="viewport" content="width=device-width, initial-scale=1.0" />
	<link rel="shortcut icon" href="/favicon.ico" />
	<link rel="icon" type="image/x-icon" href="/favicon.ico" />
Esempio n. 14
0
 function WriteElementUpdateDebug(&$arFields)
 {
     define("LOG_FILENAME", $_SERVER["DOCUMENT_ROOT"] . "/import_element_log.txt");
     AddMessage2Log(print_r($arFields, true), "------------UPDATE-----------");
 }
Esempio n. 15
0
 /**
  * Checks component frame mode
  * @param string $context
  */
 public static function applyComponentFrameMode($context = "")
 {
     if (defined("USE_HTML_STATIC_CACHE") && USE_HTML_STATIC_CACHE === true && \Bitrix\Main\Page\Frame::getInstance()->getCurrentDynamicId() === false) {
         $staticHtmlCache = static::getInstance();
         if (!$staticHtmlCache->isVotingEnabled()) {
             return;
         }
         $staticHtmlCache->markNonCacheable();
         if (defined("BX_COMPOSITE_DEBUG") && BX_COMPOSITE_DEBUG === true) {
             AddMessage2Log("Reason: " . $context . "\n" . "Request URI: " . $_SERVER["REQUEST_URI"] . "\n" . "Script: " . (isset($_SERVER["REAL_FILE_PATH"]) ? $_SERVER["REAL_FILE_PATH"] : $_SERVER["SCRIPT_NAME"]), "Composite was rejected");
         }
     }
 }
Esempio n. 16
0
 public function call($methodName, $additionalParams = null)
 {
     if (!is_array($additionalParams)) {
         $additionalParams = array();
     }
     $request = $this->prepareRequest($additionalParams);
     $http = new \Bitrix\Main\Web\HttpClient(array('socketTimeout' => $this->httpTimeout));
     $result = $http->post(CBitrix24NetOAuthInterface::NET_URL . self::SERVICE_URL . $methodName, $request);
     try {
         $res = $this->prepareResponse($result);
     } catch (\Bitrix\Main\ArgumentException $e) {
         $res = false;
     }
     if (!$res) {
         AddMessage2Log('Strange answer from Network! ' . $http->getStatus() . ' ' . $result);
     }
     return $res;
 }
Esempio n. 17
0
function FormationName(&$arFields) {
	
	if ( $arFields['IBLOCK_ID'] == 24 ){
		// if iBLOCK_ID SK_CONTRACT
		try{

			global $APPLICATION;
			$include_file = __DIR__ .'/../templates/work_copy/class/class_contract.php';
			include_once ( $include_file );

			$no_errors = IBlockContractHandler::OnBeforeIBlockElementAddHandler( $arFields );

			if( is_array( $no_errors ) != true && $no_errors === true ){
				return true;
			}else{
				$APPLICATION->throwException( implode ("\n", $no_errors ));
				return false;
			}
		}catch( Exception $e ){

			ob_start();
				echo "\n ". __FILE__ ."\n";
				print_r ( $e->getMessage() );
				echo "\n ";
				$toLog = ob_get_contents();
			ob_end_clean();
			AddMessage2Log("$toLog", "my_module_id");
		}
	}elseif( $arFields['IBLOCK_ID'] == 23 ){
		try{
			global $APPLICATION;
			$include_file = __DIR__ .'/../templates/work_copy/class/class_chassis.php';
			include_once ( $include_file );

			$no_errors = IBlockChassisHandler::OnBeforeIBlockElementAddHandler( $arFields );

			if( is_array( $no_errors ) != true && $no_errors === true ){
				return true;
			}else{
				$APPLICATION->throwException( implode ("\n", $no_errors ));
				return false;
			}
		}catch( Exception $e ){
			echo $e->getMessage();
		}
	}elseif( $arFields['IBLOCK_ID'] == 22 ){
		try{

			global $APPLICATION;
			$include_file = __DIR__ .'/../templates/work_copy/class/class_client.php';
			include_once ( $include_file );

			$no_errors = IBlockClientHandler::OnBeforeIBlockElementAddHandler( $arFields );
		
			if( is_array( $no_errors ) != true && $no_errors === true ){
				return true;
			}else{
				$APPLICATION->throwException( implode ("\n", $no_errors ));
				return false;
			}
		}catch( Exception $e ){
			echo $e->getMessage();
		}
	}elseif( $arFields['IBLOCK_ID'] == 6  ){
		try{
			global $USER;
			CModule::IncludeModule('iblock');
			$dbEl = CIBlockElement::GetByID( $arFields["ID"] );
			if( $obEl = $dbEl->GetNextElement() ){

				$CurrentVal = $obEl->GetFields();
				$CurrentVal["PROPERTIES"] = $obEl->GetProperties();
				
				// ob_start();
				// echo "\n ". __FILE__ ."\n";
				// print_r ( $arFields );
				// print_r ( $CurrentVal );
				// echo "\n ";
				// $toLog = ob_get_contents();
				// ob_end_clean();
				// AddMessage2Log("$toLog", __METHOD__ . __LINE__);
				
				$log_mess = "";
				$newService_code = $arFields["PROPERTY_VALUES"][106] [ $CurrentVal ["PROPERTIES"]["service_code"]["PROPERTY_VALUE_ID"] ]["VALUE"];
				if( $CurrentVal ["PROPERTIES"]["service_code"]["VALUE"] !==  $newService_code ){
					$log_mess.= "Значение свойства «". $CurrentVal ["PROPERTIES"]["service_code"]["NAME"]."» изменено ".$CurrentVal["PROPERTIES"]["service_code"]["VALUE"]." => ".$newService_code." ;";
				}
				$newService_price = $arFields["PROPERTY_VALUES"][107] [ $CurrentVal ["PROPERTIES"]["service_price"]["PROPERTY_VALUE_ID"] ]["VALUE"];
				if( $CurrentVal ["PROPERTIES"]["service_price"]["VALUE"] !== $newService_price ){
					$log_mess.= "Значение свойства «". $CurrentVal ["PROPERTIES"]["service_price"]["NAME"]."» изменено ".$CurrentVal["PROPERTIES"]["service_price"]["VALUE"]." => ".$newService_price." ;";
				}
				
				if( $log_mess!="" ){
					CEventLog::Add(array(
						"SEVERITY"=>"SECURITY",
						"AUDIT_TYPE_ID"=>"SERVICE_CALC_ITEM_PRICE_CHANGE",
						"MODULE_ID"=>"IBLOCK",
						"ITEM_ID"=>$arFields["ID"],
						"USER_ID"=>$USER->GetID(),
						"DESCRIPTION"=>"$log_mess",
					));
				}
			}else{
				throw new Exception("Элемент с ID: ".$arFields["ID"]." не найден.");
			}
		}catch( Exception $e ){
				echo $e->getMessage();
		}			
	}
}
Esempio n. 18
0
 <?
     include_once($_SERVER['DOCUMENT_ROOT'].'/include/getTitle_and_getAlt.php');
 ?>
 <div class="outer-content-wrapper item-cross item-page-outer-posit" style="float:none; margin-left: auto; margin-right: auto;">
     <div class="content-wrapper">
         <p class="section-header">С этим товаром покупают</p>
         <div class="item-cards-list-cnt">
             <ul class="item-cards-list js-item-cards-slider">
                 <?foreach ($arResult["ITEMS"] as $key => $arItems) :?>
                     <li class="item-card-item">
                         <a href="<?=$arItems["DETAIL_PAGE_URL"]?>">
                             <?
                                 //$waterImage = waterImage($arItems["~PREVIEW_PICTURE"]);
                                 // $waterImage["src"]
                                 $waterImage["src"] = CFIle::GetPath($arItems["~PREVIEW_PICTURE"]);
                                 AddMessage2Log($arItems["ID"], "/log/")
                             ?>
                             <div class="img-cnt">
                                 <img src="/img/img_dummy.png" data-src="<?=$waterImage["src"]?>" alt="<?=getAlt($arItems)?>" title="<?=getTitle($arItems)?>"/>
                             </div>
                             <div class="item-info">
                                 <p class="item-brand">Артикул <?=$arItems["PROPERTY_ARTIKUL_VALUE"]?></p>
                                 <p class="item-desc"><?=$arItems["NAME"]?></p>
                                 <?if ($arItems['PRICE_VALUE']['DISCOUNT_PRICE'] < $arItems['PRICE_VALUE']['PRICE']):?>
                                     <p class="item-price"><span><?=number_format($arItems['PRICE_VALUE']['DISCOUNT_PRICE'], 0, 0, " ")?></span> руб.</p>
                                     <p class="old-price"><span><?=number_format($arItems['PRICE_VALUE']['PRICE'], 0, 0, " ")?></span> руб.</p>
                                 <?else:?>
                                     <p class="item-price"><span><?=number_format($arItems['PRICE_VALUE']['PRICE'], 0, 0, " ")?></span> руб.</p>
                                 <?endif?>
                             </div>
                             <?if ($arItems["PROPERTY_HIT_VALUE"]):?>
Esempio n. 19
0
 /**
  * @return string $status one of this values:
  *    self::GRAPH_STATUS_LEGACY - if not updated to graph (it means, we must work in legacy mode)
  *    self::GRAPH_STATUS_UPDATED_TO_GRAPH - if update to graph,
  *    self::GRAPH_STATUS_UNDEFINED - if status is undefined (update in progress or interrupted)
  */
 public static function getUpdatedToGraphStatus()
 {
     $rc = COption::GetOptionString(self::MODULE_ID, self::OPTION_ID, self::DEFAULT_VALUE, self::SITE_ID);
     // status wasn't set yet (we must determine, is our tables updated to graph or not)
     if ($rc === self::DEFAULT_VALUE) {
         // Set determined mode in global options
         self::setUpdatedToGraphStatus(self::GRAPH_STATUS_LEGACY);
     }
     $allowed_statuses = array(self::GRAPH_STATUS_LEGACY, self::GRAPH_STATUS_UPDATED_TO_GRAPH, self::GRAPH_STATUS_UNDEFINED);
     if (!in_array($rc, $allowed_statuses, true)) {
         AddMessage2Log('Invalid COption ~CLearnHelper::isUpdatedToGraph();: `' . $rc . '`;', 'learning');
         $rc = self::GRAPH_STATUS_UNDEFINED;
     }
     return $rc;
 }
Esempio n. 20
0
 /**
  * Logs data in common log (@see AddMessage2Log).
  * @param mixed $data Mixed data to log.
  * @return void
  */
 public function log($data)
 {
     $this->showOnDisplay && var_dump($data);
     AddMessage2Log(var_export($data, true), 'disk', 0);
 }
Esempio n. 21
0
 /**
  * Deletes the file
  * with predefined path (current request uri)
  *
  * @return void
  */
 public function delete()
 {
     if ($this->cacheFile && $this->cacheFile->isExists()) {
         $cacheDirectory = $this->cacheFile->getDirectory();
         $fileSize = $this->cacheFile->getFileSize();
         if (defined("FX_COMPOSITE_DEBUG")) {
             $backupName = $this->cacheFile->getPath() . ".delete." . microtime(true);
             if ($this->checkQuota()) {
                 AddMessage2Log($backupName, "composite");
                 $backupFile = new Main\IO\File($backupName);
                 $backupFile->putContents($this->cacheFile->getContents());
                 $this->writeStatistic(0, 0, 0, 0, $fileSize);
             } else {
                 AddMessage2Log($backupName . "(quota exceeded)", "composite");
             }
         }
         $this->cacheFile->delete();
         //Try to cleanup directory
         $children = $cacheDirectory->getChildren();
         if (empty($children)) {
             $cacheDirectory->delete();
         }
         //Update total files size
         $this->writeStatistic(0, 0, 0, 0, -$fileSize);
     }
 }
Esempio n. 22
0
 function Query($strSql, $bIgnoreErrors = false, $error_position = "", $arOptions = array())
 {
     global $DB;
     $this->DoConnect();
     $this->db_Error = "";
     if ($this->DebugToFile || $DB->ShowSqlStat) {
         $start_time = microtime(true);
     }
     //We track queries for DML statements
     //and when there is no one we can choose
     //to run query against master connection
     //or replicated one
     static $bSelectOnly = true;
     if ($this->bModuleConnection) {
         //In case of dedicated module database
         //were is nothing to do
     } elseif ($DB->bMasterOnly > 0) {
         //We requested to process all queries
         //by master connection
     } elseif (isset($arOptions["fixed_connection"])) {
         //We requested to process this query
         //by current connection
     } elseif ($this->bNodeConnection) {
         //It is node so nothing to do
     } else {
         $bSelect = preg_match('/^\\s*(select|show)/i', $strSql) && !preg_match('/get_lock/i', $strSql);
         if (!$bSelect && !isset($arOptions["ignore_dml"])) {
             $bSelectOnly = false;
         }
         if ($bSelect && $bSelectOnly) {
             if (!isset($this->obSlave)) {
                 $this->StartUsingMasterOnly();
                 //This is bootstrap code
                 $this->obSlave = CDatabase::SlaveConnection();
                 $this->StopUsingMasterOnly();
             }
             if (is_object($this->obSlave)) {
                 return $this->obSlave->Query($strSql, $bIgnoreErrors, $error_position, $arOptions);
             }
         }
     }
     $result = @mysql_query($strSql, $this->db_Conn);
     if ($this->DebugToFile || $DB->ShowSqlStat) {
         $exec_time = round(microtime(true) - $start_time, 10);
         if ($DB->ShowSqlStat) {
             $DB->cntQuery++;
             $DB->timeQuery += $exec_time;
             $DB->arQueryDebug[] = array("QUERY" => $strSql, "TIME" => $exec_time, "TRACE" => function_exists("debug_backtrace") ? debug_backtrace() : false, "BX_STATE" => $GLOBALS["BX_STATE"]);
         }
         if ($this->DebugToFile) {
             $fp = fopen($_SERVER["DOCUMENT_ROOT"] . "/mysql_debug.sql", "ab+");
             $str = "TIME: " . $exec_time . " SESSION: " . session_id() . "  CONN: " . $this->db_Conn . "\n";
             $str .= $strSql . "\n\n";
             $str .= "----------------------------------------------------\n\n";
             fputs($fp, $str);
             @fclose($fp);
         }
     }
     if (!$result) {
         $this->db_Error = mysql_error($this->db_Conn);
         $this->db_ErrorSQL = $strSql;
         if (!$bIgnoreErrors) {
             AddMessage2Log($error_position . " MySql Query Error: " . $strSql . " [" . $this->db_Error . "]", "main");
             if ($this->DebugToFile) {
                 $fp = fopen($_SERVER["DOCUMENT_ROOT"] . "/mysql_debug.sql", "ab+");
                 fputs($fp, "SESSION: " . session_id() . " ERROR: " . $this->db_Error . "\n\n----------------------------------------------------\n\n");
                 @fclose($fp);
             }
             if ($this->debug || @session_start() && $_SESSION["SESS_AUTH"]["ADMIN"]) {
                 echo $error_position . "<br><font color=#ff0000>MySQL Query Error: " . htmlspecialcharsbx($strSql) . "</font>[" . htmlspecialcharsbx($this->db_Error) . "]<br>";
             }
             $error_position = preg_replace("#<br[^>]*>#i", "\n", $error_position);
             SendError($error_position . "\nMySQL Query Error:\n" . $strSql . " \n [" . $this->db_Error . "]\n---------------\n\n");
             if (file_exists($_SERVER["DOCUMENT_ROOT"] . BX_PERSONAL_ROOT . "/php_interface/dbquery_error.php")) {
                 include $_SERVER["DOCUMENT_ROOT"] . BX_PERSONAL_ROOT . "/php_interface/dbquery_error.php";
             } elseif (file_exists($_SERVER["DOCUMENT_ROOT"] . "/bitrix/modules/main/include/dbquery_error.php")) {
                 include $_SERVER["DOCUMENT_ROOT"] . "/bitrix/modules/main/include/dbquery_error.php";
             } else {
                 die("MySQL Query Error!");
             }
             die;
         }
         return false;
     }
     $res = new CDBResult($result);
     $res->DB = $this;
     if ($DB->ShowSqlStat) {
         $res->SqlTraceIndex = count($DB->arQueryDebug);
     }
     return $res;
 }
Esempio n. 23
0
    public static function OnBeforePrologHandler()
    {
        global $USER_FIELD_MANAGER;
        if (isset($_REQUEST['action_button']) && !isset($_REQUEST['action'])) {
            $_REQUEST['action'] = $_REQUEST['action_button'];
        }
        if (!isset($_REQUEST['action'])) {
            return;
        }
        $BID = isset($_REQUEST['ID']) ? (int) $_REQUEST['ID'] : 0;
        if ($_REQUEST['action'] == 'asd_prop_export' && $BID > 0 && check_bitrix_sessid() && CModule::IncludeModule('iblock') && CASDIblockRights::IsIBlockEdit($BID)) {
            $strPath = $_SERVER['DOCUMENT_ROOT'] . '/bitrix/tmp/asd.iblock/';
            $strName = 'asd_props_export_' . $BID . '_' . md5(LICENSE_KEY) . '.xml';
            CheckDirPath($strPath);
            if ($hdlOutput = fopen($strPath . $strName, 'wb')) {
                fwrite($hdlOutput, '<?xml version="1.0" encoding="' . SITE_CHARSET . '"?>' . "\n");
                fwrite($hdlOutput, '<asd_iblock_props>' . "\n");
                fwrite($hdlOutput, CASDiblockTools::ExportPropsToXML($BID, $_REQUEST['p']));
                if ($_REQUEST['forms'] == 'Y') {
                    fwrite($hdlOutput, CASDiblockTools::ExportSettingsToXML($BID, array('forms')));
                }
                fwrite($hdlOutput, '</asd_iblock_props>' . "\n");
                fclose($hdlOutput);
            }
            ?>
<script type="text/javascript">
				top.BX.closeWait(); top.BX.WindowManager.Get().AllowClose(); top.BX.WindowManager.Get().Close();
				window.location.href = '/bitrix/tools/asd.iblock/props_export.php?ID=<?php 
            echo $BID;
            ?>
';
			</script><?php 
            die;
        }
        if ($_REQUEST['action'] == 'asd_prop_import' && $BID > 0 && !$_FILES['xml_file']['error'] && check_bitrix_sessid() && CModule::IncludeModule('iblock') && CASDIblockRights::IsIBlockEdit($BID)) {
            CASDiblockTools::ImportPropsFromXML($BID, $_FILES['xml_file']['tmp_name'], $arOldNewID);
            CASDiblockTools::ImportFormsFromXML($BID, $_FILES['xml_file']['tmp_name'], $arOldNewID);
            LocalRedirect('/bitrix/admin/iblock_edit.php?type=' . $_REQUEST['type'] . '&tabControl_active_tab=edit2&lang=' . LANGUAGE_ID . '&ID=' . $BID . '&admin=Y');
        }
        $IBLOCK_ID = 0;
        if (isset($_REQUEST['IBLOCK_ID'])) {
            $IBLOCK_ID = (int) $_REQUEST['IBLOCK_ID'];
            if ($IBLOCK_ID < 0) {
                $IBLOCK_ID = 0;
            }
        }
        if ($_REQUEST['action'] == 'asd_reverse' && $IBLOCK_ID > 0 && check_bitrix_sessid() && CModule::IncludeModule('iblock') && CASDIblockRights::IsIBlockEdit($IBLOCK_ID)) {
            $LIST_MODE = CIBlock::GetArrayByID($IBLOCK_ID, 'LIST_MODE');
            if (!strlen($LIST_MODE)) {
                $LIST_MODE = COption::GetOptionString('iblock', 'combined_list_mode', 'N') == 'Y' ? 'C' : 'S';
            }
            $LIST_MODE = $LIST_MODE == 'C' ? 'S' : 'C';
            $ib = new CIBlock();
            $ib->Update($IBLOCK_ID, array('LIST_MODE' => $LIST_MODE));
            LocalRedirect('/bitrix/admin/' . ($LIST_MODE == 'S' ? 'iblock_element_admin' : 'iblock_list_admin') . '.php?IBLOCK_ID=' . $IBLOCK_ID . '&type=' . htmlspecialcharsbx($_REQUEST['type']) . '&find_section_section=' . intval($_REQUEST['find_section_section']) . '&lang=' . LANGUAGE_ID);
        }
        $strCurPage = $GLOBALS['APPLICATION']->GetCurPage();
        $bElemPage = $strCurPage == '/bitrix/admin/iblock_element_admin.php' || $strCurPage == '/bitrix/admin/cat_product_admin.php';
        $bSectPage = $strCurPage == '/bitrix/admin/iblock_section_admin.php' || $strCurPage == '/bitrix/admin/cat_section_admin.php';
        $bMixPage = $strCurPage == '/bitrix/admin/iblock_list_admin.php';
        $bRightPage = $bElemPage || $bSectPage || $bMixPage;
        $successRedirect = false;
        if ($bRightPage && $_REQUEST['action'] == 'asd_copy_in_list' && strlen($_REQUEST['ID']) > 0) {
            $bDoAction = true;
            $_REQUEST['action'] = 'asd_copy';
            $_REQUEST['asd_ib_dest'] = $IBLOCK_ID;
            $_REQUEST['ID'] = array($_REQUEST['ID']);
        } else {
            $bDoAction = false;
        }
        if ($bRightPage && check_bitrix_sessid() && !empty($_REQUEST['ID']) && ($_SERVER['REQUEST_METHOD'] == 'POST' || $bDoAction) && CModule::IncludeModule('iblock') && ($_REQUEST['action'] == 'asd_copy' || $_REQUEST['action'] == 'asd_move') && isset($_REQUEST['asd_ib_dest']) && (int) $_REQUEST['asd_ib_dest'] > 0 && CASDIblockRights::IsIBlockDisplay($_REQUEST['asd_ib_dest'])) {
            $intSrcIBlockID = $IBLOCK_ID;
            $intDestIBlockID = (int) $_REQUEST['asd_ib_dest'];
            $intSetSectID = 0;
            if (isset($_REQUEST['asd_sect_dest'])) {
                $intSetSectID = (int) $_REQUEST['asd_sect_dest'];
                if ($intSetSectID < 0) {
                    $intSetSectID = 0;
                }
            }
            $boolCreateElement = false;
            $boolCreateSection = false;
            if ($bElemPage || $bMixPage) {
                $boolCreateElement = CASDIblockRights::IsSectionElementCreate($intDestIBlockID, $intSetSectID);
            }
            if ($bSectPage || $bMixPage) {
                $boolCreateSection = CASDIblockRights::IsSectionSectionCreate($intDestIBlockID, $intSetSectID);
            }
            if ($boolCreateElement || $boolCreateSection) {
                $arPropListCache = array();
                $arOldPropListCache = array();
                $arNamePropListCache = array();
                $arOldNamePropListCache = array();
                $boolUFListCache = false;
                $arUFListCache = array();
                $arOldUFListCache = array();
                $arUFEnumCache = array();
                $arOldUFEnumCache = array();
                $arUFNameEnumCache = array();
                $arOldUFNameEnumCache = array();
                $arDestIBlock = CIBlock::GetArrayByID($intDestIBlockID);
                $arDestIBFields = $arDestIBlock['FIELDS'];
                $boolCodeUnique = false;
                if ($arDestIBFields['CODE']['DEFAULT_VALUE']['UNIQUE'] == 'Y') {
                    $boolCodeUnique = $intSrcIBlockID == $intDestIBlockID;
                }
                $boolSectCodeUnique = false;
                if ($arDestIBFields['SECTION_CODE']['DEFAULT_VALUE']['UNIQUE'] == 'Y') {
                    $boolSectCodeUnique = $intSrcIBlockID == $intDestIBlockID;
                }
                $boolCatalog = CModule::IncludeModule('catalog');
                $boolCopyCatalog = false;
                $boolNewCatalog = false;
                if ($boolCatalog) {
                    $boolCopyCatalog = is_array(CCatalog::GetByID($intDestIBlockID));
                    $boolNewCatalog = $boolCopyCatalog;
                    if ($boolCopyCatalog) {
                        $boolCopyCatalog = is_array(CCatalog::GetByID($intSrcIBlockID));
                    }
                }
                $el = new CIBlockElement();
                $sc = new CIBlockSection();
                $obEnum = new CUserFieldEnum();
                foreach ($_REQUEST['ID'] as $eID) {
                    $boolCopyElem = false;
                    $boolCopySect = false;
                    if ($bMixPage) {
                        if (substr($eID, 0, 1) != 'E') {
                            $boolCopySect = true;
                        } else {
                            $boolCopyElem = true;
                        }
                        $ID = (int) substr($eID, 1);
                    } else {
                        $boolCopyElem = $bElemPage;
                        $boolCopySect = $bSectPage;
                        $ID = (int) $eID;
                    }
                    if ($boolCreateElement && $boolCopyElem) {
                        if ($obSrc = CIBlockElement::GetByID($ID)->GetNextElement()) {
                            $arSrc = $obSrc->GetFields();
                            $arSrcPr = $obSrc->GetProperties(false, array('EMPTY' => 'N'));
                            $arSrc['PREVIEW_PICTURE'] = (int) $arSrc['PREVIEW_PICTURE'];
                            if ($arSrc['PREVIEW_PICTURE'] > 0) {
                                $arSrc['PREVIEW_PICTURE'] = CFile::MakeFileArray($arSrc['PREVIEW_PICTURE']);
                                if (empty($arSrc['PREVIEW_PICTURE'])) {
                                    $arSrc['PREVIEW_PICTURE'] = false;
                                } else {
                                    $arSrc['PREVIEW_PICTURE']['COPY_FILE'] = 'Y';
                                }
                            } else {
                                $arSrc['PREVIEW_PICTURE'] = false;
                            }
                            $arSrc['DETAIL_PICTURE'] = (int) $arSrc['DETAIL_PICTURE'];
                            if ($arSrc['DETAIL_PICTURE'] > 0) {
                                $arSrc['DETAIL_PICTURE'] = CFile::MakeFileArray($arSrc['DETAIL_PICTURE']);
                                if (empty($arSrc['DETAIL_PICTURE'])) {
                                    $arSrc['DETAIL_PICTURE'] = false;
                                } else {
                                    $arSrc['DETAIL_PICTURE']['COPY_FILE'] = 'Y';
                                }
                            } else {
                                $arSrc['DETAIL_PICTURE'] = false;
                            }
                            $arSrc = array('IBLOCK_ID' => $intDestIBlockID, 'ACTIVE' => $arSrc['ACTIVE'], 'ACTIVE_FROM' => $arSrc['ACTIVE_FROM'], 'ACTIVE_TO' => $arSrc['ACTIVE_TO'], 'SORT' => $arSrc['SORT'], 'NAME' => $arSrc['~NAME'], 'PREVIEW_PICTURE' => $arSrc['PREVIEW_PICTURE'], 'PREVIEW_TEXT' => $arSrc['~PREVIEW_TEXT'], 'PREVIEW_TEXT_TYPE' => $arSrc['PREVIEW_TEXT_TYPE'], 'DETAIL_TEXT' => $arSrc['~DETAIL_TEXT'], 'DETAIL_TEXT_TYPE' => $arSrc['DETAIL_TEXT_TYPE'], 'DETAIL_PICTURE' => $arSrc['DETAIL_PICTURE'], 'WF_STATUS_ID' => $arSrc['WF_STATUS_ID'], 'CODE' => $arSrc['~CODE'], 'TAGS' => $arSrc['~TAGS'], 'XML_ID' => $arSrc['~XML_ID'], 'PROPERTY_VALUES' => array());
                            if ($arDestIBFields['CODE']['IS_REQUIRED'] == 'Y') {
                                if (!strlen($arSrc['CODE'])) {
                                    $arSrc['CODE'] = mt_rand(100000, 1000000);
                                }
                            }
                            if ($arDestIBFields['CODE']['DEFAULT_VALUE']['UNIQUE'] == 'Y') {
                                $boolElCodeUnique = $boolCodeUnique;
                                if (!$boolCodeUnique) {
                                    $rsCheckItems = CIBlockElement::GetList(array(), array('IBLOCK_ID' => $intDestIBlockID, '=CODE' => $arSrc['CODE'], 'CHECK_PERMISSIONS' => 'N'), false, array('nTopCount' => 1), array('ID', 'IBLOCK_ID'));
                                    if ($arCheck = $rsCheckItems->Fetch()) {
                                        $boolElCodeUnique = true;
                                    }
                                }
                                if ($boolElCodeUnique) {
                                    $arSrc['CODE'] .= mt_rand(100, 10000);
                                }
                            }
                            if ($intSetSectID > 0) {
                                $arSrc['IBLOCK_SECTION_ID'] = $intSetSectID;
                            } elseif ($intSrcIBlockID == $intDestIBlockID) {
                                $arSectionList = array();
                                $rsSections = CIBlockElement::GetElementGroups($ID, true);
                                while ($arSection = $rsSections->Fetch()) {
                                    $arSectionList[] = $arSection['ID'];
                                }
                                $arSrc['IBLOCK_SECTION'] = $arSectionList;
                            }
                            if ($intSrcIBlockID != $intDestIBlockID) {
                                if (empty($arPropListCache)) {
                                    $rsProps = CIBlockProperty::GetList(array(), array('IBLOCK_ID' => $intDestIBlockID, 'PROPERTY_TYPE' => 'L', 'ACTIVE' => 'Y', 'CHECK_PERMISSIONS' => 'N'));
                                    while ($arProp = $rsProps->Fetch()) {
                                        $arValueList = array();
                                        $arNameList = array();
                                        $rsValues = CIBlockProperty::GetPropertyEnum($arProp['ID']);
                                        while ($arValue = $rsValues->Fetch()) {
                                            $arValueList[$arValue['XML_ID']] = $arValue['ID'];
                                            $arNameList[$arValue['ID']] = trim($arValue['VALUE']);
                                        }
                                        if (!empty($arValueList)) {
                                            $arPropListCache[$arProp['CODE']] = $arValueList;
                                        }
                                        if (!empty($arNameList)) {
                                            $arNamePropListCache[$arProp['CODE']] = $arNameList;
                                        }
                                    }
                                }
                                if (empty($arOldPropListCache)) {
                                    $rsProps = CIBlockProperty::GetList(array(), array('IBLOCK_ID' => $intSrcIBlockID, 'PROPERTY_TYPE' => 'L', 'ACTIVE' => 'Y', 'CHECK_PERMISSIONS' => 'N'));
                                    while ($arProp = $rsProps->Fetch()) {
                                        $arValueList = array();
                                        $arNameList = array();
                                        $rsValues = CIBlockProperty::GetPropertyEnum($arProp['ID']);
                                        while ($arValue = $rsValues->Fetch()) {
                                            $arValueList[$arValue['ID']] = $arValue['XML_ID'];
                                            $arNameList[$arValue['ID']] = trim($arValue['VALUE']);
                                        }
                                        if (!empty($arValueList)) {
                                            $arOldPropListCache[$arProp['CODE']] = $arValueList;
                                        }
                                        if (!empty($arNameList)) {
                                            $arOldNamePropListCache[$arProp['CODE']] = $arNameList;
                                        }
                                    }
                                }
                            }
                            foreach ($arSrcPr as &$arProp) {
                                if ($arProp['USER_TYPE'] == 'HTML') {
                                    if (is_array($arProp['~VALUE'])) {
                                        if ($arProp['MULTIPLE'] == 'N') {
                                            $arSrc['PROPERTY_VALUES'][$arProp['CODE']] = array('VALUE' => array('TEXT' => $arProp['~VALUE']['TEXT'], 'TYPE' => $arProp['~VALUE']['TYPE']));
                                            if ($arProp['WITH_DESCRIPTION'] == 'Y') {
                                                $arSrc['PROPERTY_VALUES'][$arProp['CODE']]['DESCRIPTION'] = $arProp['~DESCRIPTION'];
                                            }
                                        } else {
                                            if (!empty($arProp['~VALUE'])) {
                                                $arSrc['PROPERTY_VALUES'][$arProp['CODE']] = array();
                                                foreach ($arProp['~VALUE'] as $propValueKey => $propValue) {
                                                    $oneNewValue = array('VALUE' => array('TEXT' => $propValue['TEXT'], 'TYPE' => $propValue['TYPE']));
                                                    if ($arProp['WITH_DESCRIPTION'] == 'Y') {
                                                        $oneNewValue['DESCRIPTION'] = $arProp['~DESCRIPTION'][$propValueKey];
                                                    }
                                                    $arSrc['PROPERTY_VALUES'][$arProp['CODE']][] = $oneNewValue;
                                                    unset($oneNewValue);
                                                }
                                                unset($propValue, $propValueKey);
                                            }
                                        }
                                    }
                                } elseif ($arProp['PROPERTY_TYPE'] == 'F') {
                                    if (is_array($arProp['VALUE'])) {
                                        $arSrc['PROPERTY_VALUES'][$arProp['CODE']] = array();
                                        foreach ($arProp['VALUE'] as $propValueKey => $file) {
                                            if ($file > 0) {
                                                $tmpValue = CFile::MakeFileArray($file);
                                                if (!is_array($tmpValue)) {
                                                    continue;
                                                }
                                                if ($arProp['WITH_DESCRIPTION'] == 'Y') {
                                                    $tmpValue = array('VALUE' => $tmpValue, 'DESCRIPTION' => $arProp['~DESCRIPTION'][$propValueKey]);
                                                }
                                                $arSrc['PROPERTY_VALUES'][$arProp['CODE']][] = $tmpValue;
                                            }
                                        }
                                    } elseif ($arProp['VALUE'] > 0) {
                                        $tmpValue = CFile::MakeFileArray($arProp['VALUE']);
                                        if (is_array($tmpValue)) {
                                            if ($arProp['WITH_DESCRIPTION'] == 'Y') {
                                                $tmpValue = array('VALUE' => $tmpValue, 'DESCRIPTION' => $arProp['~DESCRIPTION']);
                                            }
                                            $arSrc['PROPERTY_VALUES'][$arProp['CODE']] = $tmpValue;
                                        }
                                    }
                                } elseif ($arProp['PROPERTY_TYPE'] == 'L') {
                                    if (!empty($arProp['VALUE_ENUM_ID'])) {
                                        if ($intSrcIBlockID == $arSrc['IBLOCK_ID']) {
                                            $arSrc['PROPERTY_VALUES'][$arProp['CODE']] = $arProp['VALUE_ENUM_ID'];
                                        } else {
                                            if (isset($arPropListCache[$arProp['CODE']]) && isset($arOldPropListCache[$arProp['CODE']])) {
                                                if (is_array($arProp['VALUE_ENUM_ID'])) {
                                                    $arSrc['PROPERTY_VALUES'][$arProp['CODE']] = array();
                                                    foreach ($arProp['VALUE_ENUM_ID'] as &$intValueID) {
                                                        $strValueXmlID = $arOldPropListCache[$arProp['CODE']][$intValueID];
                                                        if (isset($arPropListCache[$arProp['CODE']][$strValueXmlID])) {
                                                            $arSrc['PROPERTY_VALUES'][$arProp['CODE']][] = $arPropListCache[$arProp['CODE']][$strValueXmlID];
                                                        } else {
                                                            $strValueName = $arOldNamePropListCache[$arProp['CODE']][$intValueID];
                                                            $intValueKey = array_search($strValueName, $arNamePropListCache[$arProp['CODE']]);
                                                            if ($intValueKey !== false) {
                                                                $arSrc['PROPERTY_VALUES'][$arProp['CODE']][] = $intValueKey;
                                                            }
                                                        }
                                                    }
                                                    if (isset($intValueID)) {
                                                        unset($intValueID);
                                                    }
                                                    if (empty($arSrc['PROPERTY_VALUES'][$arProp['CODE']])) {
                                                        unset($arSrc['PROPERTY_VALUES'][$arProp['CODE']]);
                                                    }
                                                } else {
                                                    $strValueXmlID = $arOldPropListCache[$arProp['CODE']][$arProp['VALUE_ENUM_ID']];
                                                    if (isset($arPropListCache[$arProp['CODE']][$strValueXmlID])) {
                                                        $arSrc['PROPERTY_VALUES'][$arProp['CODE']] = $arPropListCache[$arProp['CODE']][$strValueXmlID];
                                                    } else {
                                                        $strValueName = $arOldNamePropListCache[$arProp['CODE']][$arProp['VALUE_ENUM_ID']];
                                                        $intValueKey = array_search($strValueName, $arNamePropListCache[$arProp['CODE']]);
                                                        if ($intValueKey !== false) {
                                                            $arSrc['PROPERTY_VALUES'][$arProp['CODE']] = $intValueKey;
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                } elseif ($arProp['PROPERTY_TYPE'] == 'S' || $arProp['PROPERTY_TYPE'] == 'N') {
                                    if ($arProp['MULTIPLE'] == 'Y') {
                                        if (is_array($arProp['~VALUE'])) {
                                            if ($arProp['WITH_DESCRIPTION'] == 'Y') {
                                                $arSrc['PROPERTY_VALUES'][$arProp['CODE']] = array();
                                                foreach ($arProp['~VALUE'] as $propValueKey => $propValue) {
                                                    $arSrc['PROPERTY_VALUES'][$arProp['CODE']][] = array('VALUE' => $propValue, 'DESCRIPTION' => $arProp['~DESCRIPTION'][$propValueKey]);
                                                }
                                                unset($propValue, $propValueKey);
                                            } else {
                                                $arSrc['PROPERTY_VALUES'][$arProp['CODE']] = $arProp['~VALUE'];
                                            }
                                        }
                                    } else {
                                        $arSrc['PROPERTY_VALUES'][$arProp['CODE']] = $arProp['WITH_DESCRIPTION'] == 'Y' ? array('VALUE' => $arProp['~VALUE'], 'DESCRIPTION' => $arProp['~DESCRIPTION']) : $arProp['~VALUE'];
                                    }
                                } else {
                                    $arSrc['PROPERTY_VALUES'][$arProp['CODE']] = $arProp['~VALUE'];
                                }
                            }
                            if (isset($arProp)) {
                                unset($arProp);
                            }
                            AddMessage2Log($arSrc['PROPERTY_VALUES']);
                            $intNewID = $el->Add($arSrc, true, true, true);
                            if ($intNewID) {
                                if ($boolCatalog && $boolCopyCatalog) {
                                    $priceRes = CPrice::GetListEx(array(), array('PRODUCT_ID' => $ID), false, false, array('PRODUCT_ID', 'EXTRA_ID', 'CATALOG_GROUP_ID', 'PRICE', 'CURRENCY', 'QUANTITY_FROM', 'QUANTITY_TO'));
                                    while ($arPrice = $priceRes->Fetch()) {
                                        $arPrice['PRODUCT_ID'] = $intNewID;
                                        CPrice::Add($arPrice);
                                    }
                                }
                                if ($boolCatalog && $boolNewCatalog) {
                                    $arProduct = array('ID' => $intNewID);
                                    if ($boolCopyCatalog) {
                                        $productRes = CCatalogProduct::GetList(array(), array('ID' => $ID), false, false, array('QUANTITY', 'QUANTITY_TRACE_ORIG', 'CAN_BUY_ZERO_ORIG', 'NEGATIVE_AMOUNT_TRACE_ORIG', 'SUBSCRIBE_ORIG', 'WEIGHT', 'PRICE_TYPE', 'RECUR_SCHEME_TYPE', 'RECUR_SCHEME_LENGTH', 'TRIAL_PRICE_ID', 'WITHOUT_ORDER', 'SELECT_BEST_PRICE', 'VAT_ID', 'VAT_INCLUDED', 'WIDTH', 'LENGTH', 'HEIGHT', 'PURCHASING_PRICE', 'PURCHASING_CURRENCY', 'MEASURE'));
                                        if ($arCurProduct = $productRes->Fetch()) {
                                            $arProduct = $arCurProduct;
                                            $arProduct['ID'] = $intNewID;
                                            $arProduct['QUANTITY_TRACE'] = $arProduct['QUANTITY_TRACE_ORIG'];
                                            $arProduct['CAN_BUY_ZERO'] = $arProduct['CAN_BUY_ZERO_ORIG'];
                                            $arProduct['NEGATIVE_AMOUNT_TRACE'] = $arProduct['NEGATIVE_AMOUNT_TRACE_ORIG'];
                                            if (isset($arProduct['SUBSCRIBE_ORIG'])) {
                                                $arProduct['SUBSCRIBE'] = $arProduct['SUBSCRIBE_ORIG'];
                                            }
                                            foreach ($arProduct as $productKey => $productValue) {
                                                if ($productValue === null) {
                                                    unset($arProduct[$productKey]);
                                                }
                                            }
                                        }
                                    }
                                    CCatalogProduct::Add($arProduct, false);
                                }
                                if ($_REQUEST['action'] == 'asd_move') {
                                    if (CASDIblockRights::IsElementDelete($intSrcIBlockID, $ID)) {
                                        $el->Delete($ID);
                                    } else {
                                        CASDiblock::$error .= '[' . $ID . '] ' . GetMessage('ASD_ACTION_ERR_DELETE_ELEMENT_RIGHTS') . "\n";
                                    }
                                }
                            } else {
                                CASDiblock::$error .= '[' . $ID . '] ' . $el->LAST_ERROR . "\n";
                            }
                        }
                    }
                    if ($boolCreateSection && $boolCopySect) {
                        if ($_REQUEST['action'] == 'asd_move') {
                            continue;
                        }
                        $rsSections = CIBlockSection::GetList(array(), array('ID' => $ID, 'IBLOCK_ID' => $intSrcIBlockID), false, array('ID', 'NAME', 'XML_ID', 'CODE', 'IBLOCK_SECTION_ID', 'IBLOCK_ID', 'ACTIVE', 'SORT', 'PICTURE', 'DESCRIPTION', 'DESCRIPTION_TYPE', 'DETAIL_PICTURE', 'SOCNET_GROUP_ID', 'UF_*'));
                        if ($arSrcSect = $rsSections->Fetch()) {
                            $arDestSect = $arSrcSect;
                            unset($arDestSect['ID']);
                            $arDestSect['IBLOCK_ID'] = $intDestIBlockID;
                            if ($arDestIBFields['SECTION_CODE']['IS_REQUIRED'] == 'Y') {
                                if (!strlen($arDestSect['CODE'])) {
                                    $arDestSect['CODE'] = mt_rand(100000, 1000000);
                                }
                            }
                            if ($arDestIBFields['SECTION_CODE']['DEFAULT_VALUE']['UNIQUE'] == 'Y') {
                                $boolScCodeUnique = $boolSectCodeUnique;
                                if (!$boolSectCodeUnique) {
                                    $rsCheckItems = CIBlockElement::GetList(array(), array('IBLOCK_ID' => $intDestIBlockID, '=CODE' => $arSrc['CODE'], 'CHECK_PERMISSIONS' => 'N'), false, array('nTopCount' => 1), array('ID', 'IBLOCK_ID'));
                                    if ($arCheck = $rsCheckItems->Fetch()) {
                                        $boolScCodeUnique = true;
                                    }
                                }
                                if ($boolScCodeUnique) {
                                    $arDestSect['CODE'] .= mt_rand(100, 10000);
                                }
                            }
                            if ($intSetSectID > 0) {
                                $arDestSect['IBLOCK_SECTION_ID'] = $intSetSectID;
                            } elseif ($intSrcIBlockID != $intDestIBlockID) {
                                $arDestSect['IBLOCK_SECTION_ID'] = 0;
                            }
                            $arDestSect['PICTURE'] = (int) $arDestSect['PICTURE'];
                            if ($arDestSect['PICTURE'] > 0) {
                                $arDestSect['PICTURE'] = CFile::MakeFileArray($arDestSect['PICTURE']);
                                if (empty($arDestSect['PICTURE'])) {
                                    $arDestSect['PICTURE'] = false;
                                } else {
                                    $arDestSect['PICTURE']['COPY_FILE'] = 'Y';
                                }
                            } else {
                                $arDestSect['PICTURE'] = false;
                            }
                            $arDestSect['DETAIL_PICTURE'] = (int) $arDestSect['DETAIL_PICTURE'];
                            if ($arDestSect['DETAIL_PICTURE'] > 0) {
                                $arDestSect['DETAIL_PICTURE'] = CFile::MakeFileArray($arDestSect['DETAIL_PICTURE']);
                                if (empty($arDestSect['DETAIL_PICTURE'])) {
                                    $arDestSect['DETAIL_PICTURE'] = false;
                                } else {
                                    $arDestSect['DETAIL_PICTURE']['COPY_FILE'] = 'Y';
                                }
                            } else {
                                $arDestSect['DETAIL_PICTURE'] = false;
                            }
                            if (!$boolUFListCache) {
                                $boolUFListCache = true;
                                $arUFListCache = $USER_FIELD_MANAGER->GetUserFields('IBLOCK_' . $intDestIBlockID . '_SECTION');
                                if (!empty($arUFListCache)) {
                                    if ($intSrcIBlockID != $intDestIBlockID) {
                                        $arOldUFListCache = $USER_FIELD_MANAGER->GetUserFields('IBLOCK_' . $intSrcIBlockID . '_SECTION');
                                        if (empty($arOldUFListCache)) {
                                            $arUFListCache = array();
                                        }
                                    } else {
                                        $arOldUFListCache = $arUFListCache;
                                    }
                                }
                                if (!empty($arUFListCache)) {
                                    if ($intSrcIBlockID != $intDestIBlockID) {
                                        foreach ($arUFListCache as &$arOneUserField) {
                                            if ('enum' == $arOneUserField['USER_TYPE']['BASE_TYPE']) {
                                                $arUFEnumCache[$arOneUserField['FIELD_NAME']] = array();
                                                $arUFNameEnumCache[$arOneUserField['FIELD_NAME']] = array();
                                                $rsEnum = $obEnum->GetList(array(), array('USER_FIELD_ID' => $arOneUserField['ID']));
                                                while ($arEnum = $rsEnum->Fetch()) {
                                                    $arUFEnumCache[$arOneUserField['FIELD_NAME']][$arEnum['XML_ID']] = $arEnum['ID'];
                                                    $arUFNameEnumCache[$arOneUserField['FIELD_NAME']][$arEnum['ID']] = trim($arEnum['VALUE']);
                                                }
                                            }
                                        }
                                        if (isset($arOneUserField)) {
                                            unset($arOneUserField);
                                        }
                                        foreach ($arOldUFListCache as &$arOneUserField) {
                                            if ($arOneUserField['USER_TYPE']['BASE_TYPE'] == 'enum') {
                                                $arOldUFEnumCache[$arOneUserField['FIELD_NAME']] = array();
                                                $arOldUFNameEnumCache[$arOneUserField['FIELD_NAME']] = array();
                                                $rsEnum = $obEnum->GetList(array(), array('USER_FIELD_ID' => $arOneUserField['ID']));
                                                while ($arEnum = $rsEnum->Fetch()) {
                                                    $arOldUFEnumCache[$arOneUserField['FIELD_NAME']][$arEnum['ID']] = $arEnum['XML_ID'];
                                                    $arOldUFNameEnumCache[$arOneUserField['FIELD_NAME']][$arEnum['ID']] = trim($arEnum['VALUE']);
                                                }
                                            }
                                        }
                                        if (isset($arOneUserField)) {
                                            unset($arOneUserField);
                                        }
                                    }
                                }
                            }
                            if (!empty($arUFListCache)) {
                                foreach ($arUFListCache as &$arOneUserField) {
                                    if (!isset($arDestSect[$arOneUserField['FIELD_NAME']])) {
                                        continue;
                                    }
                                    if ($arOneUserField['USER_TYPE']['BASE_TYPE'] == 'file') {
                                        if (!empty($arDestSect[$arOneUserField['FIELD_NAME']])) {
                                            if (is_array($arDestSect[$arOneUserField['FIELD_NAME']])) {
                                                $arNewFileList = array();
                                                foreach ($arDestSect[$arOneUserField['FIELD_NAME']] as &$intFileID) {
                                                    $arNewFile = false;
                                                    $intFileID = (int) $intFileID;
                                                    if ($intFileID > 0) {
                                                        $arNewFile = CFile::MakeFileArray($intFileID);
                                                    }
                                                    if (!empty($arNewFile)) {
                                                        $arNewFileList[] = $arNewFile;
                                                    }
                                                }
                                                if (isset($intFileID)) {
                                                    unset($intFileID);
                                                }
                                                $arDestSect[$arOneUserField['FIELD_NAME']] = !empty($arNewFileList) ? $arNewFileList : false;
                                            } else {
                                                $arNewFile = false;
                                                $intFileID = (int) $arDestSect[$arOneUserField['FIELD_NAME']];
                                                if ($intFileID > 0) {
                                                    $arNewFile = CFile::MakeFileArray($intFileID);
                                                }
                                                $arDestSect[$arOneUserField['FIELD_NAME']] = !empty($arNewFile) ? $arNewFile : false;
                                            }
                                        } else {
                                            $arDestSect[$arOneUserField['FIELD_NAME']] = false;
                                        }
                                    } elseif ($arOneUserField['USER_TYPE']['BASE_TYPE'] == 'enum') {
                                        if (!empty($arDestSect[$arOneUserField['FIELD_NAME']])) {
                                            if ($intSrcIBlockID != $intDestIBlockID) {
                                                if (array_key_exists($arOneUserField['FIELD_NAME'], $arUFEnumCache) && array_key_exists($arOneUserField['FIELD_NAME'], $arOldUFEnumCache)) {
                                                    if (is_array($arDestSect[$arOneUserField['FIELD_NAME']])) {
                                                        $arNewEnumList = array();
                                                        foreach ($arDestSect[$arOneUserField['FIELD_NAME']] as &$intValueID) {
                                                            $strValueXmlID = $arOldUFEnumCache[$arOneUserField['FIELD_NAME']][$intValueID];
                                                            if (array_key_exists($strValueXmlID, $arUFEnumCache[$arOneUserField['FIELD_NAME']])) {
                                                                $arNewEnumList[] = $arUFEnumCache[$arOneUserField['FIELD_NAME']][$strValueXmlID];
                                                            } else {
                                                                $strValueName = $arOldUFNameEnumCache[$arOneUserField['FIELD_NAME']][$intValueID];
                                                                $intValueKey = array_search($strValueName, $arUFNameEnumCache[$arOneUserField['FIELD_NAME']]);
                                                                if ($intValueKey !== false) {
                                                                    $arNewEnumList[] = $intValueKey;
                                                                }
                                                            }
                                                        }
                                                        if (isset($intValueID)) {
                                                            unset($intValueID);
                                                        }
                                                        if (!empty($arNewEnumList)) {
                                                            $arDestSect[$arOneUserField['FIELD_NAME']] = $arNewEnumList;
                                                        }
                                                    } else {
                                                        $strValueXmlID = $arOldUFEnumCache[$arOneUserField['FIELD_NAME']][$arDestSect[$arOneUserField['FIELD_NAME']]];
                                                        if (array_key_exists($strValueXmlID, $arUFEnumCache[$arOneUserField['FIELD_NAME']])) {
                                                            $arDestSect[$arOneUserField['FIELD_NAME']] = $arUFEnumCache[$arOneUserField['FIELD_NAME']][$strValueXmlID];
                                                        } else {
                                                            $strValueName = $arOldUFNameEnumCache[$arOneUserField['FIELD_NAME']][$arDestSect[$arOneUserField['FIELD_NAME']]];
                                                            $intValueKey = array_search($strValueName, $arUFNameEnumCache[$arOneUserField['FIELD_NAME']]);
                                                            if ($intValueKey !== false) {
                                                                $arDestSect[$arOneUserField['FIELD_NAME']] = $intValueKey;
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        } else {
                                            $arDestSect[$arOneUserField['FIELD_NAME']] = false;
                                        }
                                    }
                                }
                                if (isset($arOneUserField)) {
                                    unset($arOneUserField);
                                }
                            }
                            $intNewID = $sc->Add($arDestSect);
                            if (!$intNewID) {
                                CASDiblock::$error .= '[' . $ID . '] ' . $sc->LAST_ERROR . "\n";
                            }
                        }
                    }
                }
                $successRedirect = true;
            }
            unset($_REQUEST['action']);
            if (isset($_REQUEST['action_button'])) {
                unset($_REQUEST['action_button']);
            }
            if ($successRedirect) {
                LocalRedirect($GLOBALS['APPLICATION']->GetCurPageParam('', array('action', 'action_button', 'asd_ib_dest', 'asd_sect_dest', 'ID')));
            }
        }
        if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'asd_remove' && $IBLOCK_ID > 0 && isset($_REQUEST['find_section_section']) && check_bitrix_sessid() && CASDIblockRights::IsIBlockDisplay($IBLOCK_ID)) {
            $intSectionID = (int) $_REQUEST['find_section_section'];
            if ($intSectionID > 0) {
                $strCurPage = $GLOBALS['APPLICATION']->GetCurPage();
                $bElemPage = $strCurPage == '/bitrix/admin/iblock_element_admin.php' || $strCurPage == '/bitrix/admin/cat_product_admin.php';
                $bMixPage = $strCurPage == '/bitrix/admin/iblock_list_admin.php';
                if ($bElemPage || $bMixPage) {
                    foreach ($_REQUEST['ID'] as $eID) {
                        if ($bMixPage) {
                            if (substr($eID, 0, 1) != 'E') {
                                continue;
                            }
                            $ID = (int) substr($eID, 1);
                        } else {
                            $ID = (int) $eID;
                        }
                        if ($ID <= 0) {
                            continue;
                        }
                        if (CASDIblockRights::IsElementEdit($IBLOCK_ID, $ID)) {
                            $arSectionList = array();
                            $rsSections = CIBlockElement::GetElementGroups($ID, true);
                            while ($arSection = $rsSections->Fetch()) {
                                $arSection['ID'] = (int) $arSection['ID'];
                                if ($arSection['ID'] != $intSectionID) {
                                    $arSectionList[] = $arSection['ID'];
                                }
                            }
                            CIBlockElement::SetElementSection($ID, $arSectionList, false);
                            $successRedirect = true;
                        }
                    }
                }
            }
            unset($_REQUEST['action']);
            if (isset($_REQUEST['action_button'])) {
                unset($_REQUEST['action_button']);
            }
            if ($successRedirect) {
                LocalRedirect($GLOBALS['APPLICATION']->GetCurPageParam('', array('action', 'action_button')));
            }
        }
    }
Esempio n. 24
0
 private static function decodeMessageBody($header, $body, $charset)
 {
     $encoding = strtolower($header->GetHeader('CONTENT-TRANSFER-ENCODING'));
     if ($encoding == 'base64') {
         $body = base64_decode($body);
     } elseif ($encoding == 'quoted-printable') {
         $body = quoted_printable_decode($body);
     } elseif ($encoding == 'x-uue') {
         $body = CMailUtil::uue_decode($body);
     }
     $content_type = strtolower($header->content_type);
     if ((strpos($content_type, 'plain') !== false || strpos($content_type, 'html') !== false || strpos($content_type, 'text') !== false) && strpos($content_type, 'x-vcard') === false && strpos($content_type, 'csv') === false) {
         $body = CMailUtil::ConvertCharset($body, $header->charset, $charset);
         if ($body === false) {
             AddMessage2Log("Failed to convert attachment body. content_type = " . $content_type);
         }
     }
     return array('CONTENT-TYPE' => $content_type, 'CONTENT-ID' => $header->content_id, 'BODY' => $body, 'FILENAME' => $header->filename);
 }
Esempio n. 25
0
	function Connect($mailbox_id)
	{
		global $DB;
		$mailbox_id = IntVal($mailbox_id);
		$strSql =
				"SELECT MB.*, C.CHARSET as LANG_CHARSET ".
				"FROM b_mail_mailbox MB, b_lang L, b_culture C ".
				"WHERE MB.LID=L.LID AND C.ID=L.CULTURE_ID ".
				"	AND MB.ID=".$mailbox_id;
		$dbr = $DB->Query($strSql, false, "File: ".__FILE__."<br>Line: ".__LINE__);
		$dbr = new _CMailBoxDBRes($dbr);
		if(!$arMAILBOX_PARAMS = $dbr->Fetch())
			return CMailError::SetError("ERR_MAILBOX_NOT_FOUND", GetMessage("MAIL_CL_ERR_MAILBOX_NOT_FOUND"), GetMessage("MAIL_CL_ERR_MAILBOX_NOT_FOUND"));

		@set_time_limit(0);

		// https://support.google.com/mail/answer/47948
		if ($arMAILBOX_PARAMS["SERVER"] == 'pop.gmail.com')
			$arMAILBOX_PARAMS["LOGIN"] = '******' . $arMAILBOX_PARAMS["LOGIN"];

		$server = $arMAILBOX_PARAMS["SERVER"];
		if ($arMAILBOX_PARAMS['USE_TLS'] == 'Y' && strpos($server, 'tls://') === false)
		{
			$server = 'tls://' . $server;
		}

		$pop3_conn = &$this->pop3_conn;
		$pop3_conn = @fsockopen($server, $arMAILBOX_PARAMS["PORT"], $errno, $errstr, COption::GetOptionInt("mail", "connect_timeout", B_MAIL_TIMEOUT));

		CMailLog::AddMessage(
			Array(
				"MAILBOX_ID"=>$mailbox_id,
				"STATUS_GOOD"=>"Y",
				"MESSAGE"=>GetMessage("MAIL_CL_CONNECT_TO")." ".$arMAILBOX_PARAMS["SERVER"]
				)
			);

		if(!$pop3_conn || !is_resource($pop3_conn))
		{
			CMailLog::AddMessage(
				Array(
					"MAILBOX_ID"=>$mailbox_id,
					"STATUS_GOOD"=>"N",
					"MESSAGE"=>GetMessage("MAIL_CL_TIMEOUT")
					)
				);
			return CMailError::SetError("ERR_CONNECT_TIMEOUT", GetMessage("MAIL_CL_TIMEOUT"), "$errstr ($errno)");
		}

		$this->mailbox_id = $mailbox_id;
		if($arMAILBOX_PARAMS["CHARSET"]!='')
			$this->charset = $arMAILBOX_PARAMS["CHARSET"];
		else
			$this->charset = $arMAILBOX_PARAMS["LANG_CHARSET"];
		$this->use_md5 = $arMAILBOX_PARAMS["USE_MD5"];

		$session_id = md5(uniqid(""));
		$this->GetResponse();
		$greeting = $this->GetResponseString();

		if($this->use_md5=="Y" && preg_match("'(<.+>)'", $greeting, $reg))
		{
			$this->SendCommand("APOP ".$arMAILBOX_PARAMS["LOGIN"]." ".md5($reg[1].$arMAILBOX_PARAMS["PASSWORD"]));
			if(!$this->GetResponse())
				return CMailError::SetError("ERR_AFTER_USER", GetMessage("MAIL_CL_ERR_APOP"), $this->GetResponseString());
		}
		else
		{
			$this->SendCommand("USER ".$arMAILBOX_PARAMS["LOGIN"]);
			if(!$this->GetResponse())
				return CMailError::SetError("ERR_AFTER_USER", GetMessage("MAIL_CL_ERR_USER"), $this->GetResponseString());
			$this->SendCommand("PASS ".$arMAILBOX_PARAMS["PASSWORD"]);
			if(!$this->GetResponse())
				return CMailError::SetError("ERR_AFTER_PASS", GetMessage("MAIL_CL_ERR_PASSWORD"), $this->GetResponseString());
		}

		$this->SendCommand("STAT");
		if(!$this->GetResponse())
			return CMailError::SetError("ERR_AFTER_STAT", GetMessage("MAIL_CL_ERR_STAT"), $this->GetResponseString());

		$stat = trim($this->GetResponseBody());
		$arStat = explode(" ", $stat);
		$this->mess_count = $arStat[1];
		if($this->mess_count>0)
		{
			$this->mess_size = $arStat[2];
			$arLIST = array();

			if($arMAILBOX_PARAMS["MAX_MSG_SIZE"]>0)
			{
				$this->SendCommand("LIST");
				if(!$this->GetResponse(true))
					return CMailError::SetError("ERR_AFTER_LIST", "LIST command error", $this->GetResponseString());
				$list = $this->GetResponseBody();
				preg_match_all("'([0-9]+)[ ]+?(.+)'", $list, $arLIST_temp, PREG_SET_ORDER);

				for($i = 0, $n = count($arLIST_temp); $i < $n; $i++)
					$arLIST[IntVal($arLIST_temp[$i][1])] = IntVal($arLIST_temp[$i][2]);
			}

			$this->SendCommand("UIDL");
			if(!$this->GetResponse(true))
				return CMailError::SetError("ERR_AFTER_UIDL", GetMessage("MAIL_CL_ERR_UIDL"), $this->GetResponseString());

			$uidl = $this->GetResponseBody();
			preg_match_all("'([0-9]+)[ ]+?(.+)'", $uidl, $arUIDL_temp, PREG_SET_ORDER);

			$arUIDL = array();
			$cnt = count($arUIDL_temp);
			for ($i = 0; $i < $cnt; $i++)
				$arUIDL[md5($arUIDL_temp[$i][2])] = $arUIDL_temp[$i][1];

			$skipOldUIDL = $cnt < $this->mess_count;
			if ($skipOldUIDL)
			{
				AddMessage2Log(sprintf(
					"%s\n%s of %s",
					$this->response, $cnt, $this->mess_count
				), 'mail');
			}

			$arOldUIDL = array();
			if (count($arUIDL) > 0)
			{
				$strSql = 'SELECT ID FROM b_mail_message_uid WHERE MAILBOX_ID = ' . $mailbox_id;
				$db_res = $DB->query($strSql, false, 'File: '.__FILE__.'<br>Line: '.__LINE__);
				while ($ar_res = $db_res->fetch())
				{
					if (isset($arUIDL[$ar_res['ID']]))
						unset($arUIDL[$ar_res['ID']]);
					else if (!$skipOldUIDL)
						$arOldUIDL[] = $ar_res['ID'];
				}
			}

			while (count($arOldUIDL) > 0)
			{
				$ids = "'" . join("','", array_splice($arOldUIDL, 0, 1000)) . "'";
				$strSql = 'DELETE FROM b_mail_message_uid WHERE MAILBOX_ID = ' . $mailbox_id . ' AND ID IN (' . $ids . ')';
				$DB->query($strSql, false, 'File: '.__FILE__.'<br>Line: '.__LINE__);
			}

			$this->new_mess_count = 0;
			$this->deleted_mess_count = 0;
			$session_id = md5(uniqid(""));

			foreach($arUIDL as $msguid=>$msgnum)
			{
				if($arMAILBOX_PARAMS["MAX_MSG_SIZE"]<=0 || $arLIST[$msgnum]<=$arMAILBOX_PARAMS["MAX_MSG_SIZE"])
					$this->GetMessage($mailbox_id, $msgnum, $msguid, $session_id);

				if($arMAILBOX_PARAMS["DELETE_MESSAGES"]=="Y")
				{
					$this->DeleteMessage($msgnum);
					$this->deleted_mess_count++;
				}

				$this->new_mess_count++;
				if($arMAILBOX_PARAMS["MAX_MSG_COUNT"]>0 && $arMAILBOX_PARAMS["MAX_MSG_COUNT"]<=$this->new_mess_count)
					break;
			}
		}

		$this->SendCommand("QUIT");
		if(!$this->GetResponse())
			return CMailError::SetError("ERR_AFTER_QUIT", GetMessage("MAIL_CL_ERR_DISCONNECT"), $this->GetResponseString());

		fclose($pop3_conn);
		return true;
	}
Esempio n. 26
0
 function __IncludePHPTemplate(&$arResult, &$arParams, $parentTemplateFolder = "")
 {
     /** @noinspection PhpUnusedLocalVariableInspection */
     global $APPLICATION, $USER, $DB;
     if (!$this->__bInited) {
         return false;
     }
     // these vars are used in the template file
     /** @noinspection PhpUnusedLocalVariableInspection */
     $templateName = $this->__name;
     /** @noinspection PhpUnusedLocalVariableInspection */
     $templateFile = $this->__file;
     /** @noinspection PhpUnusedLocalVariableInspection */
     $templateFolder = $this->__folder;
     /** @noinspection PhpUnusedLocalVariableInspection */
     $componentPath = $this->__component->GetPath();
     $component =& $this->__component;
     if ($this->__fileAlt != '') {
         include $_SERVER["DOCUMENT_ROOT"] . $this->__fileAlt;
         return null;
     }
     $templateData = false;
     include $_SERVER["DOCUMENT_ROOT"] . $this->__file;
     /** @var \Freetrix\Main\Page\FrameHelper $frame */
     foreach ($this->frames as $frame) {
         if ($frame->isStarted() && !$frame->isEnded()) {
             $frame->end();
         }
     }
     if (!$this->frameMode) {
         $staticHtmlCache = \Freetrix\Main\Data\StaticHtmlCache::getInstance();
         $staticHtmlCache->markNonCacheable();
         if (defined("FX_COMPOSITE_DEBUG") && defined("USE_HTML_STATIC_CACHE") && USE_HTML_STATIC_CACHE == true) {
             AddMessage2Log("Template: " . $this->__file . "\n" . "Request URI: " . $_SERVER["REQUEST_URI"] . "\n" . "Script: " . (isset($_SERVER["REAL_FILE_PATH"]) ? $_SERVER["REAL_FILE_PATH"] : $_SERVER["SCRIPT_NAME"]), "composite");
         }
     }
     $component_epilog = $this->__folder . "/component_epilog.php";
     if (file_exists($_SERVER["DOCUMENT_ROOT"] . $component_epilog)) {
         //These will be available with extract then component will
         //execute epilog without template
         $component->SetTemplateEpilog(array("epilogFile" => $component_epilog, "templateName" => $this->__name, "templateFile" => $this->__file, "templateFolder" => $this->__folder, "templateData" => $templateData));
     }
     return null;
 }
Esempio n. 27
0
 protected function prepareAnswer($result)
 {
     if (!defined("BX_UTF")) {
         $result = CharsetConverter::ConvertCharset($result, "utf-8", LANG_CHARSET);
     }
     $res = CUtil::JsObjectToPhp($result);
     if (!$res) {
         AddMessage2Log('Strange answer from Network! ' . $result . print_r($res, 1));
     }
     return $res;
 }
Esempio n. 28
0
 /**
  * Function executes the component. Returns the result of it's execution.
  *
  * <p>Note: component must be inited by initComponent method.</p>
  * @param string $componentTemplate
  * @param array[string]mixed $arParams
  * @param CFreetrixComponent $parentComponent
  * @return mixed
  *
  */
 public final function includeComponent($componentTemplate, $arParams, $parentComponent)
 {
     if (!$this->__bInited) {
         return null;
     }
     if ($componentTemplate !== false) {
         $this->setTemplateName($componentTemplate);
     }
     if (is_object($parentComponent) && $parentComponent instanceof cfreetrixcomponent) {
         $this->__parent = $parentComponent;
     }
     if ($arParams["CACHE_TYPE"] != "Y" && $arParams["CACHE_TYPE"] != "N") {
         $arParams["CACHE_TYPE"] = "A";
     }
     if ($this->classOfComponent) {
         /** @var CFreetrixComponent $component  */
         $component = new $this->classOfComponent($this);
         $component->arParams = $component->onPrepareComponentParams($arParams);
         $component->__prepareComponentParams($component->arParams);
         $component->onIncludeComponentLang();
         $result = $component->executeComponent();
         $this->__arIncludeAreaIcons = $component->__arIncludeAreaIcons;
         $frameMode = $component->frameMode;
     } else {
         $this->__prepareComponentParams($arParams);
         $this->arParams = $arParams;
         $this->includeComponentLang();
         $result = $this->__IncludeComponent();
         $frameMode = $this->frameMode;
     }
     if (!$frameMode) {
         $staticHtmlCache = \Freetrix\Main\Data\StaticHtmlCache::getInstance();
         $staticHtmlCache->markNonCacheable();
         if (defined("FX_COMPOSITE_DEBUG") && defined("USE_HTML_STATIC_CACHE") && USE_HTML_STATIC_CACHE == true) {
             AddMessage2Log("Component: " . $this->__name . "\n" . "Request URI: " . $_SERVER["REQUEST_URI"] . "\n" . "Script: " . (isset($_SERVER["REAL_FILE_PATH"]) ? $_SERVER["REAL_FILE_PATH"] : $_SERVER["SCRIPT_NAME"]), "composite");
         }
     }
     return $result;
 }
Esempio n. 29
0
 public function Query($strSql, $bIgnoreErrors = false, $error_position = "", $arOptions = array())
 {
     global $DB;
     $this->DoConnect();
     $this->db_Error = "";
     if ($this->DebugToFile || $DB->ShowSqlStat) {
         $start_time = microtime(true);
     }
     //We track queries for DML statements
     //and when there is no one we can choose
     //to run query against master connection
     //or replicated one
     $connectionPool = \Bitrix\Main\Application::getInstance()->getConnectionPool();
     if ($connectionPool->isMasterOnly()) {
         //We requested to process all queries
         //by master connection
     } elseif ($this->bModuleConnection) {
         //In case of dedicated module database
         //were is nothing to do
     } elseif (isset($arOptions["fixed_connection"])) {
         //We requested to process this query
         //by current connection
     } elseif ($this->bNodeConnection) {
         //It is node so nothing to do
     } else {
         if (isset($arOptions["ignore_dml"])) {
             $connectionPool->ignoreDml(true);
         }
         $connection = $connectionPool->getSlaveConnection($strSql);
         if (isset($arOptions["ignore_dml"])) {
             $connectionPool->ignoreDml(false);
         }
         if ($connection !== null) {
             if (!isset($this->obSlave)) {
                 $nodeId = $connection->getNodeId();
                 ob_start();
                 $conn = CDatabase::GetDBNodeConnection($nodeId, true);
                 ob_end_clean();
                 if (is_object($conn)) {
                     $this->obSlave = $conn;
                 } else {
                     self::$arNodes[$nodeId]["ONHIT_ERROR"] = true;
                     CClusterDBNode::SetOffline($nodeId);
                 }
             }
             if (is_object($this->obSlave)) {
                 return $this->obSlave->Query($strSql, $bIgnoreErrors, $error_position, $arOptions);
             }
         }
     }
     $result = $this->QueryInternal($strSql);
     if ($this->DebugToFile || $DB->ShowSqlStat) {
         /** @noinspection PhpUndefinedVariableInspection */
         $exec_time = round(microtime(true) - $start_time, 10);
         if ($DB->ShowSqlStat) {
             $DB->addDebugQuery($strSql, $exec_time, $connectionPool->isSlavePossible() ? $this->node_id : -1);
         }
         if ($this->DebugToFile) {
             $this->startSqlTracker()->writeFileLog($strSql, $exec_time, "CONN: " . $this->getThreadId());
         }
     }
     if (!$result) {
         $this->db_Error = $this->GetError();
         $this->db_ErrorSQL = $strSql;
         if (!$bIgnoreErrors) {
             AddMessage2Log($error_position . " MySql Query Error: " . $strSql . " [" . $this->db_Error . "]", "main");
             if ($this->DebugToFile) {
                 $this->startSqlTracker()->writeFileLog("ERROR: " . $this->db_Error, 0, "CONN: " . $this->getThreadId());
             }
             if ($this->debug || @session_start() && $_SESSION["SESS_AUTH"]["ADMIN"]) {
                 echo $error_position . "<br><font color=#ff0000>MySQL Query Error: " . htmlspecialcharsbx($strSql) . "</font>[" . htmlspecialcharsbx($this->db_Error) . "]<br>";
             }
             $error_position = preg_replace("#<br[^>]*>#i", "\n", $error_position);
             SendError($error_position . "\nMySQL Query Error:\n" . $strSql . " \n [" . $this->db_Error . "]\n---------------\n\n");
             if (file_exists($_SERVER["DOCUMENT_ROOT"] . BX_PERSONAL_ROOT . "/php_interface/dbquery_error.php")) {
                 include $_SERVER["DOCUMENT_ROOT"] . BX_PERSONAL_ROOT . "/php_interface/dbquery_error.php";
             } elseif (file_exists($_SERVER["DOCUMENT_ROOT"] . "/bitrix/modules/main/include/dbquery_error.php")) {
                 include $_SERVER["DOCUMENT_ROOT"] . "/bitrix/modules/main/include/dbquery_error.php";
             } else {
                 die("MySQL Query Error!");
             }
             die;
         }
         return false;
     }
     $res = new CDBResult($result);
     $res->DB = $this;
     if ($DB->ShowSqlStat) {
         $res->SqlTraceIndex = count($DB->arQueryDebug) - 1;
     }
     return $res;
 }
Esempio n. 30
0
 function ProcessTask($ID)
 {
     global $DB, $APPLICATION;
     $ID = IntVal($ID);
     $uniq = $APPLICATION->GetServerUniqID();
     $uniq = "X" . $uniq . "_ctask";
     $STATUS = "0";
     // locking the task
     if (!CControllerAgent::_Lock($uniq)) {
         AddMessage2Log('ERROR_GET_LOCK');
         return $STATUS;
     }
     // selecting task
     $strSql = "SELECT T.*, M.SHARED_KERNEL " . "FROM b_controller_task T LEFT JOIN b_controller_member M ON T.CONTROLLER_MEMBER_ID=M.ID " . "WHERE T.ID='" . $ID . "' AND T.STATUS<>'Y'";
     $db_task = $DB->Query($strSql);
     if ($ar_task = $db_task->Fetch()) {
         $arControllerLog = array('CONTROLLER_MEMBER_ID' => $ar_task["CONTROLLER_MEMBER_ID"], 'TASK_ID' => $ar_task['ID'], 'STATUS' => 'Y');
         $RESULT = '';
         $STATUS = 'Y';
         unset($INIT_EXECUTE_PARAMS);
         switch ($ar_task['TASK_ID']) {
             case 'SET_SETTINGS':
                 $arControllerLog['NAME'] = 'SET_SETTINGS';
                 $APPLICATION->ResetException();
                 $res = CControllerMember::SetGroupSettings($ar_task["CONTROLLER_MEMBER_ID"], $ar_task['ID']);
                 if ($res !== false) {
                     $RESULT = $res;
                 } else {
                     $e = $APPLICATION->GetException();
                     $STATUS = "F";
                     $RESULT = $e->GetString();
                     $arControllerLog['STATUS'] = 'N';
                 }
                 break;
             case 'CLOSE_MEMBER':
                 $arControllerLog['NAME'] = 'SITE_CLOSING';
                 $APPLICATION->ResetException();
                 $res = CControllerMember::CloseMember($ar_task["CONTROLLER_MEMBER_ID"], $ar_task['INIT_EXECUTE_PARAMS']);
                 if ($res !== false) {
                     $RESULT = $res;
                 } else {
                     $e = $APPLICATION->GetException();
                     $STATUS = "F";
                     $RESULT = $e->GetString();
                     $arControllerLog['STATUS'] = 'N';
                 }
                 break;
             case 'UPDATE':
                 $arControllerLog['NAME'] = 'SITE_UPDATE';
                 $APPLICATION->ResetException();
                 if ($ar_task["SHARED_KERNEL"] == "Y") {
                     $STATUS = "F";
                     $RESULT = GetMessage("CTRLR_TASK_ERR_KERNEL");
                     $arControllerLog['STATUS'] = 'N';
                 } else {
                     $command = 'require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/classes/general/update_client.php");';
                     if ($ar_task["STATUS"] == "P" && strlen($ar_task["INIT_EXECUTE_PARAMS"]) > 0) {
                         $command .= 'echo trim(CUpdateControllerSupport::Update("' . EscapePHPString($ar_task["INIT_EXECUTE_PARAMS"]) . '"));';
                     } else {
                         $command .= 'echo trim(CUpdateControllerSupport::Update(""));';
                     }
                     $res = CControllerMember::RunCommand($ar_task["CONTROLLER_MEMBER_ID"], $command, array(), $ar_task['ID']);
                     if ($res !== false) {
                         if (($p = strpos($res, "|")) > 0) {
                             $result_code = substr($res, 0, $p);
                             $RESULT = substr($res, $p + 1);
                         } else {
                             $result_code = $res;
                             $RESULT = $res;
                         }
                         if ($result_code == 'ERR') {
                             $STATUS = "F";
                             $arControllerLog['STATUS'] = 'N';
                         } elseif ($result_code == 'STP0') {
                             $STATUS = "P";
                         } elseif ($result_code != 'FIN') {
                             $STATUS = "P";
                             $INIT_EXECUTE_PARAMS = $result_code;
                         } else {
                             $RESULT = GetMessage("CTRLR_TASK_UPD_COMPL");
                         }
                     } else {
                         $STATUS = "F";
                         $e = $APPLICATION->GetException();
                         $RESULT = $e->GetString();
                         $arControllerLog['STATUS'] = 'N';
                     }
                 }
                 break;
             case 'COUNTERS_UPDATE':
                 $arControllerLog['NAME'] = 'UPDATE_COUNTERS';
                 $APPLICATION->ResetException();
                 $res = CControllerMember::UpdateCounters($ar_task["CONTROLLER_MEMBER_ID"], $ar_task['ID']);
                 $RESULT = '';
                 if ($res !== false) {
                     foreach ($res as $k => $v) {
                         $RESULT .= "{$k}={$v};\r\n";
                     }
                 } else {
                     $e = $APPLICATION->GetException();
                     $STATUS = "F";
                     $RESULT = $e->GetString();
                     $arControllerLog['STATUS'] = 'N';
                 }
                 break;
             case 'REMOTE_COMMAND':
                 $APPLICATION->ResetException();
                 $arControllerLog['NAME'] = 'REMOTE_COMMAND';
                 if (strlen($ar_task['INIT_EXECUTE_PARAMS']) > 0) {
                     $ar_task['INIT_EXECUTE_PARAMS'] = unserialize($ar_task['INIT_EXECUTE_PARAMS']);
                 } else {
                     $ar_task['INIT_EXECUTE_PARAMS'] = array();
                 }
                 $res = CControllerMember::RunCommand($ar_task["CONTROLLER_MEMBER_ID"], $ar_task['INIT_EXECUTE'], $ar_task['INIT_EXECUTE_PARAMS'], $ar_task['ID']);
                 if ($res !== false) {
                     $RESULT = $res;
                 } else {
                     $STATUS = "F";
                     $e = $APPLICATION->GetException();
                     $RESULT = $e->GetString();
                     $arControllerLog['STATUS'] = 'N';
                 }
                 break;
             case 'SEND_FILE':
                 $APPLICATION->ResetException();
                 $arControllerLog['NAME'] = 'SEND_FILE';
                 break;
         }
         if (!isset($arControllerLog['DESCRIPTION'])) {
             $arControllerLog['DESCRIPTION'] = $RESULT;
         }
         CControllerLog::Add($arControllerLog);
         // updating status
         $arUpdateFields = array("STATUS" => $STATUS, "~DATE_EXECUTE" => $DB->CurrentTimeFunction(), "RESULT_EXECUTE" => $RESULT, "INDEX_SALT" => rand());
         if (isset($INIT_EXECUTE_PARAMS)) {
             $arUpdateFields["INIT_EXECUTE_PARAMS"] = $INIT_EXECUTE_PARAMS;
         }
         $arUpdateBinds = array();
         $strUpdate = $DB->PrepareUpdateBind("b_controller_task", $arUpdateFields, "", false, $arUpdateBinds);
         $strSql = "UPDATE b_controller_task SET " . $strUpdate . " WHERE ID=" . $ID;
         $arBinds = array();
         foreach ($arUpdateBinds as $field_id) {
             $arBinds[$field_id] = $arUpdateFields[$field_id];
         }
         $DB->QueryBind($strSql, $arBinds);
     }
     // unlocking
     CControllerAgent::_UnLock($uniq);
     return $STATUS;
 }