function CheckRights($method, $strong, &$path) { $result = true; if (!parent::CheckRights($method)) { $result = false; $GLOBALS["APPLICATION"]->ThrowException(GetMessage('WD_ACCESS_DENIED'), 'ACCESS_DENIED'); } elseif ($path != '') { $io = CBXVirtualIo::GetInstance(); $path = $io->CombinePath($this->_udecode($path)); $strFileName = GetFileName($path); $extention = "." . strtolower(GetFileExtension($strFileName)); if (in_array($method, array("COPY", "MOVE", "PUT"))) { if (!$GLOBALS["USER"]->IsAdmin() && HasScriptExtension($strFileName)) { $result = false; $GLOBALS['APPLICATION']->ThrowException(GetMessage("WD_FILE_ERROR13"), "FORBIDDEN_EXTENTION"); } elseif (IsFileUnsafe($strFileName) || $strFileName == "index.php") { $result = false; $GLOBALS['APPLICATION']->ThrowException(GetMessage("WD_FILE_ERROR14"), "FORBIDDEN_NAME"); } elseif (!$io->ValidatePathString($io->CombinePath("/", $path)) || !$io->ValidateFilenameString($strFileName)) { $result = false; $GLOBALS['APPLICATION']->ThrowException(GetMessage("WD_FILE_ERROR14"), "FORBIDDEN_NAME"); } elseif (in_array($extention, $this->arFileForbiddenExtentions["WRITE"])) { $result = false; $GLOBALS['APPLICATION']->ThrowException(GetMessage("WD_FILE_ERROR13"), "FORBIDDEN_EXTENTION"); } } elseif (in_array($extention, $this->arFileForbiddenExtentions["READ"])) { $result = false; $GLOBALS["APPLICATION"]->ThrowException(GetMessage('WD_ACCESS_DENIED'), 'ACCESS_DENIED'); } } return $result; }
protected function validateFile($strFileName, $arFile) { if ($strFileName == '') { return GetMessage("FILE_BAD_FILENAME"); } $io = CBXVirtualIo::GetInstance(); if (!$io->ValidateFilenameString($strFileName)) { return GetMessage("MAIN_BAD_FILENAME1"); } if (strlen($strFileName) > 255) { return GetMessage("MAIN_BAD_FILENAME_LEN"); } //check .htaccess etc. if (IsFileUnsafe($strFileName)) { return GetMessage("FILE_BAD_TYPE"); } //nginx returns octet-stream for .jpg if (GetFileNameWithoutExtension($strFileName) == '') { return GetMessage("FILE_BAD_FILENAME"); } if (COption::GetOptionInt("main", "disk_space") > 0) { $quota = new CDiskQuota(); if (!$quota->checkDiskQuota($arFile)) { return GetMessage("FILE_BAD_QUOTA"); } } return ""; }
protected function validateFile(&$strFileName, $arFile, $bForceMD5 = false) { $strFileName = GetFileName($arFile["name"]); //File is going to be deleted if (isset($arFile["del"]) && $arFile["del"] != "") { //There is no new file as replacement if ($strFileName == "") { return ""; } } if ($arFile["name"] == "") { return ""; } if (COption::GetOptionInt("main", "disk_space") > 0) { $quota = new CDiskQuota(); if (!$quota->checkDiskQuota($arFile)) { return GetMessage("FILE_BAD_QUOTA"); } } $io = CBXVirtualIo::GetInstance(); if ($bForceMD5 != true && COption::GetOptionString("main", "save_original_file_name", "N") == "Y") { if (COption::GetOptionString("main", "translit_original_file_name", "N") == "Y") { $strFileName = CUtil::translit($strFileName, LANGUAGE_ID, array("max_len" => 1024, "safe_chars" => ".", "replace_space" => '-')); } if (COption::GetOptionString("main", "convert_original_file_name", "Y") == "Y") { $strFileName = $io->RandomizeInvalidFilename($strFileName); } } if (!$io->ValidateFilenameString($strFileName)) { return GetMessage("MAIN_BAD_FILENAME1"); } //check for double extension vulnerability $strFileName = RemoveScriptExtension($strFileName); if ($strFileName == '') { return GetMessage("FILE_BAD_FILENAME"); } if (strlen($strFileName) > 255) { return GetMessage("MAIN_BAD_FILENAME_LEN"); } //check .htaccess etc. if (IsFileUnsafe($strFileName)) { return GetMessage("FILE_BAD_TYPE"); } //nginx returns octet-stream for .jpg if (GetFileNameWithoutExtension($strFileName) == '') { return GetMessage("FILE_BAD_FILENAME"); } return ""; }
private function _extractFile(&$arEntry, $path, $removePath, $removeAllPath, &$arParams) { if (($res = $this->_readFileHeader($header)) != 1) { return $res; } //to be checked: file header should be coherent with $arEntry info $arEntry["filename"] = CharsetConverter::ConvertCharset($arEntry["filename"], "cp866", $this->fileSystemEncoding); $arEntry["stored_filename"] = CharsetConverter::ConvertCharset($arEntry["stored_filename"], "cp866", $this->fileSystemEncoding); //protecting against ../ etc in file path //only absolute path should be in the $arEntry $arEntry['filename'] = _normalizePath($arEntry['filename']); $arEntry['stored_filename'] = _normalizePath($arEntry['stored_filename']); if ($removeAllPath == true) { $arEntry['filename'] = basename($arEntry['filename']); } else { if ($removePath != "") { if ($this->_containsPath($removePath, $arEntry['filename']) == 2) { //change file status $arEntry['status'] = "filtered"; return $res; } $removePath_size = strlen($removePath); if (substr($arEntry['filename'], 0, $removePath_size) == $removePath) { //remove path $arEntry['filename'] = substr($arEntry['filename'], $removePath_size); } } } //making absolute path to the extracted file out of filename stored in the zip header and passed extracting path if ($path != '') { $arEntry['filename'] = $path . "/" . $arEntry['filename']; } //pre-extract callback if (isset($arParams['callback_pre_extract']) && $arParams['callback_pre_extract'] != '') { //generate local info $arLocalHeader = array(); $this->_convertHeader2FileInfo($arEntry, $arLocalHeader); //callback call eval('$res = ' . $arParams['callback_pre_extract'] . '(\'callback_pre_extract\', $arLocalHeader);'); //change file status if ($res == 0) { $arEntry['status'] = "skipped"; $res = 1; } //update the info, only some fields can be modified $arEntry['filename'] = $arLocalHeader['filename']; } //check if extraction should be done if ($arEntry['status'] == 'ok') { $logicalFilename = $this->io->GetLogicalName($arEntry['filename']); if ((HasScriptExtension($arEntry['filename']) || IsFileUnsafe($arEntry['filename']) || !$this->io->ValidatePathString($logicalFilename) || !$this->io->ValidateFilenameString(GetFileName($logicalFilename))) && $this->checkBXPermissions == true) { $arEntry['status'] = "no_permissions"; } else { //if the file exists, change status if (file_exists($arEntry['filename'])) { if (is_dir($arEntry['filename'])) { $arEntry['status'] = "already_a_directory"; } else { if (!is_writeable($arEntry['filename'])) { $arEntry['status'] = "write_protected"; } else { if (filemtime($arEntry['filename']) > $arEntry['mtime'] && !$this->replaceExistentFiles) { $arEntry['status'] = "newer_exist"; } } } } else { //check the directory availability and create it if necessary if (($arEntry['external'] & 0x10) == 0x10 || substr($arEntry['filename'], -1) == '/') { $checkDir = $arEntry['filename']; } else { if (!strstr($arEntry['filename'], "/")) { $checkDir = ""; } else { $checkDir = dirname($arEntry['filename']); } } if (($res = $this->_checkDir($checkDir, ($arEntry['external'] & 0x10) == 0x10)) != 1) { //change file status $arEntry['status'] = "path_creation_fail"; //return $res; $res = 1; } } } } //check if extraction should be done if ($arEntry['status'] == 'ok') { //if not a folder - extract if (!(($arEntry['external'] & 0x10) == 0x10)) { //if zip file with 0 compression if ($arEntry['compression'] == 0 && $arEntry['compressed_size'] == $arEntry['size']) { if (($destFile = @fopen($arEntry['filename'], 'wb')) == 0) { $arEntry['status'] = "write_error"; return $res; } //reading the fileby by self::ReadBlockSize octets blocks $size = $arEntry['compressed_size']; while ($size != 0) { $length = $size < self::ReadBlockSize ? $size : self::ReadBlockSize; $buffer = fread($this->zipfile, $length); $binary_data = pack('a' . $length, $buffer); @fwrite($destFile, $binary_data, $length); $size -= $length; } //close the destination file fclose($destFile); //changing file modification time touch($arEntry['filename'], $arEntry['mtime']); } else { if (($destFile = @fopen($arEntry['filename'], 'wb')) == 0) { //change file status $arEntry['status'] = "write_error"; return $res; } //read the compressed file in a buffer (one shot) $buffer = @fread($this->zipfile, $arEntry['compressed_size']); //decompress the file $fileContent = gzinflate($buffer); unset($buffer); //write uncompressed data @fwrite($destFile, $fileContent, $arEntry['size']); unset($fileContent); @fclose($destFile); touch($arEntry['filename'], $arEntry['mtime']); } if (isset($arParams['set_chmod']) && $arParams['set_chmod'] != 0) { chmod($arEntry['filename'], $arParams['set_chmod']); } } } //post-extract callback if (isset($arParams['callback_post_extract']) && $arParams['callback_post_extract'] != '') { //make local info $arLocalHeader = array(); $this->_convertHeader2FileInfo($arEntry, $arLocalHeader); //callback call eval('$res = ' . $arParams['callback_post_extract'] . '(\'callback_post_extract\', $arLocalHeader);'); } return $res; }
} $_SESSION["BX_CML2_EXPORT"]["zip"] = $arParams["USE_ZIP"] && function_exists("zip_open"); echo "zip=" . ($_SESSION["BX_CML2_EXPORT"]["zip"] ? "yes" : "no") . "\n"; echo "file_limit=0\n"; } } elseif ($_GET["mode"] == "file") { $DIR_NAME = "/" . COption::GetOptionString("main", "upload_dir", "upload") . "/1c_exchange/"; $ABS_FILE_NAME = false; $WORK_DIR_NAME = false; if (isset($_GET["filename"]) && strlen($_GET["filename"]) > 0) { //This check for 1c server on linux $filename = preg_replace("#^(/tmp/|upload/1c/webdata)#", "", $_GET["filename"]); //Filter file name crap all alone $filename = preg_replace("/[^a-zA-Z0-9_.\\/\\\\]/", "", $filename); $io = CBXVirtualIo::GetInstance(); $bBadFile = HasScriptExtension($filename) || IsFileUnsafe($filename) || !$io->ValidatePathString("/" . $filename); if (!$bBadFile) { $filename = trim(str_replace("\\", "/", trim($filename)), "/"); $FILE_NAME = rel2abs($_SERVER["DOCUMENT_ROOT"] . $DIR_NAME, "/" . $filename); if (strlen($FILE_NAME) > 1 && $FILE_NAME === "/" . $filename) { $ABS_FILE_NAME = $_SERVER["DOCUMENT_ROOT"] . $DIR_NAME . $FILE_NAME; $WORK_DIR_NAME = substr($ABS_FILE_NAME, 0, strrpos($ABS_FILE_NAME, "/") + 1); } } } if ($ABS_FILE_NAME) { if (function_exists("file_get_contents")) { $DATA = file_get_contents("php://input"); } elseif (isset($GLOBALS["HTTP_RAW_POST_DATA"])) { $DATA =& $GLOBALS["HTTP_RAW_POST_DATA"]; } else {
public static function UnZip($file_name, $last_zip_entry = "", $start_time = 0, $interval = 0) { global $APPLICATION; $io = CBXVirtualIo::GetInstance(); //Function and securioty checks if (!function_exists("zip_open")) { return false; } $dir_name = substr($file_name, 0, strrpos($file_name, "/") + 1); if (strlen($dir_name) <= strlen($_SERVER["DOCUMENT_ROOT"])) { return false; } $hZip = zip_open($file_name); if (!$hZip) { return false; } //Skip from last step if ($last_zip_entry) { while ($entry = zip_read($hZip)) { if (zip_entry_name($entry) == $last_zip_entry) { break; } } } $io = CBXVirtualIo::GetInstance(); //Continue unzip while ($entry = zip_read($hZip)) { $entry_name = zip_entry_name($entry); //Check for directory zip_entry_open($hZip, $entry); if (zip_entry_filesize($entry)) { $file_name = trim(str_replace("\\", "/", trim($entry_name)), "/"); $file_name = $APPLICATION->ConvertCharset($file_name, "cp866", LANG_CHARSET); $file_name = preg_replace("#^import_files/tmp/webdata/\\d+/\\d+/import_files/#", "import_files/", $file_name); $bBadFile = HasScriptExtension($file_name) || IsFileUnsafe($file_name) || !$io->ValidatePathString("/" . $file_name); if (!$bBadFile) { $file_name = $io->GetPhysicalName($dir_name . rel2abs("/", $file_name)); CheckDirPath($file_name); $fout = fopen($file_name, "wb"); if (!$fout) { return false; } while ($data = zip_entry_read($entry, 102400)) { $data_len = function_exists('mb_strlen') ? mb_strlen($data, 'latin1') : strlen($data); $result = fwrite($fout, $data); if ($result !== $data_len) { return false; } } } } zip_entry_close($entry); //Jump to next step if ($interval > 0 && time() - $start_time > $interval) { zip_close($hZip); return $entry_name; } } zip_close($hZip); return true; }
public static function Request($action, $site) { global $USER; if (!$USER->CanDoOperation('fileman_view_file_structure')) { return; } $io = CBXVirtualIo::GetInstance(); CUtil::JSPostUnescape(); switch ($action) { case "count": case "search": case "replace": $oSearch = new CFilemanSearch(); $oSearch->Init(array('lastPath' => isset($_POST['last_path']) ? $_POST['last_path'] : false, 'bCount' => $action == "count", 'bReplace' => $action == "replace", "fileName" => trim($_POST['file']), "phrase" => trim($_POST['phrase']), "replacePhrase" => trim($_POST['replace_phrase']), "dir" => CFilemanUtils::NormalizePath($_POST['dir']), "bSubdir" => $_POST['subdir'], "dateFrom" => $_POST['date_from'], "dateTo" => $_POST['date_to'], "sizeFrom" => intVal($_POST['size_from']), "sizeTo" => intVal($_POST['size_to']), "entire" => $_POST['entire'], "bCaseSens" => $_POST['case_sens'], "bDirsToo" => $_POST['dirs_too'], "ssess" => $_POST['ssess'], "bInResult" => $_POST['in_result'], "site" => CFileMan::__CheckSite($_GET['fu_site']))); CFileMan::SaveLastPath(CFilemanUtils::NormalizePath($_POST['dir'])); break; case "clean_old": CFilemanSearch::CleanOldSearchResult(); break; case "search_save_config": CFilemanSearch::SaveConfig(array("advMode" => (bool) $_POST['adv_mode'], "bSubdir" => (bool) $_POST['subdir'], "entire" => (bool) $_POST['entire'], "bCaseSens" => (bool) $_POST['case_sens'], "bDirsToo" => (bool) $_POST['dirs_too'])); break; case "copy_save_config": CFilemanCopy::SaveConfig(array("advMode" => (bool) $_POST['adv_mode'], "caseOption" => $_POST['case_option'])); break; case "copy": case "move": $oCopy = new CFilemanCopy(); $oCopy->Init(array("bCopy" => $action == "copy", "caseOption" => $_POST['case_option'], "arFiles" => $_POST['files'], "copyTo" => $_POST['copy_to'], "createCopyTo" => $_POST['create_copy_to'] == "Y", "userCaseAnswer" => isset($_POST['uc_answer']) ? $_POST['uc_answer'] : false, "userCaseToAll" => isset($_POST['uc_to_all']) ? $_POST['uc_to_all'] : false, "userCaseLastPath" => isset($_POST['uc_last_path']) ? $_POST['uc_last_path'] : false, "bSearch" => $_POST['search'] == "Y", "ssess" => $_POST['ssess'], "siteTo" => CFileMan::__CheckSite($_GET['fu_site']))); CFileMan::SaveLastPath($_POST['copy_to']); break; case "get_last_pathes": ?> <script>window.bx_last_pathes = <?php echo CUtil::PhpToJSObject(CFilemanUtils::GetLastPathes()); ?> ;</script> <?php break; case "pack": if (isset($_POST["startFile"])) { $startFile = trim($_POST["startFile"]); } if (isset($_POST["quickPath"])) { $quickPath = trim($_POST["quickPath"]); } if (isset($_POST["packTo"])) { if (substr($_POST["packTo"], 0, 1) == "/") { $pack_to = $_POST["packTo"]; } else { $pack_to = "/" . $_POST["packTo"]; } } $siteTo = CFileMan::__CheckSite($_POST['siteTo']); $docRootTo = CSite::GetSiteDocRoot($siteTo) ? CSite::GetSiteDocRoot($siteTo) : ''; $siteFrom = CFileMan::__CheckSite($site); $docRootFrom = CSite::GetSiteDocRoot($siteFrom); if (!$USER->IsAdmin()) { $pack_to = RemoveScriptExtension($pack_to); } //check writing permissions if (!$USER->CanDoFileOperation('fm_create_new_file', array($siteTo, $pack_to))) { ?> <script> window.BXFM_archivePermsError = true; </script> <?php return; } if (IsFileUnsafe($docRootTo . $pack_to) || CFileMan::CheckFileName(GetFileName($pack_to)) !== true) { ?> <script> window.BXFM_archiveFNameError = true; </script> <?php return; } //ask if the file already exists if (file_exists($io->GetPhysicalName($docRootTo . $pack_to))) { if (empty($startFile)) { if ($_POST["bPackReplace"] != "replace") { ?> <script> window.BXFM_archiveExists = { fileOld: { name: "<?php echo CUtil::JSEscape(basename($pack_to)); ?> ", path: "<?php echo CUtil::JSEscape($pack_to); ?> ", site: "<?php echo CUtil::JSEscape($siteTo); ?> ", size: "<?php echo CFile::FormatSize(filesize($io->GetPhysicalName($docRootTo . $pack_to))); ?> ", date: "<?php echo date(CDatabase::DateFormatToPHP(CLang::GetDateFormat('FULL')), filemtime($io->GetPhysicalName($docRootTo . $pack_to)) + CTimeZone::GetOffset()); ?> " } }; </script> <?php return; } } } $packarc = CBXArchive::GetArchive($docRootTo . $pack_to, trim($_POST['arcType'])); if ($packarc instanceof IBXArchive) { //this set of options is common for every archive type $packarc->SetOptions(array("COMPRESS" => true, "STEP_TIME" => COption::GetOptionString("fileman", "archive_step_time", 30), "ADD_PATH" => false, "REMOVE_PATH" => $docRootFrom . $quickPath, "CHECK_PERMISSIONS" => $USER->IsAdmin() ? false : true)); $arPackFiles = array(); foreach ($_POST["files"] as $path2file) { $arPackFiles[] = $docRootFrom . $path2file['path']; } @set_time_limit(0); $pRes = $packarc->Pack($arPackFiles, $startFile); switch ($pRes) { case IBXArchive::StatusContinue: ?> <script> window.fmPackTimeout = true; window.fmPackLastFile = '<?php echo CUtil::JSEscape($packarc->GetStartFile()); ?> '; </script> <?php break; case IBXArchive::StatusSuccess: ?> <script> window.fmPackTimeout = false; window.fmPackLastFile = ''; window.fmPackSuccess = true; </script> <?php break; case IBXArchive::StatusError: $arErrors = $packarc->GetErrors(); ?> <script> window.fmPackTimeout = false; window.fmPackSuccess = false; window.fmPackErrors = <?php echo CUtil::PhpToJSObject($arErrors); ?> ; </script> <?php break; } } else { ?> <script> window.fmPackSuccess = false; window.fmPackErrors = <?php echo CUtil::PhpToJsObject(GetMessage("FM_UTIL_ARC_ERROR")); ?> ; </script> <?php } break; case "unpack": global $USER; if (isset($_POST["packTo"])) { if (substr($_POST["packTo"], 0, 1) == "/") { $pack_to = $_POST["packTo"]; } else { $pack_to = "/" . $_POST["packTo"]; } } $siteFrom = CFileMan::__CheckSite($_GET['site']); $siteTo = CFileMan::__CheckSite($_POST['siteTo']); $docRootFrom = CSite::GetSiteDocRoot($siteFrom); $docRootTo = CSite::GetSiteDocRoot($siteTo); if (!($USER->CanDoFileOperation('fm_create_new_file', array($siteTo, $_POST["packTo"])) || $USER->CanDoFileOperation('fm_create_new_folder', array($siteTo, $_POST["packTo"])))) { ?> <script> window.BXFM_archivePermsError = true; </script> <?php return; } $bReplaceFiles = $_POST["case_option"] == "replace" ? true : false; $arc = CBXArchive::GetArchive($docRootFrom . $_POST["files"][0]); if ($arc instanceof IBXArchive) { global $USER; $arc->SetOptions(array("REMOVE_PATH" => $docRootFrom, "UNPACK_REPLACE" => $bReplaceFiles, "CHECK_PERMISSIONS" => $USER->IsAdmin() ? false : true)); $uRes = $arc->Unpack($docRootTo . $pack_to); if (!$uRes) { $uErrors = $arc->GetErrors(); ?> <script> window.fmUnpackSuccess = false; window.fmUnpackErrors = <?php echo CUtil::PhpToJSObject($uErrors); ?> </script> <?php } else { ?> <script> window.fmUnpackSuccess = true; </script> <?php } } else { ?> <script> window.fmUnpackSuccess = false; window.fmUnpackErrors = <?php echo CUtil::PhpToJsObject(GetMessage("FM_UTIL_ARC_ERROR")); ?> ; </script> <?php } break; } }
public static function IsBaseFilenameSafe($filename) { $isUnSafe = IsFileUnsafe($filename) || HasScriptExtension($filename) || !(preg_match("#^[^\\\\/:*?\"\\'~%<>|]+\$#is", $filename) > 0); return !$isUnSafe; }
private function _extractList($p_path, &$p_list_detail, $p_mode, $p_file_list, $p_remove_path) { $v_result = true; $v_nb = 0; $v_extract_all = true; $v_listing = false; $p_path = str_replace("\\", "/", $p_path); $p_path = $this->io->GetPhysicalName($p_path); if ($p_path == '' || substr($p_path, 0, 1) != '/' && substr($p_path, 0, 3) != "../" && !strpos($p_path, ':')) { $p_path = "./" . $p_path; } $p_remove_path = str_replace("\\", "/", $p_remove_path); if ($p_remove_path != '' && substr($p_remove_path, -1) != '/') { $p_remove_path .= '/'; } $p_remove_path_size = strlen($p_remove_path); switch ($p_mode) { case "complete": $v_extract_all = TRUE; $v_listing = FALSE; break; case "partial": $v_extract_all = FALSE; $v_listing = FALSE; break; case "list": $v_extract_all = FALSE; $v_listing = TRUE; break; default: $this->_arErrors[] = array("ERR_PARAM", str_replace("#EXTRACT_MODE#", $p_mode, GetMessage("MAIN_ARCHIVE_ERR_PARAM"))); return false; } clearstatcache(); while (self::$bMbstring ? mb_strlen($v_binary_data = $this->_readBlock(), "latin1") : strlen($v_binary_data = $this->_readBlock()) != 0) { $v_extract_file = FALSE; $v_extraction_stopped = 0; if (!$this->_readHeader($v_binary_data, $v_header)) { return false; } if ($v_header['filename'] == '') { continue; } // ----- Look for long filename if ($v_header['typeflag'] == 'L') { if (!$this->_readLongHeader($v_header)) { return false; } } if (!$v_extract_all && is_array($p_file_list)) { // ----- By default no unzip if the file is not found $v_extract_file = false; $l = count($p_file_list); for ($i = 0; $i < $l; $i++) { // ----- Look if it is a directory if (substr($p_file_list[$i], -1) == '/') { // ----- Look if the directory is in the filename path if (strlen($v_header['filename']) > strlen($p_file_list[$i]) && substr($v_header['filename'], 0, strlen($p_file_list[$i])) == $p_file_list[$i]) { $v_extract_file = TRUE; break; } } elseif ($p_file_list[$i] == $v_header['filename']) { // ----- It is a file, so compare the file names $v_extract_file = TRUE; break; } } } else { $v_extract_file = TRUE; } // ----- Look if this file need to be extracted if ($v_extract_file && !$v_listing) { if ($p_remove_path != '' && substr($v_header['filename'], 0, $p_remove_path_size) == $p_remove_path) { $v_header['filename'] = substr($v_header['filename'], $p_remove_path_size); } if ($p_path != './' && $p_path != '/') { while (substr($p_path, -1) == '/') { $p_path = substr($p_path, 0, strlen($p_path) - 1); } if (substr($v_header['filename'], 0, 1) == '/') { $v_header['filename'] = $p_path . $v_header['filename']; } else { $v_header['filename'] = $p_path . '/' . $v_header['filename']; } } if (file_exists($v_header['filename'])) { if (@is_dir($v_header['filename']) && $v_header['typeflag'] == '') { $this->_arErrors[] = array("DIR_EXISTS", str_replace("#FILE_NAME#", removeDocRoot($this->io->GetLogicalName($v_header['filename'])), GetMessage("MAIN_ARCHIVE_DIR_EXISTS"))); return false; } if (is_file($v_header['filename']) && $v_header['typeflag'] == "5") { $this->_arErrors[] = array("FILE_EXISTS", str_replace("#FILE_NAME#", removeDocRoot($this->io->GetLogicalName($v_header['filename'])), GetMessage("MAIN_ARCHIVE_FILE_EXISTS"))); return false; } if (!is_writeable($v_header['filename'])) { $this->_arErrors[] = array("FILE_PERMS", str_replace("#FILE_NAME#", removeDocRoot($this->io->GetLogicalName($v_header['filename'])), GetMessage("MAIN_ARCHIVE_FILE_PERMS"))); return false; } } elseif (($v_result = $this->_dirCheck($v_header['typeflag'] == "5" ? $v_header['filename'] : dirname($v_header['filename']))) != 1) { $this->_arErrors[] = array("NO_DIR", str_replace("#FILE_NAME#", removeDocRoot($this->io->GetLogicalName($v_header['filename'])), GetMessage("MAIN_ARCHIVE_NO_DIR"))); return false; } if ($v_extract_file) { $logicalFilename = $this->io->GetLogicalName($v_header['filename']); if ((HasScriptExtension($v_header['filename']) || IsFileUnsafe($v_header['filename']) || !$this->io->ValidatePathString($logicalFilename) || !$this->io->ValidateFilenameString(GetFileName($logicalFilename))) && $this->CheckBXPermissions == true) { $this->_jumpBlock(ceil($v_header['size'] / 512)); } elseif (file_exists($v_header['filename']) && $this->ReplaceExistentFiles || !file_exists($v_header['filename'])) { if ($v_header['typeflag'] == "5") { if (!@file_exists($v_header['filename'])) { if (!@mkdir($v_header['filename'], FX_DIR_PERMISSIONS)) { $this->_arErrors[] = array("ERR_CREATE_DIR", str_replace("#DIR_NAME#", removeDocRoot($this->io->GetLogicalName($v_header['filename'])), GetMessage("MAIN_ARCHIVE_ERR_CREATE_DIR"))); return false; } } } else { if (($v_dest_file = @fopen($v_header['filename'], "wb")) == 0) { $this->_arErrors[] = array("ERR_CREATE_FILE", str_replace("#FILE_NAME#", removeDocRoot($this->io->GetLogicalName($v_header['filename'])), GetMessage("MAIN_ARCHIVE_ERR_CREATE_FILE"))); return false; } else { $n = floor($v_header['size'] / 512); for ($i = 0; $i < $n; $i++) { $v_content = $this->_readBlock(); fwrite($v_dest_file, $v_content, 512); } if ($v_header['size'] % 512 != 0) { $v_content = $this->_readBlock(); fwrite($v_dest_file, $v_content, $v_header['size'] % 512); } @fclose($v_dest_file); @chmod($v_header['filename'], FX_FILE_PERMISSIONS); @touch($v_header['filename'], $v_header['mtime']); } clearstatcache(); if (filesize($v_header['filename']) != $v_header['size']) { $this->_arErrors[] = array("ERR_SIZE_CHECK", str_replace(array("#FILE_NAME#", "#SIZE#", "#EXP_SIZE#"), array(removeDocRoot($v_header['size']), filesize($v_header['filename']), $v_header['size']), GetMessage("MAIN_ARCHIVE_ERR_SIZE_CHECK"))); return false; } } } else { $this->_jumpBlock(ceil($v_header['size'] / 512)); } } else { $this->_jumpBlock(ceil($v_header['size'] / 512)); } } else { $this->_jumpBlock(ceil($v_header['size'] / 512)); } if ($v_listing || $v_extract_file || $v_extraction_stopped) { if (($v_file_dir = dirname($v_header['filename'])) == $v_header['filename']) { $v_file_dir = ''; } if (substr($v_header['filename'], 0, 1) == '/' && $v_file_dir == '') { $v_file_dir = '/'; } $p_list_detail[$v_nb++] = $v_header; } } return true; }
function CheckRights($method = "", $strong = false, $path = "") { $result = true; if (!parent::CheckRights($method, $strong)) { $result = false; $GLOBALS["APPLICATION"]->ThrowException(GetMessage('WD_ACCESS_DENIED'), 'ACCESS_DENIED'); } elseif (!empty($path)) { $path = $this->_udecode($path); $strFileName = basename($path); $extention = strtolower(strrchr($strFileName, '.')); if (in_array($method, array("COPY", "MOVE", "PUT"))) { if (IsFileUnsafe($strFileName) || $strFileName == "index.php") { $result = false; $GLOBALS['APPLICATION']->ThrowException(GetMessage("WD_FILE_ERROR14"), "FORBIDDEN_NAME"); } } } return $result; }
function SaveFile($arFile, $strSavePath, $bForceMD5=false, $bSkipExt=false) { $strFileName = GetFileName($arFile["name"]); /* filename.gif */ if(isset($arFile["del"]) && $arFile["del"] <> '') { CFile::DoDelete($arFile["old_file"]); if($strFileName == '') return "NULL"; } if($arFile["name"] == '') { if(is_set($arFile, "description") && intval($arFile["old_file"])>0) CFile::UpdateDesc($arFile["old_file"], $arFile["description"]); return false; } if(is_set($arFile, "content") && !is_set($arFile, "size")) $arFile["size"] = CUtil::BinStrlen($arFile["content"]); else $arFile["size"] = filesize($arFile["tmp_name"]); /****************************** QUOTA ******************************/ if (COption::GetOptionInt("main", "disk_space") > 0) { $quota = new CDiskQuota(); if (!$quota->checkDiskQuota($arFile)) return false; } /****************************** QUOTA ******************************/ $arFile["ORIGINAL_NAME"] = $strFileName; $io = CBXVirtualIo::GetInstance(); if($bForceMD5 != true && COption::GetOptionString("main", "save_original_file_name", "N") == "Y") { if(COption::GetOptionString("main", "translit_original_file_name", "N") == "Y") $strFileName = CUtil::translit($strFileName, LANGUAGE_ID, array("max_len"=>1024, "safe_chars"=>".")); if(COption::GetOptionString("main", "convert_original_file_name", "Y") == "Y") $strFileName = $io->RandomizeInvalidFilename($strFileName); } if(!$io->ValidateFilenameString($strFileName)) return false; //check for double extension vulnerability $strFileName = RemoveScriptExtension($strFileName); if($strFileName == '') return false; if(strlen($strFileName) > 255) return false; //check .htaccess etc. if(IsFileUnsafe($strFileName)) return false; //nginx returns octet-stream for .jpg if(GetFileNameWithoutExtension($strFileName) == '') return false; $upload_dir = COption::GetOptionString("main", "upload_dir", "upload"); if($arFile["type"]=="image/pjpeg" || $arFile["type"]=="image/jpg") $arFile["type"]="image/jpeg"; //.jpe is not image type on many systems if(strtolower(GetFileExtension($strFileName)) == "jpe") $strFileName = substr($strFileName, 0, -4).".jpg"; $bExternalStorage = false; foreach(GetModuleEvents("main", "OnFileSave", true) as $arEvent) { if(ExecuteModuleEventEx($arEvent, array(&$arFile, $strFileName, $strSavePath, $bForceMD5, $bSkipExt))) { $bExternalStorage = true; break; } } if(!$bExternalStorage) { $newName = ''; if($bForceMD5 != true && COption::GetOptionString("main", "save_original_file_name", "N")=="Y") { $dir_add = ''; $i=0; while(true) { $dir_add = substr(md5(uniqid(mt_rand(), true)), 0, 3); if(!$io->FileExists($_SERVER["DOCUMENT_ROOT"]."/".$upload_dir."/".$strSavePath."/".$dir_add."/".$strFileName)) break; if($i>=25) { $j=0; while(true) { $dir_add = substr(md5(mt_rand()), 0, 3)."/".substr(md5(mt_rand()), 0, 3); if(!$io->FileExists($_SERVER["DOCUMENT_ROOT"]."/".$upload_dir."/".$strSavePath."/".$dir_add."/".$strFileName)) break; if($j>=25) { $dir_add = substr(md5(mt_rand()), 0, 3)."/".md5(mt_rand()); break; } $j++; } break; } $i++; } if(substr($strSavePath, -1, 1) <> "/") $strSavePath .= "/".$dir_add; else $strSavePath .= $dir_add."/"; $newName = $strFileName; } else { $strFileExt = ($bSkipExt == true? '' : strrchr($strFileName, ".")); while(true) { $newName = md5(uniqid(mt_rand(), true)).$strFileExt; if(substr($strSavePath, -1, 1) <> "/") $strSavePath .= "/".substr($newName, 0, 3); else $strSavePath .= substr($newName, 0, 3)."/"; if(!$io->FileExists($_SERVER["DOCUMENT_ROOT"]."/".$upload_dir."/".$strSavePath."/".$newName)) break; } } $arFile["SUBDIR"] = $strSavePath; $arFile["FILE_NAME"] = $newName; $strDirName = $_SERVER["DOCUMENT_ROOT"]."/".$upload_dir."/".$strSavePath."/"; $strDbFileNameX = $strDirName.$newName; $strPhysicalFileNameX = $io->GetPhysicalName($strDbFileNameX); CheckDirPath($strDirName); if(is_set($arFile, "content")) { $f = fopen($strPhysicalFileNameX, "ab"); if(!$f) return false; if(!fwrite($f, $arFile["content"])) return false; fclose($f); } elseif( !copy($arFile["tmp_name"], $strPhysicalFileNameX) && !move_uploaded_file($arFile["tmp_name"], $strPhysicalFileNameX) ) { CFile::DoDelete($arFile["old_file"]); return false; } if(isset($arFile["old_file"])) CFile::DoDelete($arFile["old_file"]); @chmod($strPhysicalFileNameX, BX_FILE_PERMISSIONS); $imgArray = CFile::GetImageSize($strDbFileNameX); if(is_array($imgArray)) { $arFile["WIDTH"] = $imgArray[0]; $arFile["HEIGHT"] = $imgArray[1]; } else { $arFile["WIDTH"] = 0; $arFile["HEIGHT"] = 0; } } //if(!$bExternalStorage) /****************************** QUOTA ******************************/ if (COption::GetOptionInt("main", "disk_space") > 0) { CDiskQuota::updateDiskQuota("file", $arFile["size"], "insert"); } /****************************** QUOTA ******************************/ $NEW_IMAGE_ID = CFile::DoInsert(array( "HEIGHT" => $arFile["HEIGHT"], "WIDTH" => $arFile["WIDTH"], "FILE_SIZE" => $arFile["size"], "CONTENT_TYPE" => $arFile["type"], "SUBDIR" => $arFile["SUBDIR"], "FILE_NAME" => $arFile["FILE_NAME"], "MODULE_ID" => $arFile["MODULE_ID"], "ORIGINAL_NAME" => $arFile["ORIGINAL_NAME"], "DESCRIPTION" => isset($arFile["description"])? $arFile["description"]: '', "HANDLER_ID" => isset($arFile["HANDLER_ID"])? $arFile["HANDLER_ID"]: '', )); CFile::CleanCache($NEW_IMAGE_ID); return $NEW_IMAGE_ID; }
else $DIR_NAME = $_SERVER["DOCUMENT_ROOT"]."/".COption::GetOptionString("main", "upload_dir", "upload")."/1c_catalog/"; if ( isset($_GET["filename"]) && (strlen($_GET["filename"]) > 0) && (strlen($DIR_NAME) > 0) ) { //This check for 1c server on linux $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) { $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); } } } ob_start();
/** * Removes snippet * * @param array - list of params (template, path) * @return bool - result */ public static function Remove($params = array()) { global $APPLICATION; $res = false; $template = CFileMan::SecurePathVar($params['template']); $path = CFileMan::SecurePathVar($params["path"]); $contPath = $_SERVER["DOCUMENT_ROOT"] . BX_PERSONAL_ROOT . "/templates/" . $template . "/snippets"; $snippetPath = $contPath . ($path == '' ? '' : '/' . $path); $io = CBXVirtualIo::GetInstance(); if (!$io->ValidatePathString($snippetPath) || IsFileUnsafe($snippetPath) || HasScriptExtension($snippetPath)) { return false; } //Delete snippet file if ($io->FileExists($snippetPath)) { $res = $io->Delete($snippetPath); } $SNIPPETS = array(); if ($io->FileExists($contPath . "/.content.php")) { @(include $contPath . "/.content.php"); } $contentSrc = '<?if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true)die();?>' . chr(10); $contentSrc .= '<?' . chr(10) . '$SNIPPETS = Array();' . chr(10); foreach ($SNIPPETS as $k => $snip) { if ($io->FileExists(CFileMan::SecurePathVar($contPath . '/' . $k))) { $contentSrc .= '$SNIPPETS[\'' . CUtil::addslashes($k) . '\'] = Array('; if (isset($snip['title']) && $snip['title'] !== '') { $contentSrc .= '\'title\' => \'' . Cutil::addslashes($snip['title']) . '\''; if (isset($snip['description']) && $snip['description'] !== '') { $contentSrc .= ', '; } } if (isset($snip['description']) && $snip['description'] !== '') { $contentSrc .= '\'description\' => \'' . Cutil::addslashes($snip['description']) . '\''; } $contentSrc .= ');' . chr(10); } } $contentSrc .= '?>'; $APPLICATION->SaveFileContent($contPath . "/.content.php", $contentSrc); CSnippets::ClearCache(); return $res; }