Exemplo n.º 1
0
 protected function receiveFiles()
 {
     $result = array();
     $timeToKeepFiles = 24;
     $tmpDir = \CTempFile::GetDirectoryName($timeToKeepFiles);
     CheckDirPath($tmpDir);
     $sftp = \Bitrix\Sale\TradingPlatform\Ebay\Helper::getSftp($this->siteId);
     $sftp->connect();
     /*
     $orderFiles = $sftp->getFilesList($this->remotePath);
     
     foreach($orderFiles as $file)
     {
     	if($sftp->downloadFile($this->remotePath."/".$file, $tmpDir.$file))
     	{
     		$result[] = $tmpDir.$file;
     		Ebay::log(Logger::LOG_LEVEL_INFO, "EBAY_DATA_SOURCE_ORDERFILE_RECEIVED", $file, "File received successfully.", $this->siteId);
     	}
     }
     */
     $file = "orderLatest";
     if ($sftp->downloadFile($this->orderLatest, $tmpDir . $file)) {
         $result[] = $tmpDir . $file;
         Ebay::log(Logger::LOG_LEVEL_INFO, "EBAY_DATA_SOURCE_ORDERFILE_RECEIVED", $file, "File received successfully.", $this->siteId);
     }
     return $result;
 }
Exemplo n.º 2
0
 protected function getFileContent($feedData)
 {
     $result = "";
     $timeToKeepFiles = 24;
     $tmpDir = \CTempFile::GetDirectoryName($timeToKeepFiles);
     CheckDirPath($tmpDir);
     $sftp = \Bitrix\Sale\TradingPlatform\Ebay\Helper::getSftp($this->siteId);
     $sftp->connect();
     $remotePath = $this->createRemotePath($feedData);
     $files = $sftp->getFilesList($remotePath);
     foreach ($files as $file) {
         if (!strstr($file, $feedData["FILENAME"])) {
             continue;
         }
         if ($sftp->downloadFile($remotePath . "/" . $file, $tmpDir . $file)) {
             $result = file_get_contents($tmpDir . $file);
             Ebay::log(Logger::LOG_LEVEL_INFO, "EBAY_DATA_SOURCE_RESULTS_RECEIVED", $file, "File received successfully.", $this->siteId);
         } else {
             Ebay::log(Logger::LOG_LEVEL_ERROR, "EBAY_DATA_SOURCE_RESULTS_ERROR", $tmpDir . $file, "Can't receive file content.", $this->siteId);
         }
     }
     return $result;
 }
Exemplo n.º 3
0
 /**
  * Returns value of ldap user field mapped to bitrix field.
  * @param string $fieldName Name of user field in Bitrix system.
  * @param array $arLdapUser User params received from ldap.
  * @return mixed.
  */
 function getLdapValueByBitrixFieldName($fieldName, $arLdapUser)
 {
     global $USER_FIELD_MANAGER;
     if (!isset($this->arFields["FIELD_MAP"][$fieldName])) {
         return false;
     }
     $attr = $this->arFields["FIELD_MAP"][$fieldName];
     $arRes = $USER_FIELD_MANAGER->GetUserFields("USER", 0, LANGUAGE_ID);
     $result = false;
     if (is_array($arRes[$fieldName])) {
         if ($arRes[$fieldName]["MULTIPLE"] == "Y") {
             if (is_array($arLdapUser[strtolower($attr)])) {
                 $result = array_values($arLdapUser[strtolower($attr)]);
             } else {
                 $result = array($arLdapUser[strtolower($attr)]);
             }
         } else {
             if (!empty($arLdapUser[strtolower($attr)])) {
                 $result = $arLdapUser[strtolower($attr)];
             } else {
                 if (!empty($arRes[$fieldName]['SETTINGS']['DEFAULT_VALUE'])) {
                     if (is_array($arRes[$fieldName]['SETTINGS']['DEFAULT_VALUE'])) {
                         if (!empty($arRes[$fieldName]['SETTINGS']['DEFAULT_VALUE']['VALUE'])) {
                             $result = $arRes[$fieldName]['SETTINGS']['DEFAULT_VALUE']['VALUE'];
                         }
                     } else {
                         $result = $arRes[$fieldName]['SETTINGS']['DEFAULT_VALUE'];
                     }
                 }
             }
         }
     } elseif (preg_match("/(.*)&([0-9]+)/", $attr, $arMatch)) {
         if (intval($arLdapUser[strtolower($arMatch[1])]) & intval($arMatch[2])) {
             $result = "N";
         } else {
             $result = "Y";
         }
     } elseif ($fieldName == "PERSONAL_PHOTO") {
         if ($arLdapUser[strtolower($attr)] == "") {
             return false;
         }
         $fExt = CLdapUtil::GetImgTypeBySignature($arLdapUser[strtolower($attr)][0]);
         if (!$fExt) {
             return false;
         }
         $tmpDir = CTempFile::GetDirectoryName();
         CheckDirPath($tmpDir);
         $fname = "ad_" . rand() . "." . $fExt;
         if (!file_put_contents($tmpDir . $fname, $arLdapUser[strtolower($attr)][0])) {
             return false;
         }
         $result = array("name" => $fname, "type" => CFile::GetContentType($tmpDir . $fname), "tmp_name" => $tmpDir . $fname);
     } else {
         $result = $arLdapUser[strtolower($attr)];
     }
     if (is_null($result)) {
         $result = false;
     }
     return $result;
 }
Exemplo n.º 4
0
                        break;
                    }
                }
            }
            $res = '
				<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
				<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="' . LANGUAGE_ID . '" lang="' . LANGUAGE_ID . '">
				<body>
				<script>alert("' . GetMessage("HK_EXP_FALSE") . '");
				window.close();
				</script>
				</body></html>';
            break;
        case 'import':
            if (!$_FILES['bx_hk_filename']['name'] || !$_FILES['bx_hk_filename']['size']) {
                $res = '<script type="text/javascript">window.parent.BXHotKeys.OnImportResponse(0);</script>';
                break;
            }
            $numImported = 0;
            $tmpDir = CTempFile::GetDirectoryName();
            CheckDirPath($tmpDir);
            $name = $tmpDir . basename($_FILES['bx_hk_filename']['name']);
            if (move_uploaded_file($_FILES['bx_hk_filename']['tmp_name'], $tmpDir . CHotKeys::$ExpImpFileName)) {
                $numImported = $hkInstance->Import($tmpDir . CHotKeys::$ExpImpFileName, $uid);
            }
            $res = '<script type="text/javascript">window.parent.BXHotKeys.OnImportResponse("' . $numImported . '");</script>';
            break;
    }
    echo $res;
}
require $_SERVER["DOCUMENT_ROOT"] . BX_ROOT . "/modules/main/include/epilog_admin_after.php";
Exemplo n.º 5
0
	/**
	 * @param $script - url for detail
	 */
	function __construct($params = array(), $doCheckPost = true)
	{
		global $APPLICATION;
		$this->errorCode = array(
			"BXU344" => GetMessage("UP_CID_IS_REQUIRED"),
			"BXU344.1" => GetMessage("UP_PACKAGE_INDEX_IS_REQUIRED"),
			"BXU345" => GetMessage("UP_BAD_SESSID"),
			"BXU346" => GetMessage("UP_NOT_ENOUGH_PERMISSION"),
			"BXU347" => GetMessage("UP_FILE_IS_LOST"),
			"BXU348" => GetMessage("UP_FILE_IS_NOT_UPLOADED"));
		$params = (is_array($params) ? $params : array());
		$this->script = (array_key_exists("urlToUpload", $params) ? $params["urlToUpload"] : $APPLICATION->GetCurPageParam());
		if (array_key_exists("copies", $params) && is_array($params["copies"]))
		{
			$copies = array();
			foreach($params["copies"] as $key => $val)
			{
				if (is_array($val) && (array_key_exists("width", $val) || array_key_exists("height", $val)))
					$copies[$key] = array("width" => $val["width"], "height" => $val["height"]);
			}
			if (!empty($copies))
				$this->params["copies"] = $copies;
		}
		if (array_key_exists("uploadFileWidth", $params))
			$this->params["uploadFileWidth"] = $params["uploadFileWidth"];
		if (array_key_exists("uploadFileHeight", $params))
			$this->params["uploadFileHeight"] = $params["uploadFileHeight"];
		if (array_key_exists("uploadMaxFilesize", $params))
			$this->params["uploadMaxFilesize"] = $params["uploadMaxFilesize"];

		if (array_key_exists("events", $params) && is_array($params["events"]))
		{
			foreach($params["events"] as $key => $val)
			{
				AddEventHandler(self::EVENT_NAME, $key, $val);
			}
		}
		if (array_key_exists("allowUpload", $params))
		{
			// ALLOW_UPLOAD = 'A'll files | 'I'mages | 'F'iles with selected extensions
			// ALLOW_UPLOAD_EXT = comma-separated list of allowed file extensions (ALLOW_UPLOAD='F')
			$this->params["allowUpload"] = (in_array($params["allowUpload"], array("A", "I", "F")) ? $params["allowUpload"] : "A");
			if ($params["allowUpload"] == "F" && empty($params["allowUploadExt"]))
				$this->params["allowUpload"] = "A";
			$this->params["allowUploadExt"] = $params["allowUploadExt"];
		}
		if (array_key_exists("controlId", $params))
			$this->controlId = $params["controlId"];
		$this->params["controlId"] = $this->controlId;
		$this->path = CTempFile::GetDirectoryName(
			12,
			array(
				"bxu",
				md5(serialize(array(
					$this->controlId,
					bitrix_sessid(),
					CMain::GetServerUniqID()
					))
				)
			)
		);
		if ($doCheckPost !== false && !$this->checkPost(($doCheckPost === true || $doCheckPost == "post")))
		{
			$this->showError();
		}
		return $this;
	}
Exemplo n.º 6
0
$strError = '';
$arResult['STEP'] = isset($_POST['step']) ? intval($_POST['step']) : 1;
if ($_SERVER['REQUEST_METHOD'] == 'POST' && check_bitrix_sessid()) {
    if (isset($_POST['next'])) {
        if ($arResult['STEP'] == 1) {
            if ($_FILES['IMPORT_FILE']['error'] > 0) {
                ShowError(GetMessage('CRM_CSV_NF_ERROR'));
            } else {
                $error = CFile::CheckFile($_FILES['IMPORT_FILE'], 0, 0, 'csv,txt');
                if ($error !== '') {
                    ShowError($error);
                } else {
                    if (isset($_SESSION['CRM_IMPORT_FILE'])) {
                        unset($_SESSION['CRM_IMPORT_FILE']);
                    }
                    $sTmpFilePath = CTempFile::GetDirectoryName(12, 'crm');
                    CheckDirPath($sTmpFilePath);
                    $_SESSION['CRM_IMPORT_FILE_SKIP_EMPTY'] = isset($_POST['IMPORT_FILE_SKIP_EMPTY']) && $_POST['IMPORT_FILE_SKIP_EMPTY'] == 'Y' ? true : false;
                    $_SESSION['CRM_IMPORT_FILE_FIRST_HEADER'] = isset($_POST['IMPORT_FILE_FIRST_HEADER']) && $_POST['IMPORT_FILE_FIRST_HEADER'] == 'Y' ? true : false;
                    $_SESSION['CRM_IMPORT_FILE'] = $sTmpFilePath . md5($_FILES['IMPORT_FILE']['tmp_name']) . '.tmp';
                    $_SESSION['CRM_IMPORT_FILE_POS'] = 0;
                    move_uploaded_file($_FILES['IMPORT_FILE']['tmp_name'], $_SESSION['CRM_IMPORT_FILE']);
                    @chmod($_SESSION['CRM_IMPORT_FILE'], BX_FILE_PERMISSIONS);
                    if (isset($_POST['IMPORT_FILE_ENCODING'])) {
                        $fileEncoding = $_POST['IMPORT_FILE_ENCODING'];
                        if ($fileEncoding !== '' && $fileEncoding !== '_' && $fileEncoding !== strtolower(SITE_CHARSET)) {
                            $convertCharsetErrorMsg = '';
                            $fileHandle = fopen($_SESSION['CRM_IMPORT_FILE'], 'rb');
                            $fileContents = fread($fileHandle, filesize($_SESSION['CRM_IMPORT_FILE']));
                            fclose($fileHandle);
                            //HACK: Remove UTF-8 BOM
Exemplo n.º 7
0
$db_res = CLanguage::GetList($b = "sort", $o = "asc");
while ($res = $db_res->Fetch()) {
    $arLang[$res["LID"]] = $res;
    $arLangTitle["reference_id"][] = $res["LID"];
    $arLangTitle["reference"][] = htmlspecialcharsbx($res["NAME"]);
}
$bInitVars = false;
$bImportComplete = false;
$APPLICATION->SetTitle(GetMessage("SMILE_IMPORT_TITLE"));
$fileName = '';
if ($REQUEST_METHOD == "POST" && (strlen($save) > 0 || strlen($apply) > 0)) {
    $fileName = 'import' . $USER->GetID() . time() . '.zip';
    if (!check_bitrix_sessid()) {
        $arError[] = array("id" => "bad_sessid", "text" => GetMessage("ERROR_BAD_SESSID"));
    } elseif (!empty($_FILES["IMPORT"]["tmp_name"])) {
        $sUploadDir = CTempFile::GetDirectoryName(1);
        CheckDirPath($sUploadDir);
        $res = CFile::CheckFile($_FILES["IMPORT"], 500000, false, 'zip');
        if (strLen($res) > 0) {
            $arError[] = array("id" => "IMPORT", "text" => $res);
        } elseif (file_exists($sUploadDir . $fileName)) {
            $arError[] = array("id" => "IMPORT", "text" => GetMessage("ERROR_EXISTS_FILE"));
        } elseif (!@copy($_FILES["IMPORT"]["tmp_name"], $sUploadDir . $fileName)) {
            $arError[] = array("id" => "IMPORT", "text" => GetMessage("ERROR_COPY_FILE"));
        } else {
            @chmod($sUploadDir . $fileName, BX_FILE_PERMISSIONS);
        }
    } elseif (empty($_FILES["IMPORT"]["tmp_name"])) {
        $arError[] = array("id" => "IMPORT", "text" => GetMessage("ERROR_EXISTS_FILE"));
    }
    if (empty($arError)) {
Exemplo n.º 8
0
 /**
  * Exports current user's binded hot keys and using custom codes
  * @return string exported file name
  * */
 public function Export()
 {
     $this->LoadToCache();
     if (!is_array($this->arList) || empty($this->arList)) {
         return false;
     }
     $arForExport = array();
     $tmpDir = CTempFile::GetDirectoryName();
     CheckDirPath($tmpDir);
     $tmpExportFile = $tmpDir . self::$ExpImpFileName;
     foreach ($this->arList as $arHK) {
         $res = self::$codes->GetByID($arHK['CODE_ID']);
         $arTmpCode = $res->Fetch();
         if (!is_array($arTmpCode) || empty($arTmpCode)) {
             continue;
         }
         $arTmpLink = array('KEYS_STRING' => $arHK['KEYS_STRING'], 'CLASS_NAME' => $arTmpCode['CLASS_NAME'], 'NAME' => $arTmpCode['NAME'], 'IS_CUSTOM' => $arTmpCode['IS_CUSTOM']);
         if ($arTmpCode['IS_CUSTOM']) {
             $arTmpLink['CODE'] = $arTmpCode['CODE'];
             $arTmpLink['COMMENTS'] = $arTmpCode['COMMENTS'];
             $arTmpLink['URL'] = $arTmpCode['URL'];
         }
         $arForExport[] = $arTmpLink;
     }
     $result = file_put_contents($tmpExportFile, serialize($arForExport));
     if ($result === false) {
         return false;
     }
     return $tmpExportFile;
 }
Exemplo n.º 9
0
				Input params
********************************************************************/
/***************** BASE ********************************************/
$arParams["IBLOCK_TYPE"] = trim($arParams["IBLOCK_TYPE"]);
$arParams["IBLOCK_ID"] = intVal($arParams["IBLOCK_ID"]);
$arParams["SECTION_ID"] = intVal($arParams["SECTION_ID"]);
$arParams["USER_ALIAS"] = trim($arParams["USER_ALIAS"]);
$arParams["BEHAVIOUR"] = $arParams["BEHAVIOUR"] == "USER" ? "USER" : "SIMPLE";
$arParams["PERMISSION_EXTERNAL"] = trim($arParams["PERMISSION"]);
$arParams["IMAGE_UPLOADER_ACTIVEX_CLSID"] = "718B3D1E-FF0C-4EE6-9F3B-0166A5D1C1B9";
$arParams["IMAGE_UPLOADER_ACTIVEX_CONTROL_VERSION"] = "6,0,20,0";
$arParams["IMAGE_UPLOADER_JAVAAPPLET_VERSION"] = "6.0.20.0";
$arParams["THUMBNAIL_ACTIVEX_CLSID"] = "58C8ACD5-D8A6-4AC8-9494-2E6CCF6DD2F8";
$arParams["THUMBNAIL_ACTIVEX_CONTROL_VERSION"] = "3,5,204,0";
$arParams["THUMBNAIL_JAVAAPPLET_VERSION"] = "1.1.81.0";
$arParams["PATH_TO_TMP"] = CTempFile::GetDirectoryName(12, "uploader");
/***************** URL *********************************************/
$URL_NAME_DEFAULT = array("index" => "", "gallery" => "PAGE_NAME=gallery&USER_ALIAS=#USER_ALIAS#", "section" => "PAGE_NAME=section" . ($arParams["BEHAVIOUR"] == "USER" ? "&USER_ALIAS=#USER_ALIAS#" : "") . "&SECTION_ID=#SECTION_ID#", "section_edit" => "PAGE_NAME=section_edit" . ($arParams["BEHAVIOUR"] == "USER" ? "&USER_ALIAS=#USER_ALIAS#" : "") . "&SECTION_ID=#SECTION_ID#");
foreach ($URL_NAME_DEFAULT as $URL => $URL_VALUE) {
    $arParams[strToUpper($URL) . "_URL"] = trim($arParams[strToUpper($URL) . "_URL"]);
    if (empty($arParams[strToUpper($URL) . "_URL"])) {
        $arParams[strToUpper($URL) . "_URL"] = $APPLICATION->GetCurPage() . "?" . $URL_VALUE;
    }
    $arParams["~" . strToUpper($URL) . "_URL"] = $arParams[strToUpper($URL) . "_URL"];
    $arParams[strToUpper($URL) . "_URL"] = htmlspecialcharsbx($arParams["~" . strToUpper($URL) . "_URL"]);
}
$arParams["SUCCESS_URL"] = CHTTP::urlDeleteParams(CComponentEngine::MakePathFromTemplate($arParams["~SECTION_URL"], array("USER_ALIAS" => $arParams["USER_ALIAS"], "SECTION_ID" => $arParams["SECTION_ID"])), array("sessid", "uploader_redirect"), true);
$arParams["REDIRECT_URL"] = $arParams["ACTION_URL"];
$arParams["REDIRECT_URL"] = CHTTP::urlDeleteParams($arParams["REDIRECT_URL"], array("clear_cache", "bitrix_include_areas", "bitrix_show_mode", "back_url_admin", "bx_photo_ajax", "change_view_mode_data", "sessid", "uploader_redirect"));
$arParams["REDIRECT_URL"] .= (strpos($arParams["REDIRECT_URL"], "?") === false ? "?" : "&") . "uploader_redirect=Y&sessid=" . bitrix_sessid();
$arParams["SIMPLE_FORM_URL"] = $APPLICATION->GetCurPageParam("view_mode=form&" . bitrix_sessid_get(), array("view_mode", "sessid", "uploader_redirect"));
Exemplo n.º 10
0
 function OnPostForm()
 {
     $wizard =& $this->GetWizard();
     if ($wizard->IsNextButtonClick() || $wizard->IsFinishButtonClick()) {
         $locations_csv = $wizard->GetVar('locations_csv');
         $load_zip = $wizard->GetVar('load_zip');
         if (strlen($locations_csv) <= 0 && $load_zip != 'Y') {
             $this->SetError(GetMessage('WSL_STEP2_GFILE_ERROR'), 'locations_csv');
         }
         if ($locations_csv == "locations.csv") {
             if (!is_uploaded_file($_FILES["FILE_IMPORT_UPLOAD"]["tmp_name"]) || !file_exists($_FILES["FILE_IMPORT_UPLOAD"]["tmp_name"])) {
                 $this->SetError(GetMessage("NO_LOC_FILE"), 'locations_csv');
             } else {
                 $fp = fopen($_FILES["FILE_IMPORT_UPLOAD"]["tmp_name"], 'r');
                 $contents = fread($fp, filesize($_FILES["FILE_IMPORT_UPLOAD"]["tmp_name"]));
                 fclose($fp);
                 $contents = $GLOBALS["APPLICATION"]->ConvertCharset($contents, 'windows-1251', LANG_CHARSET);
                 $sTmpFilePath = CTempFile::GetDirectoryName(12, 'sale');
                 CheckDirPath($sTmpFilePath);
                 $fp = fopen($sTmpFilePath . "locations.csv", 'w+');
                 fwrite($fp, $contents);
                 fclose($fp);
             }
         }
     }
 }
Exemplo n.º 11
0
     $filename = preg_replace("#^(/tmp/|upload/1c/webdata)#", "", $_GET["filename"]);
     $filename = trim(str_replace("\\", "/", trim($filename)), "/");
     $io = CBXVirtualIo::GetInstance();
     $bBadFile = HasScriptExtension($filename) || IsFileUnsafe($filename) || !$io->ValidatePathString("/" . $filename);
     if (!$bBadFile) {
         $filename = trim(str_replace("\\", "/", trim($filename)), "/");
         $FILE_NAME = rel2abs($DIR_NAME, "/" . $filename);
         if (strlen($FILE_NAME) > 1 && $FILE_NAME === "/" . $filename) {
             $ABS_FILE_NAME = $DIR_NAME . $FILE_NAME;
             $WORK_DIR_NAME = substr($ABS_FILE_NAME, 0, strrpos($ABS_FILE_NAME, "/") + 1);
         }
     }
 }
 if ($_GET["mode"] == "init") {
     if ($arParams["USE_TEMP_DIR"] === "Y") {
         $DIR_NAME = CTempFile::GetDirectoryName(6, "1c_exchange");
     } else {
         $DIR_NAME = $_SERVER["DOCUMENT_ROOT"] . "/" . COption::GetOptionString("main", "upload_dir", "upload") . "/1c_exchange/";
         DeleteDirFilesEx(substr($DIR_NAME, strlen($_SERVER["DOCUMENT_ROOT"])));
     }
     CheckDirPath($DIR_NAME);
     if (!is_dir($DIR_NAME)) {
         echo "failure\n" . GetMessage("CC_BSC1_ERROR_INIT");
     } else {
         $ht_name = $DIR_NAME . ".htaccess";
         if (!file_exists($ht_name)) {
             $fp = fopen($ht_name, "w");
             if ($fp) {
                 fwrite($fp, "Deny from All");
                 fclose($fp);
                 @chmod($ht_name, BX_FILE_PERMISSIONS);
Exemplo n.º 12
0
 protected static function downloadFile($fileName, $storeAs, $skip404 = false, $storeTo = false)
 {
     if ($storeTo === false) {
         $storeTo = \CTempFile::GetDirectoryName(5);
     }
     $storeTo .= $storeAs;
     if (file_exists($storeTo)) {
         if (!is_writable($storeTo)) {
             throw new Main\SystemException('Cannot remove previous ' . $storeAs . ' file');
         }
         unlink($storeTo);
     }
     $query = 'http://' . self::DISTRIBUTOR_HOST . ':' . self::DISTRIBUTOR_PORT . self::REMOTE_PATH . $fileName;
     $client = new HttpClient();
     if (!$client->download($query, $storeTo)) {
         $eFormatted = array();
         foreach ($client->getError() as $code => $desc) {
             $eFormatted[] = trim($desc . ' (' . $code . ')');
         }
         throw new Main\SystemException('File download failed: ' . implode(', ', $eFormatted) . ' (' . $query . ')');
     }
     $status = intval($client->getStatus());
     if ($status != 200 && file_exists($storeTo)) {
         unlink($storeTo);
     }
     $okay = $status == 200 || $status == 404 && $skip404;
     // honestly we should check for all 2xx codes, but for now this is enough
     if (!$okay) {
         throw new Main\SystemException('File download failed: http error ' . $status . ' (' . $query . ')');
     }
     return filesize($storeTo);
 }
Exemplo n.º 13
0
 function GetUserFields($arLdapUser, &$departmentCache = FALSE)
 {
     global $APPLICATION;
     $arFields = array('DN' => $arLdapUser['dn'], 'LOGIN' => $arLdapUser[strtolower($this->arFields['~USER_ID_ATTR'])], 'EXTERNAL_AUTH_ID' => 'LDAP#' . $this->arFields['ID'], 'LDAP_GROUPS' => $arLdapUser[strtolower($this->arFields['~USER_GROUP_ATTR'])]);
     // list of user field definitions
     $arRes = $GLOBALS["USER_FIELD_MANAGER"]->GetUserFields("USER", 0, LANGUAGE_ID);
     // for each field, do the conversion
     foreach ($this->arFields["FIELD_MAP"] as $userField => $attr) {
         if (is_array($arRes[$userField])) {
             //"USER_TYPE_ID"
             if ($arRes[$userField]["MULTIPLE"] == "Y") {
                 if (is_array($arLdapUser[strtolower($attr)])) {
                     $arFields[$userField] = array_values($arLdapUser[strtolower($attr)]);
                 } else {
                     $arFields[$userField] = array($arLdapUser[strtolower($attr)]);
                 }
             } else {
                 if (!empty($arLdapUser[strtolower($attr)])) {
                     $arFields[$userField] = $arLdapUser[strtolower($attr)];
                 } else {
                     if (!empty($arRes[$userField]['SETTINGS']['DEFAULT_VALUE'])) {
                         if (is_array($arRes[$userField]['SETTINGS']['DEFAULT_VALUE'])) {
                             if (!empty($arRes[$userField]['SETTINGS']['DEFAULT_VALUE']['VALUE'])) {
                                 $arFields[$userField] = $arRes[$userField]['SETTINGS']['DEFAULT_VALUE']['VALUE'];
                             }
                         } else {
                             $arFields[$userField] = $arRes[$userField]['SETTINGS']['DEFAULT_VALUE'];
                         }
                     }
                 }
             }
         } elseif (preg_match("/(.*)&([0-9]+)/", $attr, $arMatch)) {
             if (intval($arLdapUser[strtolower($arMatch[1])]) & intval($arMatch[2])) {
                 $arFields[$userField] = "N";
             } else {
                 $arFields[$userField] = "Y";
             }
         } elseif ($userField == "PERSONAL_PHOTO") {
             $arFields["PERSONAL_PHOTO"] = "";
             if ($arLdapUser[strtolower($attr)] == "") {
                 continue;
             }
             $fExt = CLdapUtil::GetImgTypeBySignature($arLdapUser[strtolower($attr)][0]);
             if (!$fExt) {
                 continue;
             }
             $tmpDir = CTempFile::GetDirectoryName();
             CheckDirPath($tmpDir);
             $fname = "ad_" . rand() . "." . $fExt;
             if (!file_put_contents($tmpDir . $fname, $arLdapUser[strtolower($attr)][0])) {
                 continue;
             }
             $arFields["PERSONAL_PHOTO"] = array("name" => $fname, "type" => CFile::GetContentType($tmpDir . $fname), "tmp_name" => $tmpDir . $fname);
         } else {
             $arFields[$userField] = $arLdapUser[strtolower($attr)];
         }
         if (is_null($arFields[$userField])) {
             $arFields[$userField] = false;
         }
     }
     $APPLICATION->ResetException();
     $db_events = GetModuleEvents("ldap", "OnLdapUserFields");
     while ($arEvent = $db_events->Fetch()) {
         $arParams = array(array(&$arFields, $arLdapUser));
         if (ExecuteModuleEventEx($arEvent, $arParams) === false) {
             if (!($err = $APPLICATION->GetException())) {
                 $APPLICATION->ThrowException("Unknown error");
             }
             return false;
         }
         $arFields = $arParams[0][0];
     }
     // set a department field, if needed
     if (empty($arFields['UF_DEPARTMENT']) && isModuleInstalled('intranet') && $this->arFields['IMPORT_STRUCT'] && $this->arFields['IMPORT_STRUCT'] == 'Y') {
         //$arLdapUser[$this->arFields['USER_DN_ATTR']]
         $username = $arLdapUser[$this->arFields['USER_ID_ATTR']];
         if ($arDepartment = $this->GetDepartmentIdForADUser($arLdapUser[$this->arFields['USER_DEPARTMENT_ATTR']], $arLdapUser[$this->arFields['USER_MANAGER_ATTR']], $username, $departmentCache)) {
             // fill in cache. it is done outside the function because it has many exit points
             if ($departmentCache) {
                 $departmentCache[$username] = $arDepartment;
             }
             // this is not final assignment
             // $arFields['UF_DEPARTMENT'] sould contain array of department ids
             // but somehow we have to return an information whether this user is a department head
             // so we'll save this data here temporarily
             $arFields['UF_DEPARTMENT'] = $arDepartment;
         } else {
             $arFields['UF_DEPARTMENT'] = array();
         }
         // at this point $arFields['UF_DEPARTMENT'] should be set to some value, even an empty array is ok
     }
     if (!is_array($arFields['LDAP_GROUPS'])) {
         $arFields['LDAP_GROUPS'] = !empty($arFields['LDAP_GROUPS']) ? array($arFields['LDAP_GROUPS']) : array();
     }
     $primarygroupid_name_attr = 'primarygroupid';
     $primarygrouptoken_name_attr = 'primarygrouptoken';
     if ($this->arFields['USER_GROUP_ACCESSORY'] == 'Y') {
         $primarygroupid_name_attr = strtolower($this->arFields['GROUP_ID_ATTR']);
         $primarygrouptoken_name_attr = strtolower($this->arFields['USER_GROUP_ATTR']);
         $userIdAttr = strtolower($this->arFields['USER_ID_ATTR']);
         $groupMemberAttr = strtolower($this->arFields['GROUP_MEMBERS_ATTR']);
     }
     $arAllGroups = $this->GetGroupListArray();
     if (!is_array($arAllGroups) || count($arAllGroups) <= 0) {
         return $arFields;
     }
     $arGroup = reset($arAllGroups);
     do {
         if (in_array($arGroup['ID'], $arFields['LDAP_GROUPS'])) {
             continue;
         }
         if (is_set($arLdapUser, $primarygroupid_name_attr) && $arGroup[$primarygrouptoken_name_attr] == $arLdapUser[$primarygroupid_name_attr] || $this->arFields['USER_GROUP_ACCESSORY'] == 'Y' && is_set($arGroup, $groupMemberAttr) && (is_array($arGroup[$groupMemberAttr]) && in_array($arLdapUser[$userIdAttr], $arGroup[$groupMemberAttr]) || $arLdapUser[$userIdAttr] == $arGroup[$groupMemberAttr])) {
             $arFields['LDAP_GROUPS'][] = $arGroup['ID'];
             if ($this->arFields['USER_GROUP_ACCESSORY'] == 'N') {
                 break;
             }
         }
     } while ($arGroup = next($arAllGroups));
     return $arFields;
 }
Exemplo n.º 14
0
	private function fillRequireData($requestType)
	{
		$this->mode = $this->getPost("mode", $requestType);
		$this->CID = $this->getPost("CID", $requestType);
		$this->path = CTempFile::GetDirectoryName(
			12,
			array(
				"bxu",
				md5(serialize(array(
					"CID" => $this->CID,
					"sessid" => freetrix_sessid()))
				)
			)
		);
		if (in_array($this->mode, array("upload", "delete", "view")))
		{
			if (empty($this->CID))
				$this->error = "BXU344";
			else if (!check_freetrix_sessid())
				$this->error = "BXU345";
			else if (!CheckDirPath($this->path))
				$this->error .= "BXU346";
			else if ($this->getPost("packageIndex", $requestType))
			{
				$this->package = array(
					"handler" => CBXVirtualIo::GetInstance()->GetFile($this->path.$this->getPost("packageIndex").".package"),
					"id" => $this->getPost("packageIndex"),
					"data" => array("filesCount" => intval($this->getPost("filesCount")), "files" => array())
				);
				if ($this->package["handler"]->IsExists())
					$this->package["data"] = unserialize($this->package["handler"]->GetContents());
			}
			else if ($this->mode == "upload")
				$this->error = "BXU344.1";

			$this->uploading = array(
				"handler" => CBXVirtualIo::GetInstance()->GetFile($this->path.".log"),
				"data" => array());
			if ($this->uploading["handler"]->IsExists())
				$this->uploading["data"] = unserialize($this->uploading["handler"]->GetContents());

			return true;
		}
		return false;
	}
Exemplo n.º 15
0
        echo "success\n";
        echo session_name() . "\n";
        echo session_id() . "\n";
        echo bitrix_sessid_get() . "\n";
    }
} elseif (!check_bitrix_sessid()) {
    echo "failure\n", GetMessage("CC_BCIH_ERROR_SOURCE_CHECK");
} elseif (!$USER->IsAuthorized()) {
    echo "failure\n", GetMessage("CC_BCIH_ERROR_AUTHORIZE");
} elseif (!$bUSER_HAVE_ACCESS) {
    echo "failure\n", GetMessage("CC_BCIH_PERMISSION_DENIED");
} elseif (!CModule::IncludeModule('highloadblock')) {
    echo "failure\n", GetMessage("CC_BCIH_ERROR_MODULE");
} elseif ($_GET["mode"] == "init") {
    if ($arParams["USE_TEMP_DIR"] === "Y") {
        $DIR_NAME = CTempFile::GetDirectoryName(6, "1c_highloadblock");
    } else {
        //Cleanup previous import files
        $directory = new \Bitrix\Main\IO\Directory($DIR_NAME);
        if ($directory->isExists()) {
            $directory->delete();
        }
    }
    CheckDirPath($DIR_NAME);
    if (!is_dir($DIR_NAME)) {
        echo "failure\n", GetMessage("CC_BCIH_ERROR_INIT");
    } else {
        $_SESSION["BX_HL_IMPORT"] = array("zip" => $arParams["USE_ZIP"] && function_exists("zip_open"), "TEMP_DIR" => $arParams["USE_TEMP_DIR"] === "Y" ? $DIR_NAME : "", "NS" => array("XMLPOS" => "", "SESSID" => md5($_REQUEST["sessid"])));
        echo "zip=" . ($_SESSION["BX_HL_IMPORT"]["zip"] ? "yes" : "no") . "\n";
        echo "file_limit=" . $arParams["FILE_SIZE_LIMIT"];
    }
Exemplo n.º 16
0
    die;
}
if (!CModule::IncludeModule('crm')) {
    return;
}
if (!CModule::IncludeModule('sale')) {
    return;
}
global $USER;
$CCrmPerms = new CCrmPerms($USER->GetID());
if ($CCrmPerms->HavePerm('CONFIG', BX_CRM_PERM_NONE, 'WRITE')) {
    ShowError(GetMessage('CRM_LOC_IMP_ERROR_ACCESS_DENIED'));
    return;
}
CUtil::InitJSCore();
$arResult["TMP_PATH"] = CTempFile::GetDirectoryName(12, 'crm');
CheckDirPath($arResult["TMP_PATH"]);
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (check_bitrix_sessid()) {
        $arResult['BACK_URL'] = isset($_POST['BACK_URL']) ? $_POST['BACK_URL'] : '';
        $locations_csv = $_POST['locations_csv'];
        $load_zip = isset($_POST['load_zip']) && $_POST['load_zip'] == 'Y' ? 'Y' : 'N';
        $errorMsg = '';
        if (strlen($locations_csv) <= 0 && $load_zip != 'Y') {
            $errorMsg .= GetMessage('CRM_LOC_IMP_GFILE_ERROR');
        }
        if ($locations_csv == "locations.csv") {
            if (!is_uploaded_file($_FILES["FILE_IMPORT_UPLOAD"]["tmp_name"]) || !file_exists($_FILES["FILE_IMPORT_UPLOAD"]["tmp_name"])) {
                $errorMsg .= GetMessage("CRM_LOC_IMP_NO_LOC_FILE");
            } else {
                $fp = fopen($_FILES["FILE_IMPORT_UPLOAD"]["tmp_name"], 'r');
 function Export($documentId)
 {
     $work_dir = CTempFile::GetDirectoryName();
     CheckDirPath($work_dir);
     $file = "import";
     $file_name = $work_dir . $file . ".xml";
     $file_dir = $file . "_files/";
     $arcname = $work_dir . $file . '.tar.gz';
     if ($fp = fopen($file_name, "ab")) {
         $documentService = $this->workflow->GetService("DocumentService");
         $document = $documentService->GetDocument($documentId);
         $obExport = new CIBlockCMLExport();
         $step = array();
         $PROPERTY_MAP = array();
         $SECTION_MAP = array();
         if ($obExport->Init($fp, $document["IBLOCK_ID"], $step, true, $work_dir, $file_dir)) {
             $obExport->StartExport();
             $obExport->StartExportMetadata();
             $obExport->ExportProperties($PROPERTY_MAP);
             $obExport->ExportSections($SECTION_MAP, time(), 0);
             $obExport->EndExportMetadata();
             $obExport->StartExportCatalog(true, true);
             $obExport->ExportElements($PROPERTY_MAP, $SECTION_MAP, time(), 0, 0, array("SHOW_NEW" => "Y", "IBLOCK_ID" => $document["IBLOCK_ID"], "=ID" => $document["ID"]));
             $obExport->EndExportCatalog();
             $obExport->EndExport();
             fclose($fp);
             include_once $_SERVER["DOCUMENT_ROOT"] . BX_ROOT . '/modules/main/classes/general/tar_gz.php';
             $ob = new CArchiver($arcname);
             $res = $ob->Add('"' . $file_name . '"', false, $work_dir);
             if ($res) {
                 $res = $ob->Add('"' . $work_dir . $file_dir . '"', false, $work_dir);
             }
             if ($res) {
                 return $arcname;
             } else {
                 return '';
             }
         } else {
             return '';
         }
     } else {
         return '';
     }
 }
Exemplo n.º 18
0
 }
 $fp = $f->Open("rb");
 if (!is_resource($fp)) {
     $message = new CAdminMessage(GetMessage("CLO_STORAGE_FILE_UPLOAD_ERROR"), new CApplicationException(GetMessage("CLO_STORAGE_FILE_OPEN_ERROR")));
     break;
 }
 $bytes = 0;
 $fileSize = $f->GetFileSize();
 if ($fileSize > $obBucket->GetService()->GetMinUploadPartSize()) {
     $obUpload = new CCloudStorageUpload($filePath);
     if (!$obUpload->isStarted()) {
         if ($obBucket->FileExists($filePath)) {
             $message = new CAdminMessage(GetMessage("CLO_STORAGE_FILE_UPLOAD_ERROR"), new CApplicationException(GetMessage("CLO_STORAGE_FILE_EXISTS_ERROR")));
             break;
         }
         $tempFile = CTempFile::GetDirectoryName(6, "clouds_upload") . $f->GetName();
         $tempFileX = $io->GetPhysicalName($tempFile);
         CheckDirPath($tempFileX);
         if (copy($_FILES["upload"]["tmp_name"], $tempFileX)) {
             if ($obUpload->Start($obBucket->ID, $fileSize, CFile::GetContentType($tempFile), $tempFile)) {
                 $moveResult = CCloudStorage::FILE_PARTLY_UPLOADED;
             } else {
                 $strError = GetMessage("CLO_STORAGE_FILE_UNKNOWN_ERROR", array("#CODE#" => "e01"));
             }
         } else {
             $strError = GetMessage("CLO_STORAGE_FILE_UNKNOWN_ERROR", array("#CODE#" => "e04"));
         }
     } else {
         $pos = $obUpload->getPos();
         if ($pos > $fileSize) {
             if ($obUpload->Finish()) {
Exemplo n.º 19
0
 public static function import($arParams)
 {
     global $APPLICATION;
     // check fields
     $aMsg = array();
     $arParams['SET_ID'] = intval($arParams['SET_ID']);
     $arParams['IMPORT_IF_FILE_EXISTS'] = isset($arParams['IMPORT_IF_FILE_EXISTS']) && $arParams['IMPORT_IF_FILE_EXISTS'] == 'Y' ? true : false;
     if (isset($arParams['FILE']) && GetFileExtension($arParams['FILE']) != 'zip') {
         $aMsg["FILE_EXT"] = array("id" => "FILE_EXT", "text" => GetMessage("MAIN_SMILE_IMPORT_FILE_EXT_ERROR"));
     } else {
         if (!isset($arParams['FILE']) || !file_exists($arParams['FILE'])) {
             $aMsg["FILE"] = array("id" => "FILE", "text" => GetMessage("MAIN_SMILE_IMPORT_FILE_ERROR"));
         } else {
             if ($arParams['SET_ID'] <= 0) {
                 $aMsg["SET_ID"] = array("id" => "SET_ID", "text" => GetMessage("MAIN_SMILE_IMPORT_SET_ID_ERROR"));
             }
         }
     }
     if (!empty($aMsg)) {
         $e = new CAdminException($aMsg);
         $APPLICATION->ThrowException($e);
         return false;
     }
     $sUnpackDir = CTempFile::GetDirectoryName(1);
     CheckDirPath($sUnpackDir);
     /** @var IBXArchive $oArchiver */
     $oArchiver = CBXArchive::GetArchive($arParams['FILE'], "ZIP");
     $oArchiver->SetOptions(array("STEP_TIME" => 300));
     if (!$oArchiver->Unpack($sUnpackDir)) {
         $aMsg["UNPACK"] = array("id" => "UNPACK", "text" => GetMessage("MAIN_SMILE_IMPORT_UNPACK_ERROR"));
         $e = new CAdminException($aMsg);
         $APPLICATION->ThrowException($e);
         return false;
     }
     $arSmiles = array();
     if (file_exists($sUnpackDir . 'install.csv')) {
         $arLang = array();
         $db_res = CLanguage::GetList($b = "sort", $o = "asc");
         while ($res = $db_res->Fetch()) {
             if (file_exists($sUnpackDir . 'install_lang_' . $res["LID"] . '.csv')) {
                 $arSmiles = array();
                 $csvFile = new CCSVData();
                 $csvFile->LoadFile($sUnpackDir . 'install_lang_' . $res["LID"] . '.csv');
                 $csvFile->SetFieldsType("R");
                 $csvFile->SetFirstHeader(false);
                 while ($smile = $csvFile->Fetch()) {
                     if (defined('BX_UTF') && BX_UTF && $res["LID"] == 'ru') {
                         $smile[1] = $APPLICATION->ConvertCharset($smile[1], 'windows-1251', 'utf-8');
                     }
                     $arLang[$smile[0]][$res["LID"]] = $smile[1];
                 }
             }
         }
         $csvFile = new CCSVData();
         $csvFile->LoadFile($sUnpackDir . 'install.csv');
         $csvFile->SetFieldsType("R");
         $csvFile->SetFirstHeader(false);
         while ($smileRes = $csvFile->Fetch()) {
             $smile = array('TYPE' => $smileRes[0], 'CLICKABLE' => $smileRes[1] == 'Y' ? 'Y' : 'N', 'SORT' => intval($smileRes[2]), 'IMAGE' => $smileRes[3], 'IMAGE_WIDTH' => intval($smileRes[4]), 'IMAGE_HEIGHT' => intval($smileRes[5]), 'IMAGE_DEFINITION' => in_array($smileRes[6], array(self::IMAGE_SD, self::IMAGE_HD, self::IMAGE_UHD)) ? $smileRes[6] : ($smileRes[6] == 'Y' ? self::IMAGE_HD : self::IMAGE_SD), 'HIDDEN' => in_array($smileRes[7], array('Y', 'N')) ? $smileRes[7] : 'N', 'IMAGE_LANG' => in_array($smileRes[7], array('Y', 'N')) ? $smileRes[8] : $smileRes[7], 'TYPING' => in_array($smileRes[7], array('Y', 'N')) ? $smileRes[9] : $smileRes[8]);
             if (!in_array($smile['TYPE'], array(CSmile::TYPE_SMILE, CSmile::TYPE_ICON))) {
                 continue;
             }
             $smile['IMAGE'] = GetFileName($smile['IMAGE']);
             $imgArray = CFile::GetImageSize($sUnpackDir . $smile['IMAGE']);
             if (!is_array($imgArray)) {
                 continue;
             }
             $arInsert = array('TYPE' => $smile['TYPE'], 'SET_ID' => $arParams['SET_ID'], 'CLICKABLE' => $smile['CLICKABLE'], 'SORT' => $smile['SORT'], 'IMAGE' => $smile['IMAGE'], 'IMAGE_WIDTH' => $smile['IMAGE_WIDTH'], 'IMAGE_HEIGHT' => $smile['IMAGE_HEIGHT'], 'IMAGE_DEFINITION' => $smile['IMAGE_DEFINITION'], 'HIDDEN' => $smile['HIDDEN'], 'TYPING' => $smile['TYPING']);
             if (isset($arLang[$smile['IMAGE_LANG']])) {
                 $arInsert['LANG'] = $arLang[$smile['IMAGE_LANG']];
             }
             $arSmiles[] = $arInsert;
         }
     } else {
         $smileSet = CSmileSet::getById($arParams['SET_ID']);
         if ($handle = @opendir($sUnpackDir)) {
             $sort = 300;
             while (($file = readdir($handle)) !== false) {
                 if ($file == "." || $file == "..") {
                     continue;
                 }
                 if (is_file($sUnpackDir . $file)) {
                     $imgArray = CFile::GetImageSize($sUnpackDir . $file);
                     if (is_array($imgArray)) {
                         $smileHR = self::IMAGE_SD;
                         $smileType = CSmile::TYPE_SMILE;
                         $smileCode = GetFileNameWithoutExtension($file);
                         if (strpos($file, 'smile_') !== false && strpos($file, 'smile_') == 0) {
                             $smileCode = substr($smileCode, 6);
                         } elseif (strpos($file, 'smile') !== false && strpos($file, 'smile') == 0) {
                             $smileCode = substr($smileCode, 5);
                         } elseif (strpos($file, 'icon_') !== false && strpos($file, 'icon_') == 0) {
                             $smileType = CSmile::TYPE_ICON;
                             $smileCode = substr($smileCode, 5);
                         } else {
                             if (strpos($file, 'icon') !== false && strpos($file, 'icon') == 0) {
                                 $smileType = CSmile::TYPE_ICON;
                                 $smileCode = substr($smileCode, 4);
                             }
                         }
                         if (strrpos($smileCode, '_hr') !== false && strrpos($smileCode, '_hr') == strlen($smileCode) - 3) {
                             $smileHR = self::IMAGE_HD;
                             $smileCode = substr($smileCode, 0, strrpos($smileCode, '_hr'));
                         }
                         if ($pos = strpos($smileCode, '_hr_')) {
                             $smileHR = self::IMAGE_HD;
                             $smileCode = substr($smileCode, 0, $pos) . '_' . substr($smileCode, $pos + 4);
                         }
                         $arSmiles[] = array('TYPE' => $smileType, 'SET_ID' => $arParams['SET_ID'], 'CLICKABLE' => 'Y', 'SORT' => $sort, 'IMAGE' => $file, 'IMAGE_WIDTH' => intval($imgArray[0]), 'IMAGE_HEIGHT' => intval($imgArray[1]), 'IMAGE_DEFINITION' => $smileHR, 'TYPING' => ':' . (isset($smileSet['STRING_ID']) ? $smileSet['STRING_ID'] : $smileSet['ID']) . '/' . $smileCode . ':');
                         $sort = $sort + 5;
                     }
                 }
             }
             @closedir($handle);
         }
     }
     $importSmile = 0;
     foreach ($arSmiles as $smile) {
         $sUploadDir = ($smile['TYPE'] == CSmile::TYPE_ICON ? CSmile::PATH_TO_ICON : CSmile::PATH_TO_SMILE) . intval($smile["SET_ID"]) . '/';
         if (file_exists($sUnpackDir . $smile['IMAGE']) && ($arParams['IMPORT_IF_FILE_EXISTS'] || !file_exists($_SERVER["DOCUMENT_ROOT"] . $sUploadDir . $smile['IMAGE']))) {
             if (CheckDirPath($_SERVER["DOCUMENT_ROOT"] . $sUploadDir)) {
                 $insertId = CSmile::add($smile);
                 if ($insertId) {
                     if ($arParams['IMPORT_IF_FILE_EXISTS'] && file_exists($_SERVER["DOCUMENT_ROOT"] . $sUploadDir . $smile['IMAGE'])) {
                         $importSmile++;
                     } else {
                         if (copy($sUnpackDir . $smile['IMAGE'], $_SERVER["DOCUMENT_ROOT"] . $sUploadDir . $smile['IMAGE'])) {
                             @chmod($_SERVER["DOCUMENT_ROOT"] . $sUploadDir . $smile['IMAGE'], BX_FILE_PERMISSIONS);
                             $importSmile++;
                         } else {
                             CSmile::delete($insertId);
                         }
                     }
                 }
                 $APPLICATION->ResetException();
             }
         }
     }
     return $importSmile;
 }
Exemplo n.º 20
0
        echo session_name() . "\n";
        echo session_id() . "\n";
        echo bitrix_sessid_get() . "\n";
        echo "timestamp=" . time() . "\n";
    }
} elseif (!$arParams["SKIP_SOURCE_CHECK"] && !check_bitrix_sessid()) {
    echo "failure\n", GetMessage("CC_BSC1_ERROR_SOURCE_CHECK");
} elseif (!$USER->IsAuthorized()) {
    echo "failure\n", GetMessage("CC_BSC1_ERROR_AUTHORIZE");
} elseif (!$bUSER_HAVE_ACCESS) {
    echo "failure\n", GetMessage("CC_BSC1_PERMISSION_DENIED");
} elseif (!CModule::IncludeModule('iblock')) {
    echo "failure\n", GetMessage("CC_BSC1_ERROR_MODULE");
} elseif ($_GET["mode"] == "init") {
    if ($arParams["USE_TEMP_DIR"] === "Y") {
        $DIR_NAME = CTempFile::GetDirectoryName(6, "1c_catalog");
    } else {
        //Cleanup previous import files
        $this->cleanUpDirectory($DIR_NAME);
    }
    CheckDirPath($DIR_NAME);
    if (!is_dir($DIR_NAME)) {
        echo "failure\n", GetMessage("CC_BSC1_ERROR_INIT");
    } else {
        $_SESSION["BX_CML2_IMPORT"] = array("zip" => $arParams["USE_ZIP"] && function_exists("zip_open"), "TEMP_DIR" => $arParams["USE_TEMP_DIR"] === "Y" ? $DIR_NAME : "", "NS" => array("STEP" => 0), "SECTION_MAP" => false, "PRICES_MAP" => false);
        echo "zip=" . ($_SESSION["BX_CML2_IMPORT"]["zip"] ? "yes" : "no") . "\n";
        echo "file_limit=" . $arParams["FILE_SIZE_LIMIT"];
    }
} elseif ($_GET["mode"] == "file" && $ABS_FILE_NAME) {
    //Read http data
    if (function_exists("file_get_contents")) {
Exemplo n.º 21
0
 public static function MoveFile($arFile, $obTargetBucket)
 {
     $io = CBXVirtualIo::GetInstance();
     //Try to find suitable bucket for the file
     $bucket = CCloudStorage::FindBucketForFile($arFile, $arFile["FILE_NAME"]);
     if (!is_object($bucket)) {
         return CCloudStorage::FILE_SKIPPED;
     }
     if (!$bucket->Init()) {
         return CCloudStorage::FILE_SKIPPED;
     }
     //Check if this is same bucket as the target
     if ($bucket->ID != $obTargetBucket->ID) {
         return CCloudStorage::FILE_SKIPPED;
     }
     if ($bucket->FileExists($bucket->GetFileSRC($arFile))) {
         //TODO rename file
         return CCloudStorage::FILE_SKIPPED;
     }
     $filePath = "/" . $arFile["SUBDIR"] . "/" . $arFile["FILE_NAME"];
     $filePath = preg_replace("#[\\\\\\/]+#", "/", $filePath);
     if ($arFile["FILE_SIZE"] > $bucket->GetService()->GetMinUploadPartSize()) {
         $obUpload = new CCloudStorageUpload($filePath);
         if (!$obUpload->isStarted()) {
             if ($arFile["HANDLER_ID"]) {
                 $ar = array();
                 if (!CCloudStorage::OnMakeFileArray($arFile, $ar)) {
                     return CCloudStorage::FILE_SKIPPED;
                 }
                 if (!isset($ar["tmp_name"])) {
                     return CCloudStorage::FILE_SKIPPED;
                 }
             } else {
                 $ar = CFile::MakeFileArray($arFile["ID"]);
                 if (!isset($ar["tmp_name"])) {
                     return CCloudStorage::FILE_SKIPPED;
                 }
             }
             $temp_file = CTempFile::GetDirectoryName(2, "clouds") . bx_basename($arFile["FILE_NAME"]);
             $temp_fileX = $io->GetPhysicalName($temp_file);
             CheckDirPath($temp_fileX);
             if (!copy($io->GetPhysicalName($ar["tmp_name"]), $temp_fileX)) {
                 return CCloudStorage::FILE_SKIPPED;
             }
             if ($obUpload->Start($bucket->ID, $arFile["FILE_SIZE"], $arFile["CONTENT_TYPE"], $temp_file)) {
                 return CCloudStorage::FILE_PARTLY_UPLOADED;
             } else {
                 return CCloudStorage::FILE_SKIPPED;
             }
         } else {
             $temp_file = $obUpload->getTempFileName();
             $temp_fileX = $io->GetPhysicalName($temp_file);
             $fp = fopen($temp_fileX, "rb");
             if (!is_resource($fp)) {
                 return CCloudStorage::FILE_SKIPPED;
             }
             $pos = $obUpload->getPos();
             if ($pos > filesize($temp_fileX)) {
                 if ($obUpload->Finish()) {
                     $bucket->IncFileCounter(filesize($temp_fileX));
                     if ($arFile["HANDLER_ID"]) {
                         CCloudStorage::OnFileDelete($arFile);
                     } else {
                         $ar = CFile::MakeFileArray($arFile["ID"]);
                         $fileNameX = $io->GetPhysicalName($ar["tmp_name"]);
                         unlink($fileNameX);
                         @rmdir(substr($fileNameX, 0, -strlen(bx_basename($fileNameX))));
                     }
                     return CCloudStorage::FILE_MOVED;
                 } else {
                     return CCloudStorage::FILE_SKIPPED;
                 }
             }
             fseek($fp, $pos);
             self::$part_count = $obUpload->GetPartCount();
             self::$part_size = $obUpload->getPartSize();
             $part = fread($fp, self::$part_size);
             while ($obUpload->hasRetries()) {
                 if ($obUpload->Next($part)) {
                     return CCloudStorage::FILE_PARTLY_UPLOADED;
                 }
             }
             return CCloudStorage::FILE_SKIPPED;
         }
     } else {
         if ($arFile["HANDLER_ID"]) {
             $ar = array();
             if (!CCloudStorage::OnMakeFileArray($arFile, $ar)) {
                 return CCloudStorage::FILE_SKIPPED;
             }
             if (!isset($ar["tmp_name"])) {
                 return CCloudStorage::FILE_SKIPPED;
             }
         } else {
             $ar = CFile::MakeFileArray($arFile["ID"]);
             if (!isset($ar["tmp_name"])) {
                 return CCloudStorage::FILE_SKIPPED;
             }
         }
         $res = $bucket->SaveFile($filePath, $ar);
         if ($res) {
             $bucket->IncFileCounter(filesize($ar["tmp_name"]));
             if (file_exists($ar["tmp_name"])) {
                 unlink($ar["tmp_name"]);
                 @rmdir(substr($ar["tmp_name"], 0, -strlen(bx_basename($ar["tmp_name"]))));
             }
             if ($arFile["HANDLER_ID"]) {
                 CCloudStorage::OnFileDelete($arFile);
             }
         } else {
             //delete temporary copy
             if ($arFile["HANDLER_ID"]) {
                 unlink($ar["tmp_name"]);
                 @rmdir(substr($ar["tmp_name"], 0, -strlen(bx_basename($ar["tmp_name"]))));
             }
         }
         return $res ? CCloudStorage::FILE_MOVED : CCloudStorage::FILE_SKIPPED;
     }
 }
Exemplo n.º 22
0
 protected function getTemporalDirectory()
 {
     $wasCreated = false;
     if ((string) $this->data['LOCAL_PATH'] != '' && \Bitrix\Main\IO\Directory::isDirectoryExists($this->data['LOCAL_PATH'])) {
         $localPath = $this->data['LOCAL_PATH'];
     } else {
         $wasCreated = true;
         $localPath = \CTempFile::GetDirectoryName(10);
         if (!\Bitrix\Main\IO\Directory::isDirectoryExists($localPath)) {
             \Bitrix\Main\IO\Directory::createDirectory($localPath);
         }
     }
     return array($localPath, $wasCreated);
 }
Exemplo n.º 23
0
 function __construct($params = array())
 {
     $this->status = new Status("ready");
     global $APPLICATION;
     $this->script = $APPLICATION->GetCurPageParam();
     $this->setParams($params);
     $this->path = \CTempFile::GetDirectoryName(12, array("bxu", md5(serialize(array($this->controlId, bitrix_sessid(), \CMain::GetServerUniqID())))));
     $this->processTime["max"] = intval(ini_get("max_execution_time")) * 0.75;
     $this->processTime["start"] = time();
     $this->log = new Log();
     $this->packLog = new Log();
     $this->http = new HttpClient();
     set_time_limit(0);
     return $this;
 }
Exemplo n.º 24
0
function saleLocationImport($arParams)
{
    global $DB;
    $arReturn = array('STEP' => false, 'ERROR' => '', 'AMOUNT' => 0, 'POS' => 0, 'MESSAGE' => '');
    $step_length = intval($arParams["STEP_LENGTH"]);
    if ($step_length <= 0) {
        $step_length = 10;
    }
    define('ZIP_STEP_LENGTH', $step_length);
    define('LOC_STEP_LENGTH', $step_length);
    define('DLZIPFILE', $arParams["DLZIPFILE"]);
    $STEP = intval($arParams['STEP']);
    $CSVFILE = $arParams["CSVFILE"];
    $LOADZIP = $arParams["LOADZIP"];
    $bSync = $arParams["SYNC"] == "Y";
    if (isset($arParams['TMP_PATH'])) {
        $sTmpFilePath = $arParams['TMP_PATH'];
    } else {
        $sTmpFilePath = CTempFile::GetDirectoryName(12, 'sale');
    }
    if (strlen($CSVFILE) > 0 && !in_array($CSVFILE, array('loc_ussr.csv', 'loc_ua.csv', 'loc_kz.csv', 'loc_usa.csv', 'loc_cntr.csv', 'locations.csv'))) {
        //echo GetMessage('SL_IMPORT_ERROR_FILES');
        $arReturn['ERROR'] = GetMessage('SL_IMPORT_ERROR_FILES');
    } else {
        if ($STEP == 1 && strlen($CSVFILE) <= 0) {
            if ($LOADZIP == 'Y') {
                $STEP = 2;
            } else {
                $STEP = 3;
            }
        }
        switch ($STEP) {
            case 0:
                $arReturn['MESSAGE'] = GetMessage('WSL_IMPORT_FILES_LOADING');
                $arReturn['STEP'] = 1;
                break;
            case 1:
                $time_limit = ini_get('max_execution_time');
                if ($time_limit < LOC_STEP_LENGTH) {
                    set_time_limit(LOC_STEP_LENGTH + 5);
                }
                $start_time = time();
                $finish_time = $start_time + LOC_STEP_LENGTH;
                $file_url = $sTmpFilePath . $CSVFILE;
                if (!file_exists($file_url)) {
                    $arReturn['ERROR'] = GetMessage('SL_IMPORT_ERROR_NO_LOC_FILE');
                    break;
                }
                $bFinish = true;
                $arSysLangs = array();
                $db_lang = CLangAdmin::GetList($b = "sort", $o = "asc", array("ACTIVE" => "Y"));
                while ($arLang = $db_lang->Fetch()) {
                    $arSysLangs[$arLang["LID"]] = $arLang["LID"];
                }
                $arLocations = array();
                if (!$bSync) {
                    if (!is_set($_SESSION["LOC_POS"])) {
                        CSaleLocation::DeleteAll();
                    }
                } else {
                    $dbLocations = CSaleLocation::GetList(array(), array(), false, false, array("ID", "COUNTRY_ID", "REGION_ID", "CITY_ID"));
                    while ($arLoc = $dbLocations->Fetch()) {
                        $arLocations[$arLoc["ID"]] = $arLoc;
                    }
                }
                if (count($arLocations) <= 0) {
                    $bSync = false;
                }
                include_once $_SERVER["DOCUMENT_ROOT"] . "/bitrix/modules/main/classes/general/csv_data.php";
                $csvFile = new CCSVData();
                $csvFile->LoadFile($file_url);
                $csvFile->SetFieldsType("R");
                $csvFile->SetFirstHeader(false);
                $csvFile->SetDelimiter(",");
                $arRes = $csvFile->Fetch();
                if (!is_array($arRes) || count($arRes) <= 0 || strlen($arRes[0]) != 2) {
                    $strWarning .= GetMessage('SL_IMPORT_ERROR_WRONG_LOC_FILE') . "<br />";
                }
                if (strlen($strWarning) <= 0) {
                    $DefLang = $arRes[0];
                    if (!in_array($DefLang, $arSysLangs)) {
                        $strWarning .= GetMessage('SL_IMPORT_ERROR_NO_LANG') . "<br />";
                    }
                }
                if (strlen($strWarning) > 0) {
                    $arReturn['ERROR'] = $strWarning . "<br />";
                    break;
                }
                if (is_set($_SESSION["LOC_POS"])) {
                    $csvFile->SetPos($_SESSION["LOC_POS"]);
                    $CurCountryID = $_SESSION["CUR_COUNTRY_ID"];
                    $CurRegionID = $_SESSION["CUR_REGION_ID"];
                    $numCountries = $_SESSION["NUM_COUNTRIES"];
                    $numRegiones = $_SESSION["NUM_REGIONES"];
                    $numCities = $_SESSION["NUM_CITIES"];
                    $numLocations = $_SESSION["NUM_LOCATIONS"];
                } else {
                    $CurCountryID = 0;
                    $CurRegionID = 0;
                    $numCountries = 0;
                    $numRegiones = 0;
                    $numCities = 0;
                    $numLocations = 0;
                }
                $tt = 0;
                while ($arRes = $csvFile->Fetch()) {
                    $type = ToUpper($arRes[0]);
                    $tt++;
                    $arArrayTmp = array();
                    foreach ($arRes as $ind => $value) {
                        if ($ind % 2 && isset($arSysLangs[$value])) {
                            $arArrayTmp[$value] = array("LID" => $value, "NAME" => $arRes[$ind + 1]);
                            if ($value == $DefLang) {
                                $arArrayTmp["NAME"] = $arRes[$ind + 1];
                            }
                        }
                    }
                    //country
                    if (is_array($arArrayTmp) && strlen($arArrayTmp["NAME"]) > 0) {
                        if ($type == "S") {
                            $CurRegionID = null;
                            $arRegionList = array();
                            $CurCountryID = null;
                            $arContList = array();
                            $LLL = 0;
                            if ($bSync) {
                                $db_contList = CSaleLocation::GetList(array(), array("COUNTRY_NAME" => $arArrayTmp["NAME"], "LID" => $DefLang));
                                if ($arContList = $db_contList->Fetch()) {
                                    $LLL = IntVal($arContList["ID"]);
                                    $CurCountryID = IntVal($arContList["COUNTRY_ID"]);
                                }
                            }
                            if (IntVal($CurCountryID) <= 0) {
                                $CurCountryID = CSaleLocation::AddCountry($arArrayTmp);
                                $CurCountryID = IntVal($CurCountryID);
                                if ($CurCountryID > 0) {
                                    $numCountries++;
                                    if (IntVal($LLL) <= 0) {
                                        $LLL = CSaleLocation::AddLocation(array("COUNTRY_ID" => $CurCountryID));
                                        if (IntVal($LLL) > 0) {
                                            $numLocations++;
                                        }
                                    }
                                }
                            }
                        } elseif ($type == "R") {
                            $CurRegionID = null;
                            $arRegionList = array();
                            $LLL = 0;
                            if ($bSync) {
                                $db_rengList = CSaleLocation::GetList(array(), array("COUNTRY_ID" => $CurCountryID, "REGION_NAME" => $arArrayTmp["NAME"], "LID" => $DefLang));
                                if ($arRegionList = $db_rengList->Fetch()) {
                                    $LLL = $arRegionList["ID"];
                                    $CurRegionID = IntVal($arRegionList["REGION_ID"]);
                                }
                            }
                            if (IntVal($CurRegionID) <= 0) {
                                $CurRegionID = CSaleLocation::AddRegion($arArrayTmp);
                                $CurRegionID = IntVal($CurRegionID);
                                if ($CurRegionID > 0) {
                                    $numRegiones++;
                                    if (IntVal($LLL) <= 0) {
                                        $LLL = CSaleLocation::AddLocation(array("COUNTRY_ID" => $CurCountryID, "REGION_ID" => $CurRegionID));
                                        if (IntVal($LLL) > 0) {
                                            $numLocations++;
                                        }
                                    }
                                }
                            }
                        } elseif ($type == "T" && IntVal($CurCountryID) > 0) {
                            $city_id = 0;
                            $LLL = 0;
                            $arCityList = array();
                            if ($bSync) {
                                $arFilter = array("COUNTRY_ID" => $CurCountryID, "CITY_NAME" => $arArrayTmp["NAME"], "LID" => $DefLang);
                                if (IntVal($CurRegionID) > 0) {
                                    $arFilter["REGION_ID"] = $CurRegionID;
                                }
                                $db_cityList = CSaleLocation::GetList(array(), $arFilter);
                                if ($arCityList = $db_cityList->Fetch()) {
                                    $LLL = $arCityList["ID"];
                                    $city_id = IntVal($arCityList["CITY_ID"]);
                                }
                            }
                            if ($city_id <= 0) {
                                $city_id = CSaleLocation::AddCity($arArrayTmp);
                                $city_id = IntVal($city_id);
                                if ($city_id > 0) {
                                    $numCities++;
                                }
                            }
                            if ($city_id > 0) {
                                if (IntVal($LLL) <= 0) {
                                    $LLL = CSaleLocation::AddLocation(array("COUNTRY_ID" => $CurCountryID, "REGION_ID" => $CurRegionID, "CITY_ID" => $city_id));
                                    if (intval($LLL) > 0) {
                                        $numLocations++;
                                    }
                                }
                            }
                        }
                    }
                    if ($tt == 10) {
                        $tt = 0;
                        $cur_time = time();
                        if ($cur_time >= $finish_time) {
                            $cur_step = $csvFile->GetPos();
                            $amount = $csvFile->iFileLength;
                            $_SESSION["LOC_POS"] = $cur_step;
                            $_SESSION["CUR_COUNTRY_ID"] = $CurCountryID;
                            $_SESSION["CUR_REGION_ID"] = $CurRegionID;
                            $_SESSION["NUM_COUNTRIES"] = $numCountries;
                            $_SESSION["NUM_REGIONES"] = $numRegiones;
                            $_SESSION["NUM_CITIES"] = $numCities;
                            $_SESSION["NUM_LOCATIONS"] = $numLocations;
                            $bFinish = false;
                            //echo "<script>Import(1, {AMOUNT:".CUtil::JSEscape($amount).",POS:".CUtil::JSEscape($cur_step)."})</script>";
                            $arReturn['STEP'] = 1;
                            $arReturn['AMOUNT'] = $amount;
                            $arReturn['POS'] = $cur_step;
                            break;
                        }
                    }
                }
                if ($bFinish) {
                    unset($_SESSION["LOC_POS"]);
                    $strOK = GetMessage('SL_IMPORT_LOC_STATS') . '<br />';
                    $strOK = str_replace('#NUMCOUNTRIES#', intval($numCountries), $strOK);
                    $strOK = str_replace('#NUMREGIONES#', intval($numRegiones), $strOK);
                    $strOK = str_replace('#NUMCITIES#', intval($numCities), $strOK);
                    $strOK = str_replace('#NUMLOCATIONS#', intval($numLocations), $strOK);
                    $arReturn['MESSAGE'] = $strOK;
                    $arReturn['STEP'] = $LOADZIP == "Y" ? 2 : 3;
                    //echo '<script>Import('.($LOADZIP == "Y" ? 2 : 3).')</script>';
                }
                break;
            case 2:
                $time_limit = ini_get('max_execution_time');
                if ($time_limit < ZIP_STEP_LENGTH) {
                    set_time_limit(ZIP_STEP_LENGTH + 5);
                }
                $start_time = time();
                $finish_time = $start_time + ZIP_STEP_LENGTH;
                if ($LOADZIP == "Y" && file_exists($sTmpFilePath . DLZIPFILE)) {
                    $rsLocations = CSaleLocation::GetList(array(), array("LID" => 'ru'), false, false, array("ID", "CITY_NAME_LANG", "REGION_NAME_LANG"));
                    $arLocationMap = array();
                    while ($arLocation = $rsLocations->Fetch()) {
                        if (strlen($arLocation["REGION_NAME_LANG"]) > 0) {
                            if (strlen($arLocation["CITY_NAME_LANG"]) > 0) {
                                $arLocationMap[$arLocation["CITY_NAME_LANG"]][$arLocation["REGION_NAME_LANG"]] = $arLocation["ID"];
                            }
                        } else {
                            $arLocationMap[$arLocation["CITY_NAME_LANG"]] = $arLocation["ID"];
                        }
                    }
                    $DB->StartTransaction();
                    include_once $_SERVER["DOCUMENT_ROOT"] . "/bitrix/modules/main/classes/general/csv_data.php";
                    $csvFile = new CCSVData();
                    $csvFile->LoadFile($sTmpFilePath . DLZIPFILE);
                    $csvFile->SetFieldsType("R");
                    $csvFile->SetFirstHeader(false);
                    $csvFile->SetDelimiter(";");
                    if (is_set($_SESSION, 'ZIP_POS')) {
                        $numZIP = $_SESSION["NUM_ZIP"];
                        $csvFile->SetPos($_SESSION["ZIP_POS"]);
                    } else {
                        CSaleLocation::ClearAllLocationZIP();
                        unset($_SESSION["NUM_ZIP"]);
                        $numZIP = 0;
                    }
                    $bFinish = true;
                    $tt = 0;
                    $REGION = "";
                    while ($arRes = $csvFile->Fetch()) {
                        $tt++;
                        $CITY = $arRes[1];
                        if (strlen($arRes[3]) > 0) {
                            $REGION = $arRes[3];
                        }
                        if (array_key_exists($CITY, $arLocationMap)) {
                            if (strlen($REGION) > 0) {
                                $ID = $arLocationMap[$CITY][$REGION];
                            } else {
                                $ID = $arLocationMap[$CITY];
                            }
                        } else {
                            $ID = 0;
                        }
                        if ($ID) {
                            CSaleLocation::AddLocationZIP($ID, $arRes[2]);
                            $numZIP++;
                        }
                        if ($tt == 10) {
                            $tt = 0;
                            $cur_time = time();
                            if ($cur_time >= $finish_time) {
                                $cur_step = $csvFile->GetPos();
                                $amount = $csvFile->iFileLength;
                                $_SESSION["ZIP_POS"] = $cur_step;
                                $_SESSION["NUM_ZIP"] = $numZIP;
                                $bFinish = false;
                                $arReturn['STEP'] = 2;
                                $arReturn['AMOUNT'] = $amount;
                                $arReturn['POS'] = $cur_step;
                                break;
                            }
                        }
                    }
                    $DB->Commit();
                    if ($bFinish) {
                        unset($_SESSION["ZIP_POS"]);
                        $numCity = CSaleLocation::_GetZIPImportStats();
                        $strOK = GetMessage('SL_IMPORT_ZIP_STATS');
                        $strOK = str_replace('#NUMZIP#', intval($numZIP), $strOK);
                        $strOK = str_replace('#NUMCITIES#', intval($numCity["CITY_CNT"]), $strOK);
                        $arReturn['MESSAGE'] = $strOK;
                        $arReturn['STEP'] = 3;
                        $arReturn['PB_REMOVE'] = true;
                        break;
                    }
                } else {
                    $arReturn['ERROR'] = GetMessage('SL_IMPORT_ERROR_NO_ZIP_FILE') . '<br>';
                    $arReturn['STEP'] = 3;
                    break;
                }
                break;
            case 3:
                $arReturn['COMPLETE'] = true;
                break;
        }
    }
    return $arReturn;
}
Exemplo n.º 25
0
    function NewMediaObject($params)
    {
        global $USER, $DB;
        $blogId = IntVal(CBlogMetaWeblog::DecodeParams($params[0]["#"]["value"][0]["#"]));
        $user = CBlogMetaWeblog::DecodeParams($params[1]["#"]["value"][0]["#"]);
        $password = CBlogMetaWeblog::DecodeParams($params[2]["#"]["value"][0]["#"]);
        $arImage = $params[3]["#"]["value"][0]["#"]["struct"][0]["#"]["member"];
        foreach ($arImage as $val) {
            $arImageInfo[$val["#"]["name"][0]["#"]] = CBlogMetaWeblog::DecodeParams($val["#"]["value"][0]["#"]);
        }
        if (CBlogMetaWeblog::Authorize($user, $password)) {
            $result = '';
            $userId = $USER->GetID();
            if (IntVal($blogId) > 0) {
                $dbBlog = CBlog::GetList(array(), array("GROUP_SITE_ID" => SITE_ID, "ACTIVE" => "Y", "ID" => $blogId), false, false, array("ID", "URL", "NAME"));
                if ($arBlog = $dbBlog->GetNext()) {
                    $filename = trim(str_replace("\\", "/", trim($arImageInfo["name"])), "/");
                    $DIR_NAME = CTempFile::GetDirectoryName(12);
                    $FILE_NAME = rel2abs($DIR_NAME, "/" . $filename);
                    if (strlen($FILE_NAME) > 1 && $FILE_NAME === "/" . $filename) {
                        $ABS_FILE_NAME = $DIR_NAME . $FILE_NAME;
                    } else {
                        $ABS_FILE_NAME = "";
                    }
                    CheckDirPath($DIR_NAME);
                    if (strlen($ABS_FILE_NAME) > 0 && ($fp = fopen($ABS_FILE_NAME, "ab"))) {
                        $result = fwrite($fp, $arImageInfo["bits"]);
                        if ($result !== (function_exists("mb_strlen") ? mb_strlen($arImageInfo["bits"], 'latin1') : strlen($arImageInfo["bits"]))) {
                            return '<fault>
									<value>
										<struct>
											<member>
												<name>faultCode</name>
												<value><int>3</int></value>
												</member>
											<member>
												<name>faultString</name>
												<value><string>Error on saving media object</string></value>
												</member>
											</struct>
										</value>
									</fault>';
                        }
                        fclose($fp);
                    } else {
                        return '<fault>
								<value>
									<struct>
										<member>
											<name>faultCode</name>
											<value><int>3</int></value>
											</member>
										<member>
											<name>faultString</name>
											<value><string>Error on saving media object</string></value>
											</member>
										</struct>
									</value>
								</fault>';
                    }
                    $arFields = array("BLOG_ID" => $arBlog["ID"], "USER_ID" => $userId, "=TIMESTAMP_X" => $DB->GetNowFunction(), "FILE_ID" => array("name" => $arImageInfo["name"], "tmp_name" => $ABS_FILE_NAME, "MODULE_ID" => "blog", "type" => $arImageInfo["type"]));
                    $imageId = CBlogImage::Add($arFields);
                    $arImg = CBlogImage::GetByID($imageId);
                    $arFile = CFile::GetFileArray($arImg["FILE_ID"]);
                    $path = $arFile["SRC"];
                    $dbSite = CSite::GetByID(SITE_ID);
                    $arSite = $dbSite->Fetch();
                    $serverName = htmlspecialcharsEx($arSite["SERVER_NAME"]);
                    if (strlen($serverName) <= 0) {
                        if (defined("SITE_SERVER_NAME") && strlen(SITE_SERVER_NAME) > 0) {
                            $serverName = SITE_SERVER_NAME;
                        } else {
                            $serverName = COption::GetOptionString("main", "server_name", "www.bitrixsoft.com");
                        }
                    }
                    if (strlen($path) > 0) {
                        return '<params>
							<param>
								<value>
									<struct>
									<member>
									<name>url</name>
									<value>
									<string>' . CHTTP::URN2URI($path, $serverName) . '</string>
									</value>
									</member>
									</struct>
								</value>
							</param>
						</params>';
                    }
                }
            }
            return '<fault>
				<value>
					<struct>
						<member>
							<name>faultCode</name>
							<value><int>3</int></value>
							</member>
						<member>
							<name>faultString</name>
							<value><string>Error on saving media object</string></value>
							</member>
						</struct>
					</value>
				</fault>';
        } else {
            return '<fault>
				<value>
					<struct>
						<member>
							<name>faultCode</name>
							<value><int>3</int></value>
							</member>
						<member>
							<name>faultString</name>
							<value><string>' . $arAuthResult["MESSAGE"] . '</string></value>
							</member>
						</struct>
					</value>
				</fault>';
        }
    }
Exemplo n.º 26
0
 protected static function generatePath()
 {
     $tmpName = md5(mt_rand() . mt_rand());
     $dir = rtrim(CTempFile::GetDirectoryName(2, 'webdav'), '/') . '/';
     CheckDirPath($dir);
     //make folder recursive
     $pathItems = explode(CTempFile::GetAbsoluteRoot(), $dir . $tmpName);
     return array(array_pop($pathItems), $tmpName);
 }