Your IP : 216.73.216.86


Current Path : /var/www/homesaver/www/bitrix/modules/webdebug.excel/classes/general/
Upload File :
Current File : /var/www/homesaver/www/bitrix/modules/webdebug.excel/classes/general/CWebdebugExcel1.php

<?

IncludeModuleLangFile(__FILE__);

class CWebdebugExcel {

	var $objPHPExcel;
	
	/**
	 *	Debug dump
	 */
	function p($arData, $Return=false, $Clear=false) {
		if ($Clear) {
			$strResult = "";
		} else {
			$strResult = "<style type='text/css'>pre {background:none repeat scroll 0 0 #FAFAFA; border-color:#AAB4BE #AAB4BE #AAB4BE #B4B4B4; border-style:dotted dotted dotted solid; border-width:1px 1px 1px 20px; font:normal 11px \"Courier New\",\"Courier\",monospace; margin:10px 0; padding:5px 0 5px 10px; text-align:left; white-space:pre-wrap;}</style>";
		}
		if (is_array($arData) && empty($arData)) $arData = "--- Array is empty ---";
		if ($arData===false) $arData = "false"; elseif ($arData===true) $arData = "true";
		if (!$Clear) $strResult .= "<pre>";
		$strResult .= print_r($arData,true);
		if (!$Clear) $strResult .= "</pre>";
		if ($Return) {
			return $strResult;
		} else {
			print $strResult;
		}
	}
	
	/**
	 *	Debug dump to file
	 */
	function l($arData){
		if (COption::GetOptionString('webdebug.excel','log_errors')=='Y') {
			$arData = self::p($arData,true,true);
			$FileName = $_SERVER['DOCUMENT_ROOT']."/upload/!webdebug_excel_log.txt";
			$OptionFileName = COption::GetOptionString('webdebug.excel','log_filename');
			if (trim($OptionFileName)!='' && substr($OptionFileName,0,1)=='/' && substr($OptionFileName,-1)!='/') {
				$FileName = $_SERVER['DOCUMENT_ROOT'].$OptionFileName;
			}
			$handle = fopen($FileName, "a+");
			@flock ($handle, LOCK_EX);
			fwrite ($handle, "[".date("d.m.Y H:i:s")."] ".$arData."\r\n");
			@flock ($handle, LOCK_UN);
			fclose($handle);
		}
	}

	/**
	 *	Creating new object
	 *	@param string $FileName XLS filename
	 */
	function __construct($FileName) {
		if (defined("BX_UTF") && BX_UTF===true) {
			ini_set("mbstring.func_overload", "0");
			ini_set("mbstring.internal_encoding", "CP1251");
		}
		require_once ($_SERVER["DOCUMENT_ROOT"].'/bitrix/modules/webdebug.excel/include/phpexcel/PHPExcel.php');
		if (file_exists($FileName)) {
			$this->objPHPExcel = PHPExcel_IOFactory::load($FileName);
		} else {
			print("File not exists!");
		}
		if (defined("BX_UTF") && BX_UTF===true) {
			ini_set("mbstring.func_overload", "2");
			ini_set("mbstring.internal_encoding", "UTF-8");
		}
	}

	/**
	 *	Get sheets list in XLS file
	 *	@param boolean $ShowHidden Flag indicates show || hide hidden sheets
	 */
	function GetSheetList($ShowHidden=false) {
		$arResult = array();
		$SheetCount = $this->objPHPExcel->getSheetCount();
		if ($SheetCount>0) {
			for ($i=0; $i<$SheetCount; $i++) {
				if ($this->objPHPExcel->getSheet($i)->getSheetState()=="visible" || $ShowHidden===true) {
					$arResult[$i] = $this->objPHPExcel->getSheet($i)->getTitle();
					if (!defined("BX_UTF") && BX_UTF!==true) {
						global $APPLICATION;
						$arResult[$i] = $APPLICATION->ConvertCharset($arResult[$i], "UTF-8", "CP1251");
					}
				}
			}
		}
		return $arResult;
	}
	
	/**
	 *	Get header array for any sheet
	 *	@param int $SheetIndex Sheet index to process
	 *	@param int $HeaderColumn Column to start find header
	 *	@param int $HeaderRow Row containing header
	 */
	function GetSheetHeaders($SheetIndex, $HeaderColumn, $HeaderRow) {
		$arResult = array();
		$Value = "";
		do {
			$Value = trim($this->objPHPExcel->getSheet($SheetIndex)->getCellByColumnAndRow($HeaderColumn,$HeaderRow)->getValue());
			if ($Value!=="") {
				if (!defined("BX_UTF") && BX_UTF!==true) {
					global $APPLICATION;
					$Value = $APPLICATION->ConvertCharset($Value, "UTF-8", "CP1251");
				}
				$arResult[] = array(
					"NAME" => $Value,
					"SHEET" => $SheetIndex,
					"COLUMN" => $HeaderColumn,
					"ROW" => $HeaderRow,
				);
				$HeaderColumn++;
			} else {
				break;
			}
		} while(1);
		return $arResult;
	}
	
	/**
	 *	Get lines count in file
	 */
	function GetLinesCount($SheetIndex, $ElementRow) {
		return IntVal($this->objPHPExcel->getSheet($SheetIndex)->getHighestRow()) - IntVal($ElementRow) + 1;
	}
	
	function GetCellBackgroundColor($SheetIndex, $Column, $Row) {
		$Cell = PHPExcel_Cell::stringFromColumnIndex($Column).$Row;
		return ToUpper($this->objPHPExcel->getSheet($SheetIndex)->getStyle($Cell)->getFill()->getStartColor()->getRGB());
	}
	
	function GetRichTextValue($Value, $SheetIndex, $Column, $Row) {
		$arValueElemens = $Value->getRichTextElements();
		$CellBackground = self::GetCellBackgroundColor($SheetIndex, $Column, $Row);
		$strResult = '';
		foreach ($arValueElemens as $objItem) {
			$objFont = $objItem->getFont();
			if (!is_object($objFont)) continue;
			$Color = $objFont->getColor()->getRGB();
			$IsBold = $objFont->getBold();
			$IsItalic = $objFont->getItalic();
			$IsUnderline = !in_array($objFont->getUnderline(),array('','none'));
			if ($Color!='000000') $strResult .= '<span style="color:#'.$Color.'">';
			if ($IsBold) $strResult .= '<b>';
			if ($IsItalic) $strResult .= '<i>';
			if ($IsUnderline) $strResult .= '<u>'.$IsUnderline;
			$strResult .= str_replace('<br />','<br/>',nl2br($objItem->getText()));
			if ($IsUnderline) $strResult .= '</u>';
			if ($IsItalic) $strResult .= '</i>';
			if ($IsBold) $strResult .= '</b>';
			if ($Color!='000000') $strResult .= '</span>';
		}
		return $strResult;
	}
	
	/**
	 *	Get cell value
	 */
	function GetValue($SheetIndex, $Column, $Row, $Trim=true, $UseHtmlFormatting=false) {
		$Value = $this->objPHPExcel->getSheet($SheetIndex)->getCellByColumnAndRow($Column,$Row)->getValue();
		if ($UseHtmlFormatting && gettype($Value)=='object') {
			$Value = self::GetRichTextValue($Value, $SheetIndex, $Column, $Row);
		}
		if (!defined("BX_UTF") && BX_UTF!==true) {
			global $APPLICATION;
			$Value = $APPLICATION->ConvertCharset($Value, "UTF-8", "CP1251");
		}
		if ($Trim!=false) {
			$Value = trim($Value);
		}
		return $Value;
	}
	
	/**
	 *	Get array of IBlocks
	 *	@param boolean $GroupByType Flag indicates that result will be grouped by infoblock types
	 *	@param boolean $ShowInActive Flag indicates select inactive or not
	 */
	function GetIBlockList($GroupByType=true, $ShowInActive=false) {
		$arResult = array();
		if (CModule::IncludeModule("iblock")) {
			if ($GroupByType!==false) {
				$resIBlockTypes = CIBlockType::GetList(array(),array());
				while ($arIBlockType = $resIBlockTypes->GetNext(false,false)) {
					$arIBlockTypeLang = CIBlockType::GetByIDLang($arIBlockType["ID"], LANGUAGE_ID, false);
					$arResult[$arIBlockType["ID"]] = array(
						"NAME" => $arIBlockTypeLang["NAME"],
						"ITEMS" => array(),
					);
				}
			}
			$arFilter = array();
			if ($ShowInActive!==true) $arFilter["ACTIVE"] = "Y";
			$resIBlock = CIBlock::GetList(array("SORT"=>"ASC"),$arFilter);
			while ($arIBlock = $resIBlock->GetNext(false,false)) {
				if ($GroupByType!==false) {
					$arResult[$arIBlock["IBLOCK_TYPE_ID"]]["ITEMS"][] = $arIBlock;
				} else {
					$arResult[] = $arIBlock;
				}
			}
		}
		return $arResult;
	}
	
	/**
	 *	Get list of currencies
	 */
	function GetCurrencyList() {
		$arResult = array();
		if (CModule::IncludeModule("currency")) {
			$resCurrency = CCurrency::GetList($by='name', $order='asc', LANGUAGE_ID);
			while ($arCurrency = $resCurrency->GetNext(false,false)) {
				$arCurrency["DEAULT"] = FloatVal($arCurrency["AMOUNT"])==1 ? "Y" : "N";
				$arResult[ToLower($arCurrency["CURRENCY"])] = $arCurrency;
			}
		}
		return $arResult;
	}
	
	/**
	 *	Get list of prices
	 */
	function GetPriceTypeList() {
		$arResult = array();
		if (CModule::IncludeModule("catalog")) {
			$resPrices = CCatalogGroup::GetList(array("SORT"=>"ASC"));
			while ($arPrice = $resPrices->GetNext(false,false)) {
				$arResult[] = $arPrice;
			}
		}
		return $arResult;
	}
	
	/**
	 *	Get list of stores
	 */
	function GetStoresTypeList() {
		$arResult = array();
		if (CModule::IncludeModule("catalog") && class_exists('CCatalogStore')) {
			$resStores = CCatalogStore::GetList(array("SORT"=>"ASC"));
			while ($arStore = $resStores->GetNext(false,false)) {
				$arResult[] = $arStore;
			}
		}
		return $arResult;
	}
	
	/**
	 *	Get IBlock property list
	 *	@param int $IBlockID Infoblock ID
	 */
	function GetIBlockProps($IBlockID,$Grouped=false) {
		$arResult = array();
		if (CModule::IncludeModule("iblock")) {
			$resProps = CIBlock::GetProperties($IBlockID, array("SORT"=>"ASC"), array(""));
			while ($arProp = $resProps->GetNext(false,false)) {
				// get enum values
				if ($arProp["CODE"]=="WD_EXCEL_IMPORT_ID") continue;
				if ($arProp["PROPERTY_TYPE"]=="L") {
					$arProp["ENUMS"] = array();
					$resPropEnum = CIBlockPropertyEnum::GetList(array("SORT"=>"ASC", "VALUE"=>"ASC"),array("IBLOCK_ID"=>$IBlockID,"PROPERTY_ID"=>$arProp["ID"]));
					while ($arPropEnum = $resPropEnum->GetNext(false,false)) {
						$arProp["ENUMS"][] = $arPropEnum;
					}
				}
				if ($Grouped) {
					$arResult[$arProp["ID"]] = $arProp;
				} else {
					$arResult[] = $arProp;
				}
			}
		}
		return $arResult;
	}

	/**
	 *	Get IBlock section property list
	 *	@param int $IBlockID Infoblock ID
	 */
	function GetIBlockSectionProps($IBlockID) {
		$arResult = array();
		if (CModule::IncludeModule("iblock")) {
			$resProps = CUserTypeEntity::GetList(array('SORT'=>'ASC'),array('ENTITY_ID'=>'IBLOCK_'.$IBlockID.'_SECTION'));
			while ($arProp = $resProps->GetNext(false,false)) {
				$arResult[$arProp["FIELD_NAME"]] = $arProp;
			}
		}
		return $arResult;
	}
	
	/**
	 *	Get IBlock fields
	 */
	function GetIBlockFields($IBlockID) {
		if (CModule::IncludeModule("iblock")) {
			return CIBlock::GetFields($IBlockID);
		}
		return false;
	}
	
	/**
	 *	Get IBlock translit settings
	 */
	function GetIBlockTranslitSettings($arIBlockFields, $ForSection=false) {
		$ArrayKey = $ForSection?"SECTION_CODE":"CODE";
		if (isset($arIBlockFields[$ArrayKey]) && is_array($arIBlockFields[$ArrayKey]) && $arIBlockFields[$ArrayKey]['DEFAULT_VALUE']) {
			$arIBlockFields[$ArrayKey]['DEFAULT_VALUE']['IS_REQUIRED'] = $arIBlockFields[$ArrayKey]['IS_REQUIRED'];
			return $arIBlockFields[$ArrayKey]['DEFAULT_VALUE'];
		}
		return false;
	}
	
	function PanelCreateHandler() {
		global $APPLICATION;
		if($APPLICATION->GetGroupRight("webdebug.excel") >= "R") {
			$WebdebugExcelImportURL = $APPLICATION->GetPopupLink(
				array(
					"URL" => "/bitrix/admin/webdebug_excel_ajax_start.php?lang=".LANGUAGE_ID."&public=Y&bxpublic=Y&str_URI=".urlencode($APPLICATION->GetCurPageParam("", array("clear_cache", "sessid", "login", "logout", "register", "forgot_password", "change_password", "confirm_registration", "confirm_code", "confirm_user_id", "bitrix_include_areas", "show_page_exec_time", "show_include_exec_time", "show_sql_stat", "show_link_stat")))."&site=".SITE_ID,
					"PARAMS" => array(
						'width' => COption::GetOptionString("webdebug.excel","popup_width"),
						'height' => COption::GetOptionString("webdebug.excel","popup_height"),
						'resize' => false,
						'resizable' => false,
					)
				)
			);
			$APPLICATION->AddPanelButton(array(
				"HREF" => "javascript:".$WebdebugExcelImportURL,
				"ICON" => "icon-wizard",
				"TEXT" => GetMessage("WEBDEBUG_EXCEL_BUTTON_TEXT"),
				"MAIN_SORT" => "1000",
				"SORT" => "1000",
				"RESORT_MENU" => true,
				"HINT" => array(
					"TITLE" => GetMessage("WEBDEBUG_EXCEL_BUTTON_HINT_TITLE"),
					"TEXT" => GetMessage("WEBDEBUG_EXCEL_BUTTON_HINT_TEXT"),
				),
			));
		}
	}
	
	///////////////////////////////////////////////
	// STATUS FUNCTIONS
	///////////////////////////////////////////////
	function SetSheetImported($ProfileID, $SheetIndex) {
		$_SESSION["WEBDEBUG"]["EXCEL"]["STATUS"][$ProfileID][$SheetIndex]["DONE"] = "Y";
	}
	function GetSheetImported($ProfileID, $SheetIndex) {
		return $_SESSION["WEBDEBUG"]["EXCEL"]["STATUS"][$ProfileID][$SheetIndex]["DONE"]=="Y";
	}
	
	function GetLineImported($ProfileID, $SheetIndex, $LineIndex) {
		return $LineIndex <= IntVal($_SESSION["WEBDEBUG"]["EXCEL"]["STATUS"][$ProfileID][$SheetIndex]["LAST_LINE"]);
	}
	function SetLineImported($ProfileID, $SheetIndex, $LineIndex) {
		$_SESSION["WEBDEBUG"]["EXCEL"]["STATUS"][$ProfileID][$SheetIndex]["LAST_LINE"] = $LineIndex;
	}
	
	function _MakeFileArray($path, $mimetype=false)
    {
        $io = CBXVirtualIo::GetInstance();
        $arFile = Array();

        if(intval($path)>0)
        {
            $res = CFile::GetByID($path);
            if($ar = $res->Fetch())
            {
                $bExternalStorage = false;
                foreach(GetModuleEvents("main", "OnMakeFileArray", true) as $arEvent)
                {
                    if(ExecuteModuleEventEx($arEvent, array($ar, &$arFile)))
                    {
                        $bExternalStorage = true;
                        break;
                    }
                }

                if(!$bExternalStorage)
                {
                    $arFile["name"] = (strlen($ar['ORIGINAL_NAME'])>0?$ar['ORIGINAL_NAME']:$ar['FILE_NAME']);
                    $arFile["size"] = $ar['FILE_SIZE'];
                    $arFile["type"] = $ar['CONTENT_TYPE'];
                    $arFile["description"] = $ar['DESCRIPTION'];
                    $arFile["tmp_name"] = $io->GetPhysicalName(preg_replace("#[\\\\\\/]+#", "/", $_SERVER['DOCUMENT_ROOT'].'/'.(COption::GetOptionString('main', 'upload_dir', 'upload')).'/'.$ar['SUBDIR'].'/'.$ar['FILE_NAME']));
                }
                return $arFile;
            }
        }

        $path = preg_replace("#(?<!:)[\\\\\\/]+#", "/", $path);

        if(strlen($path) == 0 || $path == "/")
            return NULL;

        if(preg_match("#^(http[s]?)://#", $path))
        {
            $temp_path = '';
            $bExternalStorage = false;
            foreach(GetModuleEvents("main", "OnMakeFileArray", true) as $arEvent)
            {
                if(ExecuteModuleEventEx($arEvent, array($path, &$temp_path)))
                {
                    $bExternalStorage = true;
                    break;
                }
            }

            if(!$bExternalStorage)
            {
                $temp_path = CFile::GetTempName('', bx_basename($path));
                $ob = new CHTTP;
								$ob->http_timeout = 10;
                $ob->follow_redirect = true;
                if($ob->Download($path, $temp_path)) {
									$arFile = self::_MakeFileArray($temp_path);
								}
            }
            elseif($temp_path)
            {
                $arFile = self::_MakeFileArray($temp_path);
            }
        }
        elseif(preg_match("#^(ftp[s]?|php)://#", $path))
        {
            if($fp = fopen($path,"rb"))
            {
                $content = "";
                while(!feof($fp))
                    $content .= fgets($fp, 4096);

                if(strlen($content) > 0)
                {
                    $temp_path = CFile::GetTempName('', bx_basename($path));
                    if (RewriteFile($temp_path, $content))
                        $arFile = self::_MakeFileArray($temp_path);
                }

                fclose($fp);
            }
        }
        else
        {
            if(!file_exists($path))
            {
                if (file_exists($_SERVER["DOCUMENT_ROOT"].$path))
                    $path = $_SERVER["DOCUMENT_ROOT"].$path;
                else
                    return NULL;
            }

            if(is_dir($path))
                return NULL;

            $arFile["name"] = $io->GetLogicalName(bx_basename($path));
            $arFile["size"] = filesize($path);
            $arFile["tmp_name"] = $path;
            $arFile["type"] = $mimetype;

            if(strlen($arFile["type"])<=0)
                $arFile["type"] = CFile::GetContentType($path, true);
        }

        if(strlen($arFile["type"])<=0)
            $arFile["type"] = "unknown";

        return $arFile;
    }
	
	function MakeFileArray($Value, $Easy=false) {
		if (trim($Value)=="") return false;
		$L1 = substr($Value,0,1);
		$L2 = substr($Value,1,1);
		if ($L1=="/" && $L2!="/") {
			if (file_exists($_SERVER["DOCUMENT_ROOT"].SITE_DIR.$Value)) {
				$Value = self::_MakeFileArray($_SERVER["DOCUMENT_ROOT"].SITE_DIR.$Value);
			}
		} elseif ($L1=="/" && $L2=="/") {
			$Value = self::_MakeFileArray("http:".$Value);
		} elseif (substr($Value,0,7)=="http://") {
			$Value = self::_MakeFileArray($Value);
		}
		if (!$Easy) {
			$Value = array("VALUE"=>$Value,"DESCRIPTION"=>"");
		}
		return $Value;
	}
	
	function ProcessSingleValue($Value, $strType, $PropertyID, $arIBlockProps, $arParams) {
		$PropType = $arIBlockProps[$PropertyID]["PROPERTY_TYPE"];
		$Value = trim($Value);
		if ($PropType=="L") {
			if (!in_array($strType,array("LIST_VALUE","LIST_XML_ID","FLAG"))) $strType = "LIST_VALUE";
			$arEnums = $arIBlockProps[$PropertyID]["ENUMS"];
			if ($strType=="LIST_VALUE") {
				$Found = false;
				foreach ($arEnums as $Key => $arEnum) {
					if (ToLower($arEnum["VALUE"])==ToLower($Value)) {
						$Value = $arEnum["ID"];
						$Found = true;
						break;
					}
				}
				if (!$Found) {
					$arEnumFields = array(
						'PROPERTY_ID' => $PropertyID,
						'VALUE' => $Value,
					);
					$IBlockPropertyEnum = new CIBlockPropertyEnum;
					$Value = $IBlockPropertyEnum->Add($arEnumFields);
				}
			} elseif ($strType=="LIST_XML_ID") {
				$Found = false;
				foreach ($arEnums as $Key => $arEnum) {
					if ($arEnum["XML_ID"]==$Value) {
						$Value = $arEnum["ID"];
						$Found = true;
						break;
					}
				}
				if (!$Found) {
					$arEnumFields = array(
						'PROPERTY_ID' => $PropertyID,
						'VALUE' => $Value,
						'XML_ID' => $Value,
					);
					$IBlockPropertyEnum = new CIBlockPropertyEnum;
					$Value = $IBlockPropertyEnum->Add($arEnumFields);
				}
			} elseif ($strType=="FLAG" && trim($Value)!="" && $Value!="0" && $Value!="-") {
				$Found = false;
				foreach ($arEnums as $Key => $arEnum) {
					$Value = $arEnum["ID"];
					$Found = true;
					break;
				}
				if (!$Found) {
					$arEnumFields = array(
						'PROPERTY_ID' => $PropertyID,
						'VALUE' => $Value,
						'XML_ID' => 'Y',
					);
					$IBlockPropertyEnum = new CIBlockPropertyEnum;
					$Value = $IBlockPropertyEnum->Add($arEnumFields);
				}
			}
		} elseif($PropType=="N") {
			if ($strType=="FLOAT") {
				$Value = str_replace(',','.',$Value);
				$Value = FloatVal($Value);
			} else {
				$Value = IntVal($Value);
			}
		} elseif($PropType=="S") {
			if ($arIBlockProps[$PropertyID]['USER_TYPE']=='HTML') {
				$Value = array("VALUE" => Array ("TEXT"=>$Value, "TYPE"=>($strType=='HTML'?'html':'text')));
			} elseif ($arIBlockProps[$PropertyID]['USER_TYPE']=='DateTime') {
				$DateFormat = FORMAT_DATE;
				self::l($arParams);
				if ($arParams['DATE_FORMAT']=='full') {
					$DateFormat = FORMAT_DATETIME;
				}
				self::l($DateFormat);
				$Value = date(CDatabase::DateFormatToPHP($DateFormat), PHPExcel_Shared_Date::ExcelToPHP($Value));
			} else {
				if ($strType=="FLOAT") {
					$Value = str_replace(',','.',$Value);
					$Value = FloatVal($Value);
				} elseif ($strType=="INTEGER") {
					$Value = IntVal($Value);
				}
			}
		} elseif($PropType=="F") {
			$Value = self::MakeFileArray($Value,false);
		} elseif($PropType=="E") {
			$Value = trim($Value);
			if ($Value!='' && in_array($strType,array('ELEMENT_CODE','ELEMENT_NAME','ELEMENT_EXTERNAL'))) {
				$arFilter = array();
				if ($arIBlockProps[$PropertyID]["LINK_IBLOCK_ID"]) {
					$arFilter["IBLOCK_ID"] = $arIBlockProps[$PropertyID]["LINK_IBLOCK_ID"];
				}
				if ($strType=="ELEMENT_CODE") {
					$arFilter["=CODE"] = $Value;
				} elseif ($strType=="ELEMENT_NAME") {
					$arFilter["=NAME"] = $Value;
				} elseif ($strType=="ELEMENT_EXTERNAL") {
					$arFilter["=EXTERNAL_ID"] = $Value;
				}
				if (is_array($arFilter)) {
					CModule::IncludeModule("iblock");
					$resItem = CIBlockElement::GetList(array(),$arFilter,false,array('nTopCount'=>'1'),array("ID"));
					if ($arItem = $resItem->GetNext(false,false)) {
						$Value = $arItem["ID"];
					} else {
						$Value = false;
					}
				}
			}
			if (!is_numeric($Value)) {
				$Value = false;
			}
		} elseif($PropType=="G") {
			$Value = trim($Value);
			if ($Value!='' && in_array($strType,array('SECTION_CODE','SECTION_NAME','SECTION_EXTERNAL'))) {
				$arFilter = array();
				if ($arIBlockProps[$PropertyID]["LINK_IBLOCK_ID"]) {
					$arFilter["IBLOCK_ID"] = $arIBlockProps[$PropertyID]["LINK_IBLOCK_ID"];
				}
				if ($strType=="SECTION_CODE") {
					$arFilter["=CODE"] = $Value;
				} elseif ($strType=="SECTION_NAME") {
					$arFilter["=NAME"] = $Value;
				} elseif ($strType=="SECTION_EXTERNAL") {
					$arFilter["=EXTERNAL_ID"] = $Value;
				}
				if (is_array($arFilter)) {
					CModule::IncludeModule("iblock");
					$resItem = CIBlockSection::GetList(array(),$arFilter,false,array("ID"));
					if ($arItem = $resItem->GetNext(false,false)) {
						$Value = $arItem["ID"];
					} else {
						$Value = false;
					}
				}
			}
			if (!is_numeric($Value)) {
				$Value = false;
			}
		}
		return $Value;
	}
	
	function ProcessValue($Value, $strType, $Separator, $PropertyID=false, $arIBlockProps=false, $arParams=false) {
		if (is_array($arIBlockProps) && is_numeric($PropertyID) && $PropertyID>0) {
			if (trim($Separator)=="") $Separator = ",";
			// Values for IBlock
			if ($arIBlockProps[$PropertyID]["MULTIPLE"]=="Y") {
				if ($Separator=='\n') {
					$Separator = "\n";
				} elseif ($Separator=='\t') {
					$Separator = "\t";
				} elseif ($Separator=='\r') {
					$Separator = "\r";
				}
				$arValue = explode($Separator, $Value);
				foreach ($arValue as $Key => $Value) {
					$arValue[$Key] = self::ProcessSingleValue($Value, $strType, $PropertyID, $arIBlockProps, $arParams);
				}
				$Value = $arValue;
			} else {
				$Value = self::ProcessSingleValue($Value, $strType, $PropertyID, $arIBlockProps, $arParams);
			}
		} elseif ($PropertyID=="F") {
			if ($Value) {
				$Value = self::MakeFileArray($Value, true);
				self::l(GetMessage('WEBDEBUG_EXCEL_LOG_02').print_r($Value,true));
			}
		} else {
			// Values for fields, catalog and other
			$strType = ToUpper($strType);
			if ($strType=="INTEGER") {
				$Value = IntVal($Value);
			} elseif ($strType=="FLOAT") {
				$Value = FloatVal($Value);
			} elseif ($strType!='HTML') {
				$Value = strip_tags($Value);
			}
		}
		return $Value;
	}
	
	/**
	 *	Translit text
	 */
	function Translit($Text, $arParams=false) {
		$arTranslitParams = Array( 
			 "max_len" => "100",
			 "change_case" => "L",
			 "replace_space" => "_",
			 "replace_other" => "_",
			 "delete_repeat_replace" => "true",
			 "use_google" => "false",
		);
		if (is_array($arParams)) {
			if (isset($arParams["TRANS_LEN"])) $arTranslitParams["max_len"] = $arParams["TRANS_LEN"];
			if (isset($arParams["TRANS_CASE"])) $arTranslitParams["change_case"] = $arParams["TRANS_CASE"];
			if (isset($arParams["TRANS_SPACE"])) $arTranslitParams["replace_space"] = $arParams["TRANS_SPACE"];
			if (isset($arParams["TRANS_OTHER"])) $arTranslitParams["replace_other"] = $arParams["TRANS_OTHER"];
			if (isset($arParams["TRANS_EAT"])) $arTranslitParams["delete_repeat_replace"] = $arParams["TRANS_EAT"];
			if (isset($arParams["USE_GOOGLE"])) $arTranslitParams["use_google"] = $arParams["USE_GOOGLE"];
		}
		if (COption::GetOptionString('webdebug.excel','use_own_translit')=='Y') {
			$strResult = self::_Translit($Text, $arTranslitParams);
		} else {
			$strResult = CUtil::translit($Text, LANGUAGE_ID, $arTranslitParams);
			if ($arTranslitParams["delete_repeat_replace"]==="true" || $arTranslitParams["delete_repeat_replace"]===true) {
				$strResult = trim($strResult, $arTranslitParams['replace_space']);
				$strResult = trim($strResult, $arTranslitParams['replace_other']);
			}
		}
		return $strResult;
	}
	
	function substr($Text, $Start, $Count) {
		if (function_exists('mb_substr') && defined('BX_UTF') && BX_UTF===true) {
			return mb_substr($Text,$Start,$Count);
		} else {
			return substr($Text,$Start,$Count);
		}
	}
	
	function strlen($Text) {
		if (function_exists('mb_strlen') && defined('BX_UTF') && BX_UTF===true) {
			return mb_strlen($Text);
		} else {
			return strlen($Text);
		}
	}
	
	function strpos($Haystack, $Needle, $Offset) {
		if (function_exists('mb_strpos') && defined('BX_UTF') && BX_UTF===true) {
			return mb_strpos($Haystack, $Needle, $Offset);
		} else {
			return strpos($Haystack, $Needle, $Offset);
		}
	}
	
	function _Translit($Text, $arTranslitParams) {
		if (trim($arTranslitParams['replace_space'])=='') $arTranslitParams['replace_space'] = '-';
		$strResult = '';
		$RusSymbols = GetMessage('WEBDEBUG_EXCEL_TRANSLIT_RUS');
		$LatSymbols = GetMessage('WEBDEBUG_EXCEL_TRANSLIT_ENG');
		$arRusSymbols = explode(',',$RusSymbols);
		$arLatSymbols = explode(',',$LatSymbols);
		$arRusSymbols[] = $arTranslitParams['replace_space'];
		$arLatSymbols[] = $arTranslitParams['replace_space'];
		for($i=0; $i<=self::strlen($Text); $i++) {
			$Letter = self::substr($Text,$i,1);
			$Found = false;
			foreach($arRusSymbols as $Key => $Value) {
				if ($Value==$Letter) {
					$strResult .= $arLatSymbols[$Key];
					$Found = true;
				}
			}
			if (!$Found && $Value==' ') {
				$strResult .= $arTranslitParams['replace_space'];
				$Found = true;
			}
			if (!$Found) {
				$strResult .= $arTranslitParams['replace_other'];
			}
		}
		if ($arTranslitParams['max_len']>0) {
			$strResult = self::substr($strResult,0,$arTranslitParams['max_len']);
		}
		if ($arTranslitParams["delete_repeat_replace"]==="true" || $arTranslitParams["delete_repeat_replace"]===true) {
			while (self::strpos($strResult,$arTranslitParams['replace_space'].$arTranslitParams['replace_space'])!==false) {
				$strResult = str_replace($arTranslitParams['replace_space'].$arTranslitParams['replace_space'],$arTranslitParams['replace_space'],$strResult);
			}
			while (self::strpos($strResult,$arTranslitParams['replace_other'].$arTranslitParams['replace_other'])!==false) {
				$strResult = str_replace($arTranslitParams['replace_other'].$arTranslitParams['replace_other'],$arTranslitParams['replace_other'],$strResult);
			}
			$strResult = trim($strResult, $arTranslitParams['replace_space']);
			$strResult = trim($strResult, $arTranslitParams['replace_other']);
		}
		if ($arTranslitParams['change_case']=='L') {
			$strResult = ToLower($strResult);
		} elseif ($arTranslitParams['change_case']=='U') {
			$strResult = ToUpper($strResult);
		}
		return $strResult;
	}
	
	function CodeIsUnique($Code, $IBlockID, $IsSection=false) {
		if (CModule::IncludeModule("iblock")) {
			if ($IsSection) {
				$Count = 0;
				$arSections = CIBlockSection::GetList(array(),array("IBLOCK_ID"=>$IBlockID,"CODE"=>$Code),false,array("ID"));
				while ($X = $arSections->GetNext(false,false)) {
					$Count++;
				}
			} else {
				$Count = CIBlockElement::GetList(false,array("IBLOCK_ID"=>$IBlockID,"CODE"=>$Code),array(),false,array("ID"));
			}
			return $Count==0;
		}
	}
	
	function FindUniqueCode($Code, $IBlockID, $IsSection=false) {
		if (CModule::IncludeModule("iblock")) {
			$i = 0;
			while (!self::CodeIsUnique($Code, $IBlockID, $IsSection) && $i<100) {
				$i++;
				if (preg_match("/(.*?)([0-9]+)/i",$Code,$M)) {
					$M[2]++;
					$Code = $M[1].$M[2];
				} else {
					$Code .= "-1";
				}
			}
		}
		return $Code;
	}
	
	function ProcessSection($IBlockID, array $arSections, $DepthLevel, $arIBlockTranslitParamsSection, $ProfileID, $arValues, $arParams, $arColumns) {
		foreach ($arSections as $Key => $Value) {
			if ($Key+1>$DepthLevel) {
				unset($arSections[$Key]);
			}
		}
		$ParentSection = false;
		if (!is_array($arSections)) $arSections = array();
		foreach ($arSections as $arSection) {
			$arFilter = array(
				"IBLOCK_ID"=>$IBlockID,
				"EXTERNAL_ID"=>$arSection["UNIQ"],
			);
			$resDBSection = CIBlockSection::GetList(array(),$arFilter,false,array("ID"));
			if ($arDBSection = $resDBSection->GetNext(false,false)) {
				$ParentSection = $arDBSection["ID"];
				
				if ($arParams['SECTION_METHOD']=='method2') {
					foreach ($arColumns as $ColumnID => $arField) {
						$Separator = $arParams["SHEET_{$SheetIndex}_S_COLUMN_{$ColumnID}_SEPARATOR"];
						if ($arField["FIELD"]=="NAME") {
							$arFields["NAME"] = self::ProcessValue($arValues[$ColumnID],$arField["TYPE"],$Separator);
						} elseif ($arField["FIELD"]=="CODE") {
							$arFields["CODE"] = self::ProcessValue($arValues[$ColumnID],$arField["TYPE"],$Separator);
						} elseif ($arField["FIELD"]=="SORT") {
							$arFields["SORT"] = self::ProcessValue($arValues[$ColumnID],$arField["TYPE"],$Separator);
						} elseif ($arField["FIELD"]=="DETAIL_TEXT") {
							$arFields["DETAIL_TEXT"] = self::ProcessValue($arValues[$ColumnID],$arField["TYPE"],$Separator);
						} elseif ($arField["FIELD"]=="DETAIL_TEXT_TYPE") {
							$arFields["DETAIL_TEXT_TYPE"] = ToLower($arValues[$ColumnID]);
						} elseif ($arField["FIELD"]=="PREVIEW_PICTURE") {
							$arFields["PREVIEW_PICTURE"] = self::ProcessValue($arValues[$ColumnID],$arField["TYPE"],$Separator,"F");
						} elseif ($arField["FIELD"]=="DETAIL_PICTURE") {
							$arFields["DETAIL_PICTURE"] = self::ProcessValue($arValues[$ColumnID],$arField["TYPE"],$Separator,"F");
						}
					}
					$IBlockSection = new CIBlockSection;
					$IBlockSection->Update($ParentSection, $arFields);
				}
				
			} else {
				$arFields = array(
					"IBLOCK_ID" => $IBlockID,
					"IBLOCK_SECTION_ID" => $ParentSection,
					"NAME" => $arSection["NAME"],
					"EXTERNAL_ID" => $arSection["UNIQ"],
				);
				if ($arIBlockTranslitParamsSection["IS_REQUIRED"]=="Y" || $arIBlockTranslitParamsSection["TRANSLITERATION"]=="Y") {
					$arFields["CODE"] = self::Translit($arFields["NAME"], $arIBlockTranslitParamsSection);
					if ($arIBlockTranslitParamsSection["UNIQUE"]=="Y") {
						$arFields["CODE"] = self::FindUniqueCode($arFields["CODE"], $IBlockID, true);
					}
				}
				
				if ($arParams['SECTION_METHOD']=='method2') {
					foreach ($arColumns as $ColumnID => $arField) {
						$Separator = $arParams["SHEET_{$SheetIndex}_S_COLUMN_{$ColumnID}_SEPARATOR"];
						if ($arField["FIELD"]=="NAME") {
							$arFields["NAME"] = self::ProcessValue($arValues[$ColumnID],$arField["TYPE"],$Separator);
						} elseif ($arField["FIELD"]=="CODE") {
							$arFields["CODE"] = self::ProcessValue($arValues[$ColumnID],$arField["TYPE"],$Separator);
						} elseif ($arField["FIELD"]=="SORT") {
							$arFields["SORT"] = self::ProcessValue($arValues[$ColumnID],$arField["TYPE"],$Separator);
						} elseif ($arField["FIELD"]=="DETAIL_TEXT") {
							$arFields["DETAIL_TEXT"] = self::ProcessValue($arValues[$ColumnID],$arField["TYPE"],$Separator);
						} elseif ($arField["FIELD"]=="DETAIL_TEXT_TYPE") {
							$arFields["DETAIL_TEXT_TYPE"] = ToLower($arValues[$ColumnID]);
						} elseif ($arField["FIELD"]=="PREVIEW_PICTURE") {
							$arFields["PREVIEW_PICTURE"] = self::ProcessValue($arValues[$ColumnID],$arField["TYPE"],$Separator,"F");
						} elseif ($arField["FIELD"]=="DETAIL_PICTURE") {
							$arFields["DETAIL_PICTURE"] = self::ProcessValue($arValues[$ColumnID],$arField["TYPE"],$Separator,"F");
						}
					}
				}
				
				$IBlockSection = new CIBlockSection;
				$ParentSection = $IBlockSection->Add($arFields);
				if (!is_numeric($ParentSection)) {
					self::l(GetMessage('WEBDEBUG_EXCEL_ERROR_05').$IBlockSection->LAST_ERROR.' [Line: '.$arSection['LINE'].']');
					self::l(GetMessage('WEBDEBUG_EXCEL_LOG_03').print_r($arFields,true));
					$_SESSION["WEBDEBUG"]["EXCEL"]["STATUS"][$ProfileID]['ERRORS_COUNT']++;
					return false;
				}
			}
			if (isset($arSection['DATA']) && is_array($arSection['DATA']) && !empty($arSection['DATA'])) {
				$arUpdateFields = array();
				foreach ($arSection['DATA'] as $DataKey => $DataValue) {
					if (in_array($DataKey, array('DETAIL_PICTURE','PICTURE'))) {
						$DataValue = self::MakeFileArray($DataValue,true);
					}
					$arUpdateFields[$DataKey] = $DataValue;
				}
				if (!$IBlockSection) $IBlockSection = new CIBlockSection;
				self::l($arUpdateFields);
				$IBlockSection->Update($ParentSection, $arUpdateFields);
			}
		}
		return $ParentSection;
	}
	
	/**
	 *	Function processes the product
	 */
	function ProcessOfferParent($IBlockID, $ProductName, $arSections, $DepthLevel, $ProfileID, $arParams, $arColumns, $arValues, $ProfileID, $LineIndex) {
		$arResult = array();
		$arOffersCatalog = CCatalog::GetByID($IBlockID);
		if (is_array($arOffersCatalog)) {
			$ProductIBlock = $arOffersCatalog['PRODUCT_IBLOCK_ID'];
			$arIBlockTranslitParamsElement = CWebdebugExcel::GetIBlockTranslitSettings($ProductIBlock);
			$arIBlockTranslitParamsSection = CWebdebugExcel::GetIBlockTranslitSettings($ProductIBlock, true);
			$SKUProperty = $arOffersCatalog['SKU_PROPERTY_ID'];
			$IBlockSectionID = self::ProcessSection($ProductIBlock, $arSections, $DepthLevel, $arIBlockTranslitParamsSection, $ProfileID);
			$UniqValue = "";
			foreach ($arSections as $Key => $arSection) {
				$UniqValue .= trim(ToLower($arSection["UNIQ"]));
				$UniqValue = MD5($UniqValue);
			}
			$UniqValue .= MD5($ProductName);
			
			$arProductFields = array(
				'IBLOCK_ID' => $ProductIBlock,
				'IBLOCK_SECTION_ID' => $IBlockSectionID,
				'NAME' => $ProductName,
				'EXTERNAL_ID' => $UniqValue,
			);
			
			$Currency = "";
			$arProperties = array();
			$arCatalog = array(
				"PRICE_TYPE"=>"S",
				#"QUANTITY"=>"1",
				#"WEIGHT"=>"0",
				"QUANTITY_TRACE"=>$arParams["REDUCE"]=="Y"?"Y":"N"
			);
			$arStores = array();
			$arPrices = array();
			$Break = false;
			$arIBlockProps = $this->GetIBlockProps($ProductIBlock,true);
			$PreviewTextType = false;
			$DetailTextType = false;
			foreach ($arColumns as $ColumnID => $arField) {
				$Separator = $arParams["SHEET_{$SheetIndex}_P_COLUMN_{$ColumnID}_SEPARATOR"];
				if ($arField["FIELD"]=="SKIP_FLAG" && $arValues[$ColumnID]!="") { // Logic
					$Break = true;
				} elseif ($arField["FIELD"]=="NAME") { // Fields
					$arProductFields["NAME"] = self::ProcessValue($arValues[$ColumnID],$arField["TYPE"],$Separator);
				} elseif ($arField["FIELD"]=="CODE") {
					$arProductFields["CODE"] = self::ProcessValue($arValues[$ColumnID],$arField["TYPE"],$Separator);
				} elseif ($arField["FIELD"]=="SORT") {
					$arProductFields["SORT"] = self::ProcessValue($arValues[$ColumnID],$arField["TYPE"],$Separator);
				} elseif ($arField["FIELD"]=="PREVIEW_TEXT") {
					$arProductFields["PREVIEW_TEXT"] = self::ProcessValue($arValues[$ColumnID],$arField["TYPE"],$Separator);
					if (ToLower($arField["TYPE"])=='html') $PreviewTextType = 'html';
				} elseif ($arField["FIELD"]=="PREVIEW_TEXT_TYPE") {
					$arProductFields["PREVIEW_TEXT_TYPE"] = ToLower($arValues[$ColumnID]);
				} elseif ($arField["FIELD"]=="DETAIL_TEXT") {
					$arProductFields["DETAIL_TEXT"] = self::ProcessValue($arValues[$ColumnID],$arField["TYPE"],$Separator);
					if (ToLower($arField["TYPE"])=='html') $DetailTextType = 'html';
				} elseif ($arField["FIELD"]=="DETAIL_TEXT_TYPE") {
					$arProductFields["DETAIL_TEXT_TYPE"] = ToLower($arValues[$ColumnID]);
				} elseif ($arField["FIELD"]=="PREVIEW_PICTURE") {
					$arProductFields["PREVIEW_PICTURE"] = self::ProcessValue($arValues[$ColumnID],$arField["TYPE"],$Separator,"F");
				} elseif ($arField["FIELD"]=="DETAIL_PICTURE") {
					$arProductFields["DETAIL_PICTURE"] = self::ProcessValue($arValues[$ColumnID],$arField["TYPE"],$Separator,"F");
				} elseif (preg_match("/price_([0-9]+)/i",$arField["FIELD"],$M)) { // Catalog
					$arPrices[$M[1]] = self::ProcessValue($arValues[$ColumnID],$arField["TYPE"],$Separator);
				} elseif ($arField["FIELD"]=="CURRENCY") {
					if (isset($arCurrencies[ToLower($arValues[$ColumnID])])) {
						$Currency = $arValues[$ColumnID];
					} else {
						$Currency = $arParams["CURRENCY"];
					}
				} elseif ($arField["FIELD"]=="QUANTITY") {
					$arCatalog["QUANTITY"] = self::ProcessValue($arValues[$ColumnID],$arField["TYPE"],$Separator);
				} elseif ($arField["FIELD"]=="WEIGHT") {
					$arCatalog["WEIGHT"] = self::ProcessValue($arValues[$ColumnID],$arField["TYPE"],$Separator);
				} elseif ($arField["FIELD"]=="LENGTH") {
					$arCatalog["LENGTH"] = self::ProcessValue($arValues[$ColumnID],$arField["TYPE"],$Separator);
				} elseif ($arField["FIELD"]=="WIDTH") {
					$arCatalog["WIDTH"] = self::ProcessValue($arValues[$ColumnID],$arField["TYPE"],$Separator);
				} elseif ($arField["FIELD"]=="HEIGHT") {
					$arCatalog["HEIGHT"] = self::ProcessValue($arValues[$ColumnID],$arField["TYPE"],$Separator);
				} elseif (preg_match("/store_([0-9]+)/i",$arField["FIELD"],$M)) {
					$arStores[$M[1]] = self::ProcessValue($arValues[$ColumnID],$arField["TYPE"],$Separator);
				} elseif (preg_match("/property_([0-9]+)/i",$arField["FIELD"],$M)) {
					$arProperties[$M[1]] = self::ProcessValue($arValues[$ColumnID],$arField["TYPE"],$Separator,$M[1],$arIBlockProps,$arParams);
				}
			}
			if ($Break===true) return false;
			
			if ($PreviewTextType==='html') $arProductFields['PREVIEW_TEXT_TYPE'] = 'html';
			if (!in_array(ToLower($arProductFields['PREVIEW_TEXT_TYPE']),array('html','text'))) $arProductFields['PREVIEW_TEXT_TYPE'] = 'text';
			if ($DetailTextType==='html') $arProductFields['DETAIL_TEXT_TYPE'] = 'html';
			if (!in_array(ToLower($arProductFields['DETAIL_TEXT_TYPE']),array('html','text'))) $arProductFields['DETAIL_TEXT_TYPE'] = 'text';
			
			$IBlockElement = new CIBlockElement;
			$resCheckItem = CIBlockElement::GetList(false,array("IBLOCK_ID"=>$ProductIBlock,"EXTERNAL_ID"=>$UniqValue),false,false,array("ID","NAME","CODE"));
			$Success=false;
			
			if ($arCheckItem = $resCheckItem->GetNext()) {
				// Item exists
				if ($arParams["SKIP_MULTISECTION"]=="Y") {
					$resSectionToItem = CIBlockElement::GetElementGroups($arCheckItem["ID"]);
					$ItemSectionCount = 0;
					while ($arSectionToItem = $resSectionToItem->GetNext(false,false)) {
						$ItemSectionCount++;
					}
					if ($ItemSectionCount>1) {
						unset($arProductFields["IBLOCK_SECTION_ID"]);
					}
				}
				if ($arCheckItem["~NAME"]) {
					$arCheckItem["NAME"] = $arCheckItem["~NAME"];
				}
				if ($arParams["RENAME"]!="Y") {
					$arProductFields["NAME"] = $arCheckItem["NAME"];
				}
				if ($arParams["RECODE"]!="Y") {
					$arProductFields["CODE"] = $arCheckItem["CODE"];
				} else {
					$Code = "";
					if ($arIBlockTranslitParamsElement["IS_REQUIRED"]=="Y" || $arIBlockTranslitParamsElement["TRANSLITERATION"]=="Y") {
						$Code = self::Translit($arParams["RENAME"]=="Y"?$arProductFields["NAME"]:$arCheckItem["NAME"], $arIBlockTranslitParamsElement);
						if ($arIBlockTranslitParamsElement["UNIQUE"]=="Y") {
							$Code = self::FindUniqueCode($Code, $ProductIBlock);
						}
					}
					if ($Code!='') $arProductFields['CODE'] = $Code;
				}
				unset($arProductFields['ACTIVE_FROM']);
				unset($arProductFields['ACTIVE_TO']);
				$UpdateResult = $IBlockElement->Update($arCheckItem["ID"], $arProductFields);
				if ($UpdateResult) {
					$ElementID = $arCheckItem["ID"];
					$Success = true;
				} else {
					self::l(GetMessage('WEBDEBUG_EXCEL_ERROR_01').$IBlockElement->LAST_ERROR.' [Line: '.$LineIndex.']');
					self::l(GetMessage('WEBDEBUG_EXCEL_LOG_03').print_r($arProductFields,true));
					$_SESSION["WEBDEBUG"]["EXCEL"]["STATUS"][$ProfileID]['ERRORS_COUNT']++;
				}
			} else {
				// Item not exists
				$Code = "";
				if ($arIBlockTranslitParamsElement["IS_REQUIRED"]=="Y" || $arIBlockTranslitParamsElement["TRANSLITERATION"]=="Y") {
					$Code = self::Translit($arProductFields["NAME"], $arIBlockTranslitParamsElement);
					if ($arIBlockTranslitParamsElement["UNIQUE"]=="Y") {
						$Code = self::FindUniqueCode($Code, $ProductIBlock);
					}
				}
				if ($Code!='') $arProductFields['CODE'] = $Code;
				$ElementID = $IBlockElement->Add($arProductFields);
				if ($ElementID) {
					$Success = true;
				} else {
					self::l(GetMessage('WEBDEBUG_EXCEL_ERROR_02').$IBlockElement->LAST_ERROR.' [Line: '.$LineIndex.']');
					self::l(GetMessage('WEBDEBUG_EXCEL_LOG_03').print_r($arProductFields,true));
					$_SESSION["WEBDEBUG"]["EXCEL"]["STATUS"][$ProfileID]['ERRORS_COUNT']++;
				}
			}
			if ($Success) {
				// Set import ID
				$ImportID = self::GetImportID($ProfileID);
				if ($ImportID) {
					CIBlockElement::SetPropertyValuesEx($ElementID,$ProductIBlock,array("WD_EXCEL_IMPORT_ID"=>$ImportID));
				}
				// Set properties
				foreach ($arProperties as $PropertyID => $arPropertyValue) {
					CIBlockElement::SetPropertyValuesEx($ElementID,$ProductIBlock,array($PropertyID=>$arPropertyValue));
				}
			}
		}
		$arResult[$SKUProperty] = $ElementID;
		return $arResult;
	}
	
	/**
	 *	Set default field values based on the IBlock settings
	 */
	function SetDefaultFields($arFields, $arIBlockFields) {
		if ($arIBlockFields['ACTIVE_FROM']['DEFAULT_VALUE']=='=today' && trim($arFields['ACTIVE_FROM'])=='') $arFields['ACTIVE_FROM'] = date(CDatabase::DateFormatToPHP(FORMAT_DATE));
		if ($arIBlockFields['ACTIVE_FROM']['DEFAULT_VALUE']=='=now' && trim($arFields['ACTIVE_FROM'])=='') $arFields['ACTIVE_FROM'] = date(CDatabase::DateFormatToPHP(FORMAT_DATETIME));
		if ($arIBlockFields['ACTIVE_TO']['DEFAULT_VALUE']>0 && trim($arFields['ACTIVE_TO'])=='') {
			if ($arIBlockFields['ACTIVE_FROM']['DEFAULT_VALUE']=='=today') {
				$arFields['ACTIVE_TO'] = date(CDatabase::DateFormatToPHP(FORMAT_DATE),time() + $arIBlockFields['ACTIVE_TO']['DEFAULT_VALUE']*24*60*60);
			} else {
				$arFields['ACTIVE_TO'] = date(CDatabase::DateFormatToPHP(FORMAT_DATETIME),time() + $arIBlockFields['ACTIVE_TO']['DEFAULT_VALUE']*24*60*60);
			}
		}
		if (trim($arFields['NAME'])=='' && trim($arIBlockFields['NAME']['DEFAULT_VALUE'])!='') {
			$arFields['NAME'] = $arIBlockFields['NAME']['DEFAULT_VALUE'];
		}
		if (trim($arFields['PREVIEW_TEXT'])=='' && trim($arIBlockFields['PREVIEW_TEXT']['DEFAULT_VALUE'])!='') {
			$arFields['PREVIEW_TEXT'] = $arIBlockFields['PREVIEW_TEXT']['DEFAULT_VALUE'];
			if (trim($arFields['PREVIEW_TEXT_TYPE'])=='') {
				$arFields['PREVIEW_TEXT_TYPE'] = $arIBlockFields['PREVIEW_TEXT_TYPE']['DEFAULT_VALUE']=='html' ? 'html' : 'text';
			}
		}
		if (trim($arFields['DETAIL_TEXT'])=='' && trim($arIBlockFields['DETAIL_TEXT']['DEFAULT_VALUE'])!='') {
			$arFields['DETAIL_TEXT'] = $arIBlockFields['DETAIL_TEXT']['DEFAULT_VALUE'];
			if (trim($arFields['DETAIL_TEXT_TYPE'])=='') {
				$arFields['DETAIL_TEXT_TYPE'] = $arIBlockFields['DETAIL_TEXT_TYPE']['DEFAULT_VALUE']=='html' ? 'html' : 'text';
			}
		}
		return $arFields;
	}
	
	/**
	 *	Function processes the current line for add or update item
	 */
	function ProcessLine($arValues, $arHeaders, $arColumns, $IBlockID, $arSections, $DepthLevel, $HeaderUniq, $arParams, $arIBlockTranslitParamsElement, $arIBlockTranslitParamsSection, $arIBlockProps, $SheetIndex, $arCurrencies, $ProfileID, $LineIndex, $arIBlockFields) {
		self::l(sprintf(GetMessage('WEBDEBUG_EXCEL_LOG_01'),$LineIndex));
		if (CModule::IncludeModule("iblock")) {
			$UseOffers = $arParams['USE_OFFERS']=='Y';
			$UniqValue = $arValues[$HeaderUniq];
			if ($UniqValue!="") {
				// Build fields array
				$arFields = array(
					"NAME" => "",
					"IBLOCK_ID" => $IBlockID,
					"EXTERNAL_ID" => $UniqValue
				);
				#$arFields = self::SetDefaultFields($arFields, $arIBlockFields);
				$Currency = "";
				$arProperties = array();
				$arCatalog = array(
					"PRICE_TYPE"=>"S",
					#"QUANTITY"=>"1",
					#"WEIGHT"=>"0",
					"QUANTITY_TRACE"=>$arParams["REDUCE"]=="Y"?"Y":"N"
				);
				$arStores = array();
				$arPrices = array();
				$Break = false;
				$PreviewTextType = false;
				$DetailTextType = false;
				foreach ($arColumns as $ColumnID => $arField) {
					$Separator = $arParams["SHEET_{$SheetIndex}_COLUMN_{$ColumnID}_SEPARATOR"];
					if ($arField["FIELD"]=="SKIP_FLAG" && $arValues[$ColumnID]!="") { // Logic
						$Break = true;
					} elseif ($arField["FIELD"]=="NAME") { // Fields
						$arFields["NAME"] = self::ProcessValue($arValues[$ColumnID],$arField["TYPE"],$Separator);
					} elseif ($arField["FIELD"]=="CODE") {
						$arFields["CODE"] = self::ProcessValue($arValues[$ColumnID],$arField["TYPE"],$Separator);
					} elseif ($arField["FIELD"]=="SORT") {
						$arFields["SORT"] = self::ProcessValue($arValues[$ColumnID],$arField["TYPE"],$Separator);
					} elseif ($arField["FIELD"]=="PREVIEW_TEXT") {
						$arFields["PREVIEW_TEXT"] = self::ProcessValue($arValues[$ColumnID],$arField["TYPE"],$Separator);
						if (ToLower($arField["TYPE"])=='html') $PreviewTextType = 'html';
					} elseif ($arField["FIELD"]=="PREVIEW_TEXT_TYPE") {
						$arFields["PREVIEW_TEXT_TYPE"] = ToLower($arValues[$ColumnID]);
					} elseif ($arField["FIELD"]=="DETAIL_TEXT") {
						$arFields["DETAIL_TEXT"] = self::ProcessValue($arValues[$ColumnID],$arField["TYPE"],$Separator);
						if (ToLower($arField["TYPE"])=='html') $DetailTextType = 'html';
					} elseif ($arField["FIELD"]=="DETAIL_TEXT_TYPE") {
						$arFields["DETAIL_TEXT_TYPE"] = ToLower($arValues[$ColumnID]);
					} elseif ($arField["FIELD"]=="PREVIEW_PICTURE") {
						$arFields["PREVIEW_PICTURE"] = self::ProcessValue($arValues[$ColumnID],$arField["TYPE"],$Separator,"F");
					} elseif ($arField["FIELD"]=="DETAIL_PICTURE") {
						$arFields["DETAIL_PICTURE"] = self::ProcessValue($arValues[$ColumnID],$arField["TYPE"],$Separator,"F");
					} elseif (preg_match("/price_([0-9]+)/i",$arField["FIELD"],$M)) { // Catalog
						$arPrices[$M[1]] = self::ProcessValue($arValues[$ColumnID],$arField["TYPE"],$Separator);
					} elseif ($arField["FIELD"]=="CURRENCY") {
						if (isset($arCurrencies[ToLower($arValues[$ColumnID])])) {
							$Currency = $arValues[$ColumnID];
						} else {
							$Currency = $arParams["CURRENCY"];
						}
					} elseif ($arField["FIELD"]=="QUANTITY") {
						$arCatalog["QUANTITY"] = self::ProcessValue($arValues[$ColumnID],$arField["TYPE"],$Separator);
					} elseif ($arField["FIELD"]=="WEIGHT") {
						$arCatalog["WEIGHT"] = self::ProcessValue($arValues[$ColumnID],$arField["TYPE"],$Separator);
					} elseif ($arField["FIELD"]=="LENGTH") {
						$arCatalog["LENGTH"] = self::ProcessValue($arValues[$ColumnID],$arField["TYPE"],$Separator);
					} elseif ($arField["FIELD"]=="WIDTH") {
						$arCatalog["WIDTH"] = self::ProcessValue($arValues[$ColumnID],$arField["TYPE"],$Separator);
					} elseif ($arField["FIELD"]=="HEIGHT") {
						$arCatalog["HEIGHT"] = self::ProcessValue($arValues[$ColumnID],$arField["TYPE"],$Separator);
					} elseif (preg_match("/store_([0-9]+)/i",$arField["FIELD"],$M)) {
						$arStores[$M[1]] = self::ProcessValue($arValues[$ColumnID],$arField["TYPE"],$Separator);
					} elseif (preg_match("/property_([0-9]+)/i",$arField["FIELD"],$M)) {
						$arProperties[$M[1]] = self::ProcessValue($arValues[$ColumnID],$arField["TYPE"],$Separator,$M[1],$arIBlockProps,$arParams);
					}
				}
				if ($Break!==true) {
					$arOfferData = false;
					if ($UseOffers && CModule::IncludeModule('catalog')) {
						$arLastSection = array_pop($arSections);
						if ($_SESSION["WEBDEBUG"]["EXCEL"]["STATUS"][$ProfileID]['LAST_OFFER_PROPDUCT_LINE'] != $arLastSection['LINE']) {
							if (is_array($arLastSection)) {
								self::l(sprintf(GetMessage('WEBDEBUG_EXCEL_LOG_04'),$arLastSection['LINE']));
								// Get values for offer product line (direct from Excel)
								$arValues = array();
								foreach ($arHeaders as $arHeader) {
									$Value = $this->GetValue($SheetIndex,$arHeader["COLUMN"],$arLastSection['LINE']);
									$arValues[$arHeader["COLUMN"]] = $Value;
								}
								$arColumns = array();
								foreach ($arHeaders as $arHeader) {
									$arColumns[$arHeader["COLUMN"]] = array(
										"FIELD" => $arParams["SHEET_".$SheetIndex."_P_COLUMN_".$arHeader["COLUMN"]],
										"TYPE" => $arParams["SHEET_".$SheetIndex."_P_COLUMN_".$arHeader["COLUMN"]."_TYPE"],
									);
								}
								$arOfferData = self::ProcessOfferParent($IBlockID, $arLastSection['NAME'], $arSections, $DepthLevel-1, $ProfileID, $arParams, $arColumns, $arValues, $ProfileID, $LineIndex);
								$_SESSION["WEBDEBUG"]["EXCEL"]["STATUS"][$ProfileID]['LAST_OFFER_PROPDUCT_LINE'] = $arLastSection['LINE'];
								$arSections = array();
							}
						}
					}
							
					if ($PreviewTextType==='html') $arFields['PREVIEW_TEXT_TYPE'] = 'html';
					if (!in_array(ToLower($arFields['PREVIEW_TEXT_TYPE']),array('html','text'))) $arFields['PREVIEW_TEXT_TYPE'] = 'text';
					if (!isset($arFields['PREVIEW_TEXT'])) unset($arFields['PREVIEW_TEXT_TYPE']);
					if ($DetailTextType==='html') $arFields['DETAIL_TEXT_TYPE'] = 'html';
					if (!in_array(ToLower($arFields['DETAIL_TEXT_TYPE']),array('html','text'))) $arFields['DETAIL_TEXT_TYPE'] = 'text';
					if (!isset($arFields['DETAIL_TEXT'])) unset($arFields['DETAIL_TEXT_TYPE']);
					
					if ($arParams['SECTION_METHOD']!='method3') {
						$IBlockSectionID = self::ProcessSection($IBlockID, $arSections, $DepthLevel, $arIBlockTranslitParamsSection, $ProfileID, $arValues, $arParams, $arColumns);
						$arFields["IBLOCK_SECTION_ID"] = $IBlockSectionID;
					}
					if (trim($Currency)=="") $Currency = $arParams["CURRENCY"];
					$resCheckItem = CIBlockElement::GetList(false,array("IBLOCK_ID"=>$IBlockID,"EXTERNAL_ID"=>$UniqValue),false,false,array("ID","NAME","CODE"));
					$IBlockElement = new CIBlockElement;
					$Success = false;
					foreach(GetModuleEvents("webdebug.excel", "OnBeforeElement", true) as $arEvent) {
						ExecuteModuleEventEx($arEvent, array($ElementID, &$arProperties, &$arCatalog, &$arStores, &$arFields, $arParams));
					}
					if ($arCheckItem = $resCheckItem->GetNext()) {
						if ($arParams["SKIP_MULTISECTION"]=="Y") {
							$resSectionToItem = CIBlockElement::GetElementGroups($arCheckItem["ID"]);
							$ItemSectionCount = 0;
							while ($arSectionToItem = $resSectionToItem->GetNext(false,false)) {
								$ItemSectionCount++;
							}
							if ($ItemSectionCount>1) {
								unset($arFields["IBLOCK_SECTION_ID"]);
							}
						}
						if ($arCheckItem["~NAME"]) {
							$arCheckItem["NAME"] = $arCheckItem["~NAME"];
						}
						// Item exists
						if ($arParams["RENAME"]!="Y") {
							$arFields["NAME"] = $arCheckItem["NAME"];
						}
						if ($arParams["RECODE"]!="Y") {
							$arFields["CODE"] = $arCheckItem["CODE"];
						} else {
							// Auto generate CODE
							if ($arIBlockTranslitParamsElement["IS_REQUIRED"]=="Y" || $arIBlockTranslitParamsElement["TRANSLITERATION"]=="Y") {
								$arFields["CODE"] = self::Translit($arParams["RENAME"]=="Y"?$arFields["NAME"]:$arCheckItem["NAME"], $arIBlockTranslitParamsElement);
								if ($arIBlockTranslitParamsElement["UNIQUE"]=="Y") {
									$arFields["CODE"] = self::FindUniqueCode($arFields["CODE"], $IBlockID);
								}
							}
						}
						$CanUpdate = true;
            foreach(GetModuleEvents("webdebug.excel", "OnBeforeElementUpdate", true) as $arEvent) {
							if(ExecuteModuleEventEx($arEvent, array($arCheckItem["ID"], &$arFields, $arParams))===false){
								$CanUpdate = false;
								break;
							}
            }
						if ($CanUpdate) {
							unset($arFields['ACTIVE_FROM']);
							unset($arFields['ACTIVE_TO']);
							$UpdateResult = $IBlockElement->Update($arCheckItem["ID"], $arFields);
							if ($UpdateResult) {
								$ElementID = $arCheckItem["ID"];
								$Success = true;
							} else {
								self::l(GetMessage('WEBDEBUG_EXCEL_ERROR_01').$IBlockElement->LAST_ERROR.' [Line: '.$LineIndex.']');
								self::l(GetMessage('WEBDEBUG_EXCEL_LOG_03').print_r($arFields,true));
								$_SESSION["WEBDEBUG"]["EXCEL"]["STATUS"][$ProfileID]['ERRORS_COUNT']++;
							}
						}
					} else {
						// Set default fields
						$arFields = self::SetDefaultFields($arFields, $arIBlockFields);
						// Item not exists
						// Auto generate CODE
						if ($arIBlockTranslitParamsElement["IS_REQUIRED"]=="Y" || $arIBlockTranslitParamsElement["TRANSLITERATION"]=="Y") {
							$arFields["CODE"] = self::Translit($arFields["NAME"], $arIBlockTranslitParamsElement);
							if ($arIBlockTranslitParamsElement["UNIQUE"]=="Y") {
								$arFields["CODE"] = self::FindUniqueCode($arFields["CODE"], $IBlockID);
							}
						}
						$CanAdd = true;
            foreach(GetModuleEvents("webdebug.excel", "OnBeforeElementAdd", true) as $arEvent) {
							if(ExecuteModuleEventEx($arEvent, array(&$arFields, $arParams))===false){
								$CanAdd = false;
								break;
							}
            }
						if ($CanAdd) {
							$ElementID = $IBlockElement->Add($arFields);
							if ($ElementID) {
								$Success = true;
							} else {
								self::l(GetMessage('WEBDEBUG_EXCEL_ERROR_02').$IBlockElement->LAST_ERROR.' [Line: '.$LineIndex.']');
								self::l(GetMessage('WEBDEBUG_EXCEL_LOG_03').print_r($arFields,true));
								$_SESSION["WEBDEBUG"]["EXCEL"]["STATUS"][$ProfileID]['ERRORS_COUNT']++;
							}
						}
					}
					if ($Success) {
						// Set import ID
						$ImportID = self::GetImportID($ProfileID);
						if ($ImportID) {
							CIBlockElement::SetPropertyValuesEx($ElementID,$IBlockID,array("WD_EXCEL_IMPORT_ID"=>$ImportID));
						}
						// Set properties
						foreach ($arProperties as $PropertyID => $arPropertyValue) {
							CIBlockElement::SetPropertyValuesEx($ElementID,$IBlockID,array($PropertyID=>$arPropertyValue));
						}
						// Set product to offer
						if ($arOfferData) {
							foreach($arOfferData as $Key => $Value) {
								CIBlockElement::SetPropertyValuesEx($ElementID,$IBlockID,array($Key=>$Value));
							}
						}
						// Add product data
						$arCatalog["ID"] = $ElementID;
						if (CModule::IncludeModule("catalog") && CCatalogProduct::Add($arCatalog)) {
							// Set price
							foreach ($arPrices as $PriceID => $PriceValue) {
								$arPriceFields = Array(
									"PRODUCT_ID" => $ElementID,
									"CATALOG_GROUP_ID" => $PriceID,
									"PRICE" => $PriceValue,
									"CURRENCY" => $Currency,
								);
								$resPrice = CPrice::GetList(
									array(),
									array(
										"PRODUCT_ID" => $ElementID,
										"CATALOG_GROUP_ID" => $PriceID
									)
								);
								if ($arPrice = $resPrice->GetNext()) {
									CPrice::Update($arPrice["ID"], $arPriceFields);
								} else {
									CPrice::Add($arPriceFields);
								}
							}
							if (class_exists('CCatalogStore')) {
								// Set quantity for stores
								foreach ($arStores as $StoreID => $StoreAmount) {
									$arStoreFields = array(
										"PRODUCT_ID" => $ElementID,
										"AMOUNT" => $StoreAmount,
										"STORE_ID" => $StoreID,
									);
									$Result = CCatalogStoreProduct::Add($arStoreFields);
									if ($Result) {
										// Store added
									}
								}
							}
						} else {
							print GetMessage('WEBDEBUG_EXCEL_ERROR_03');
						}
            foreach(GetModuleEvents("webdebug.excel", "OnAfterElement", true) as $arEvent) {
							ExecuteModuleEventEx($arEvent, array($ElementID, $IBlockID, &$arProperties, &$arCatalog, &$arStores, &$arFields, $arParams));
            }
					} else {
						print GetMessage('WEBDEBUG_EXCEL_ERROR_04').$IBlockElement->LAST_ERROR;
						$_SESSION["WEBDEBUG"]["EXCEL"]["STATUS"][$ProfileID]['ERRORS_COUNT']++;
					}
				}
			}
		}
	}
	
	function SetImportID($ProfileID) {
		session_start();
		$_SESSION["WEBDEBUG"]["EXCEL"]["STATUS"][$ProfileID]["IMPORT_ID"] = ToUpper(RandString(8));
	}
	
	function GetImportID($ProfileID) {
		session_start();
		return $_SESSION["WEBDEBUG"]["EXCEL"]["STATUS"][$ProfileID]["IMPORT_ID"];
	}
	
	function ClearImportID($ProfileID) {
		session_start();
		unset($_SESSION["WEBDEBUG"]["EXCEL"]["STATUS"][$ProfileID]["IMPORT_ID"]);
	}
	
	function AddImportIDProperty($IBlockID, $Delete=false) {
		if (CModule::IncludeModule("iblock")) {
			// Check if prop exists
			$resProp = CIBlockProperty::GetList(array(),array("IBLOCK_ID"=>$IBlockID,"CODE"=>"WD_EXCEL_IMPORT_ID"));
			if ($arProp = $resProp->GetNext(false,false)) {
				if ($Delete) {
					CIBlockProperty::Delete($arProp);
				}
			} elseif (!$Delete) {
				$arFields = array(
				 "NAME" => "webdebug.excel ImportID", 
				 "ACTIVE" => "Y", 
				 "SORT" => "1000",  
				 "CODE" => "WD_EXCEL_IMPORT_ID",  
				 "PROPERTY_TYPE" => "S",  
				 "IBLOCK_ID" => $IBlockID,
				);
				$IBlockProperty = new CIBlockProperty;
				$IBlockProperty->Add($arFields);
			}
		}
	}
	
	/**
	 *	Get IBlock ID for parent product
	 */
	function GetOffersProductIBlock($OfferIBlockID) {
		$ProductIBlockID = false;
		if ($OfferIBlockID && CModule::IncludeModule('iblock')) {
			$arCatalog = CCatalog::GetByID($OfferIBlockID);
			if ($arCatalog) {
				$ProductIBlockID = $arCatalog['PRODUCT_IBLOCK_ID'];
			}
		}
		return $ProductIBlockID;
	}
	
}
?>