protected static function prepareDataToInsertFromFileArray(array $fileData, array $data, ErrorCollection $errorCollection) { list($relativePath, $absolutePath) = self::generatePath(); $file = new IO\File($fileData['tmp_name']); if (!$file->isExists()) { $errorCollection->addOne(new Error('Could not find file', self::ERROR_EXISTS_FILE)); return null; } if (!$file->rename($absolutePath)) { $errorCollection->addOne(new Error('Could not move file', self::ERROR_MOVE_FILE)); return null; } //now you can set CREATED_BY $data = array_intersect_key($data, array('CREATED_BY' => true)); return array_merge(array('TOKEN' => bx_basename($relativePath), 'FILENAME' => $fileData['name'], 'PATH' => $relativePath, 'BUCKET_ID' => '', 'SIZE' => '', 'IS_CLOUD' => '', 'WIDTH' => empty($fileData['width']) ? '' : $fileData['width'], 'HEIGHT' => empty($fileData['height']) ? '' : $fileData['height']), $data); }
/** * Set to $this->usedTraits included traits */ private function readUsedTraits() { if ($this->traitsAutoExecute) { $reflection = new \ReflectionClass(get_called_class()); $parentClass = $reflection; while (1) { foreach ($parentClass->getTraitNames() as $trait) { $this->usedTraits[$trait] = bx_basename($trait); } if ($parentClass->name === __CLASS__) { break; } $parentClass = $parentClass->getParentClass(); } } }
public static function OnFileSave(&$arFile, $strFileName, $strSavePath, $bForceMD5 = false, $bSkipExt = false) { if (!$arFile["tmp_name"] && !array_key_exists("content", $arFile)) { return false; } if (array_key_exists("bucket", $arFile)) { $bucket = $arFile["bucket"]; } else { $bucket = CCloudStorage::FindBucketForFile($arFile, $strFileName); } if (!is_object($bucket)) { return false; } if (!$bucket->Init()) { return false; } $copySize = false; $subDir = ""; $filePath = ""; if (array_key_exists("content", $arFile)) { $arFile["tmp_name"] = CTempFile::GetFileName($arFile["name"]); CheckDirPath($arFile["tmp_name"]); $fp = fopen($arFile["tmp_name"], "ab"); if ($fp) { fwrite($fp, $arFile["content"]); fclose($fp); } } if (array_key_exists("bucket", $arFile)) { $newName = bx_basename($arFile["tmp_name"]); $prefix = $bucket->GetFileSRC("/"); $subDir = substr($arFile["tmp_name"], strlen($prefix)); $subDir = substr($subDir, 0, -strlen($newName) - 1); } else { if ($bForceMD5 != true && COption::GetOptionString("main", "save_original_file_name", "N") == "Y") { if (COption::GetOptionString("main", "convert_original_file_name", "Y") == "Y") { $newName = CCloudStorage::translit($strFileName); } else { $newName = $strFileName; } } else { $strFileExt = $bSkipExt == true ? '' : strrchr($strFileName, "."); $newName = md5(uniqid(mt_rand(), true)) . $strFileExt; } //check for double extension vulnerability $newName = RemoveScriptExtension($newName); while (true) { $strRand = md5(mt_rand()); $strRand = substr($strRand, 0, 3) . "/" . $strRand; if (substr($strSavePath, -1) == "/") { $subDir = $strSavePath . $strRand; } else { $subDir = $strSavePath . "/" . $strRand; } $subDir = ltrim($subDir, "/"); $filePath = "/" . $subDir . "/" . $newName; if (!$bucket->FileExists($filePath)) { break; } } $targetPath = $bucket->GetFileSRC("/"); if (strpos($arFile["tmp_name"], $targetPath) === 0) { $arDbFile = array("SUBDIR" => "", "FILE_NAME" => substr($arFile["tmp_name"], strlen($targetPath)), "CONTENT_TYPE" => $arFile["type"]); $copyPath = $bucket->FileCopy($arDbFile, $filePath); if (!$copyPath) { return false; } $copySize = $bucket->GetFileSize("/" . urldecode(substr($copyPath, strlen($targetPath)))); } else { $imgArray = CFile::GetImageSize($arFile["tmp_name"], true, false); if (is_array($imgArray) && $imgArray[2] == IMAGETYPE_JPEG) { $exifData = CFile::ExtractImageExif($arFile["tmp_name"]); if ($exifData && isset($exifData['Orientation'])) { $properlyOriented = CFile::ImageHandleOrientation($exifData['Orientation'], $arFile["tmp_name"]); if ($properlyOriented) { $jpgQuality = intval(COption::GetOptionString('main', 'image_resize_quality', '95')); if ($jpgQuality <= 0 || $jpgQuality > 100) { $jpgQuality = 95; } imagejpeg($properlyOriented, $arFile["tmp_name"], $jpgQuality); } } } if (!$bucket->SaveFile($filePath, $arFile)) { return false; } } } $arFile["HANDLER_ID"] = $bucket->ID; $arFile["SUBDIR"] = $subDir; $arFile["FILE_NAME"] = $newName; $arFile["WIDTH"] = 0; $arFile["HEIGHT"] = 0; if (array_key_exists("bucket", $arFile)) { $arFile["WIDTH"] = $arFile["width"]; $arFile["HEIGHT"] = $arFile["height"]; $arFile["size"] = $arFile["file_size"]; } elseif ($copySize !== false) { $arFile["size"] = $copySize; $bucket->IncFileCounter($copySize); } else { $bucket->IncFileCounter(filesize($arFile["tmp_name"])); $flashEnabled = !CFile::IsImage($arFile["ORIGINAL_NAME"], $arFile["type"]); $imgArray = CFile::GetImageSize($arFile["tmp_name"], true, $flashEnabled); if (is_array($imgArray)) { $arFile["WIDTH"] = $imgArray[0]; $arFile["HEIGHT"] = $imgArray[1]; } } if (isset($arFile["old_file"])) { CFile::DoDelete($arFile["old_file"]); } return true; }
$arPrevHistory = $rsHistory->GetNext(); break; } $arNextHistory = $arHistory; } if (!empty($arPrevHistory)) { $iPrevHistoryId = $arPrevHistory['ID']; } if (!empty($arNextHistory)) { $iNextHistoryId = $arNextHistory['ID']; } $arResult['ELEMENT'] = $arHistoryResult['DOCUMENT']['FIELDS']; $arResult['ELEMENT']['~DETAIL_TEXT'] = $arResult['ELEMENT']['DETAIL_TEXT']; if (is_array($arHistoryResult['DOCUMENT']['PROPERTIES']['IMAGES']['VALUE'])) { foreach ($arHistoryResult['DOCUMENT']['PROPERTIES']['IMAGES']['VALUE'] as $_sImg) { $arResult['ELEMENT']['IMAGES'][strtolower(bx_basename($_sImg))] = $_sImg; } } $arParams['ELEMENT_ID'] = $arHistoryResult['DOCUMENT']['FIELDS']['ID']; $rsUser = CUser::GetByID($arHistoryResult['USER_ID']); $arUser = $rsUser->Fetch(); $arResult['VERSION'] = array(); $arResult['VERSION']['USER_LOGIN'] = CWikiUtils::GetUserLogin($arUser, $arParams["NAME_TEMPLATE"]); $arResult['VERSION']['MODIFIED'] = FormatDateFromDB($arHistoryResult['MODIFIED']); if ($iCurHistoryId != $historyId) { $arResult['VERSION']['CUR_LINK'] = CHTTP::urlAddParams(CComponentEngine::MakePathFromTemplate($arParams['PATH_TO_POST'], array('wiki_name' => urlencode($arParams['ELEMENT_NAME']), 'group_id' => CWikiSocnet::$iSocNetId)), array('oldid' => $iCurHistoryId)); } if (!empty($iPrevHistoryId)) { $arResult['VERSION']['PREV_LINK'] = CHTTP::urlAddParams(CComponentEngine::MakePathFromTemplate($arParams['PATH_TO_POST'], array('wiki_name' => urlencode($arParams['ELEMENT_NAME']), 'group_id' => CWikiSocnet::$iSocNetId)), array('oldid' => $iPrevHistoryId)); } if (!empty($iNextHistoryId)) {
/** * @param $templateName * @param $html * @return bool|int */ public static function update($templateName, $html) { $result = false; $fullPathOfFile = \Bitrix\Main\Loader::getLocal(static::LOCAL_DIR_TMPL . bx_basename($templateName) . '.php'); if ($fullPathOfFile) { $result = File::putFileContents($fullPathOfFile, $html); } return $result; }
protected static function prepareDataToInsertFromFileArray(array $fileData, array $data, ErrorCollection $errorCollection) { if (($fileData['error'] = intval($fileData['error'])) > 0) { if ($fileData['error'] < 3) { $errorCollection->addOne(new Error('upload_max_filesize: ' . intval(ini_get('upload_max_filesize')), static::ERROR_UPLOAD_MAX_FILE_SIZE)); return null; } $errorCollection->addOne(new Error('upload_error ' . $fileData['error'], static::ERROR_UPLOAD_FILE)); return null; } if (!is_uploaded_file($fileData['tmp_name'])) { $errorCollection->addOne(new Error('Current file is unsafe (is_uploaded_file check)', static::ERROR_IS_NOT_UPLOADED_FILE)); return null; } list($relativePath, $absolutePath) = static::generatePath(); if (!move_uploaded_file($fileData['tmp_name'], $absolutePath)) { $errorCollection->addOne(new Error('Could not move uploaded file (move_uploaded_file)', static::ERROR_MOVE_UPLOADED_FILE)); return null; } //now you can set CREATED_BY $data = array_intersect_key($data, array('CREATED_BY' => true)); return array_merge(array('TOKEN' => bx_basename($relativePath), 'FILENAME' => $fileData['name'], 'CONTENT_TYPE' => empty($fileData['type']) ? \CFile::getContentType($absolutePath) : $fileData['type'], 'PATH' => $relativePath, 'BUCKET_ID' => '', 'SIZE' => '', 'IS_CLOUD' => '', 'WIDTH' => empty($fileData['width']) ? '' : $fileData['width'], 'HEIGHT' => empty($fileData['height']) ? '' : $fileData['height']), $data); }
function OnFileSave(&$arFile, $strFileName, $strSavePath, $bForceMD5 = false, $bSkipExt = false) { if(!$arFile["tmp_name"] && !$arFile["content"]) return false; if(array_key_exists("bucket", $arFile)) $bucket = $arFile["bucket"]; else $bucket = CCloudStorage::FindBucketForFile($arFile, $strFileName); if(!is_object($bucket)) return false; if(!$bucket->Init()) return false; if(array_key_exists("bucket", $arFile)) { $newName = bx_basename($arFile["tmp_name"]); $prefix = $bucket->GetFileSRC("/"); $subDir = substr($arFile["tmp_name"], strlen($prefix)); $subDir = substr($subDir, 0, -strlen($newName)-1); } else { if( $bForceMD5 != true && COption::GetOptionString("main", "save_original_file_name", "N")=="Y" ) { if(COption::GetOptionString("main", "convert_original_file_name", "Y")=="Y") $newName = CCloudStorage::translit($strFileName); else $newName = $strFileName; } else { $strFileExt = ($bSkipExt == true? '' : strrchr($strFileName, ".")); $newName = md5(uniqid(mt_rand(), true)).$strFileExt; } //check for double extension vulnerability $newName = RemoveScriptExtension($newName); while(true) { $strRand = md5(mt_rand()); $strRand = substr($strRand, 0, 3)."/".$strRand; if(substr($strSavePath, -1) == "/") $subDir = $strSavePath.$strRand; else $subDir = $strSavePath."/".$strRand; $subDir = ltrim($subDir, "/"); $filePath = "/".$subDir."/".$newName; if(!$bucket->FileExists($filePath)) break; } if(!$bucket->SaveFile($filePath, $arFile)) return false; } $arFile["HANDLER_ID"] = $bucket->ID; $arFile["SUBDIR"] = $subDir; $arFile["FILE_NAME"] = $newName; $arFile["WIDTH"] = 0; $arFile["HEIGHT"] = 0; if(array_key_exists("bucket", $arFile)) { $arFile["WIDTH"] = $arFile["width"]; $arFile["HEIGHT"] = $arFile["height"]; $arFile["size"] = $arFile["file_size"]; } elseif(array_key_exists("content", $arFile)) { $tmp_name = tempnam(); $fp = fopen($tmp_name, "ab"); if($fp) { if(fwrite($fp, $arFile["content"])) { $bucket->IncFileCounter(filesize($tmp_name)); $imgArray = CFile::GetImageSize($tmp_name); if(is_array($imgArray)) { $arFile["WIDTH"] = $imgArray[0]; $arFile["HEIGHT"] = $imgArray[1]; } } fclose($fp); unlink($tmp_name); } } else { $bucket->IncFileCounter(filesize($arFile["tmp_name"])); $imgArray = CFile::GetImageSize($arFile["tmp_name"]); if(is_array($imgArray)) { $arFile["WIDTH"] = $imgArray[0]; $arFile["HEIGHT"] = $imgArray[1]; } } if(isset($arFile["old_file"])) CFile::DoDelete($arFile["old_file"]); return true; }
/** * Returns metadata for downloadable file. * @param string $path Path part of the URL. * @param HttpHeaders $httpHeaders Server's response headers. * @return array|bool Metadata record if mime type and filename were detected, or false otherwise. */ protected static function getFileMetadata($path, HttpHeaders $httpHeaders) { $mimeType = $httpHeaders->getContentType(); $filename = $httpHeaders->getFilename() ?: bx_basename($path); $result = false; if ($mimeType && $filename) { $result = array('TYPE' => UrlMetadataTable::TYPE_FILE, 'EXTRA' => array('ATTACHMENT' => strtolower($httpHeaders->getContentDisposition()) === 'attachment' ? 'Y' : 'N', 'MIME_TYPE' => $mimeType, 'FILENAME' => $filename, 'SIZE' => $httpHeaders->get('Content-Length'))); } return $result; }
function ResizeImageFile($sourceFile, &$destinationFile, $arSize, $resizeType = BX_RESIZE_IMAGE_PROPORTIONAL, $arWaterMark = array(), $jpgQuality = false, $arFilters = false) { $io = CBXVirtualIo::GetInstance(); if (!$io->FileExists($sourceFile)) { return false; } $bNeedCreatePicture = false; if ($resizeType != BX_RESIZE_IMAGE_EXACT && $resizeType != BX_RESIZE_IMAGE_PROPORTIONAL_ALT) { $resizeType = BX_RESIZE_IMAGE_PROPORTIONAL; } if (!is_array($arSize)) { $arSize = array(); } if (!array_key_exists("width", $arSize) || intval($arSize["width"]) <= 0) { $arSize["width"] = 0; } if (!array_key_exists("height", $arSize) || intval($arSize["height"]) <= 0) { $arSize["height"] = 0; } $arSize["width"] = intval($arSize["width"]); $arSize["height"] = intval($arSize["height"]); $arSourceSize = array("x" => 0, "y" => 0, "width" => 0, "height" => 0); $arDestinationSize = array("x" => 0, "y" => 0, "width" => 0, "height" => 0); $arSourceFileSizeTmp = CFile::GetImageSize($sourceFile); if (!in_array($arSourceFileSizeTmp[2], array(IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_GIF, IMAGETYPE_BMP))) { return false; } if (class_exists("imagick") && function_exists('memory_get_usage')) { //When memory limit reached we'll try to use ImageMagic $memoryNeeded = round(($arSourceFileSizeTmp[0] * $arSourceFileSizeTmp[1] * $arSourceFileSizeTmp['bits'] * ($arSourceFileSizeTmp['channels'] > 0 ? $arSourceFileSizeTmp['channels'] : 1) / 8 + pow(2, 16)) * 1.65); $memoryLimit = CUtil::Unformat(ini_get('memory_limit')); if (memory_get_usage() + $memoryNeeded > $memoryLimit) { if ($arSize["width"] <= 0 || $arSize["height"] <= 0) { $arSize["width"] = $arSourceFileSizeTmp[0]; $arSize["height"] = $arSourceFileSizeTmp[1]; } CFile::ScaleImage($arSourceFileSizeTmp[0], $arSourceFileSizeTmp[1], $arSize, $resizeType, $bNeedCreatePicture, $arSourceSize, $arDestinationSize); if ($bNeedCreatePicture) { $new_image = CTempFile::GetFileName(bx_basename($sourceFile)); CheckDirPath($new_image); $im = new Imagick(); try { $im->setSize($arDestinationSize["width"], $arDestinationSize["height"]); $im->readImage($io->GetPhysicalName($sourceFile)); $im->setImageFileName($new_image); $im->thumbnailImage($arDestinationSize["width"], $arDestinationSize["height"], true); $im->writeImage(); $im->destroy(); } catch (ImagickException $e) { $new_image = ""; } if ($new_image != "") { $sourceFile = $new_image; $arSourceFileSizeTmp = CFile::GetImageSize($io->GetPhysicalName($sourceFile)); } } } } if ($io->Copy($sourceFile, $destinationFile)) { switch ($arSourceFileSizeTmp[2]) { case IMAGETYPE_GIF: $sourceImage = imagecreatefromgif($io->GetPhysicalName($sourceFile)); $bHasAlpha = true; break; case IMAGETYPE_PNG: $sourceImage = imagecreatefrompng($io->GetPhysicalName($sourceFile)); $bHasAlpha = true; break; case IMAGETYPE_BMP: $sourceImage = CFile::ImageCreateFromBMP($io->GetPhysicalName($sourceFile)); $bHasAlpha = false; break; default: $sourceImage = imagecreatefromjpeg($io->GetPhysicalName($sourceFile)); $bHasAlpha = false; break; } $sourceImageWidth = intval(imagesx($sourceImage)); $sourceImageHeight = intval(imagesy($sourceImage)); if ($sourceImageWidth > 0 && $sourceImageHeight > 0) { if ($arSize["width"] <= 0 || $arSize["height"] <= 0) { $arSize["width"] = $sourceImageWidth; $arSize["height"] = $sourceImageHeight; } CFile::ScaleImage($sourceImageWidth, $sourceImageHeight, $arSize, $resizeType, $bNeedCreatePicture, $arSourceSize, $arDestinationSize); if ($bNeedCreatePicture) { if (CFile::IsGD2()) { $picture = ImageCreateTrueColor($arDestinationSize["width"], $arDestinationSize["height"]); if ($arSourceFileSizeTmp[2] == IMAGETYPE_PNG) { $transparentcolor = imagecolorallocatealpha($picture, 0, 0, 0, 127); imagefilledrectangle($picture, 0, 0, $arDestinationSize["width"], $arDestinationSize["height"], $transparentcolor); imagealphablending($picture, false); imagecopyresampled($picture, $sourceImage, 0, 0, $arSourceSize["x"], $arSourceSize["y"], $arDestinationSize["width"], $arDestinationSize["height"], $arSourceSize["width"], $arSourceSize["height"]); imagealphablending($picture, true); } elseif ($arSourceFileSizeTmp[2] == IMAGETYPE_GIF) { imagepalettecopy($picture, $sourceImage); //Save transparency for GIFs $transparentcolor = imagecolortransparent($sourceImage); if ($transparentcolor >= 0 && $transparentcolor < imagecolorstotal($sourceImage)) { $RGB = imagecolorsforindex($sourceImage, $transparentcolor); $transparentcolor = imagecolorallocate($picture, $RGB["red"], $RGB["green"], $RGB["blue"]); imagecolortransparent($picture, $transparentcolor); imagefilledrectangle($picture, 0, 0, $arDestinationSize["width"], $arDestinationSize["height"], $transparentcolor); } imagecopyresampled($picture, $sourceImage, 0, 0, $arSourceSize["x"], $arSourceSize["y"], $arDestinationSize["width"], $arDestinationSize["height"], $arSourceSize["width"], $arSourceSize["height"]); } else { imagecopyresampled($picture, $sourceImage, 0, 0, $arSourceSize["x"], $arSourceSize["y"], $arDestinationSize["width"], $arDestinationSize["height"], $arSourceSize["width"], $arSourceSize["height"]); } } else { $picture = ImageCreate($arDestinationSize["width"], $arDestinationSize["height"]); imagecopyresized($picture, $sourceImage, 0, 0, $arSourceSize["x"], $arSourceSize["y"], $arDestinationSize["width"], $arDestinationSize["height"], $arSourceSize["width"], $arSourceSize["height"]); } } else { $picture = $sourceImage; } if (is_array($arFilters)) { foreach ($arFilters as $arFilter) { $bNeedCreatePicture |= CFile::ApplyImageFilter($picture, $arFilter, $bHasAlpha); } } if (is_array($arWaterMark)) { $arWaterMark["name"] = "watermark"; $bNeedCreatePicture |= CFile::ApplyImageFilter($picture, $arWaterMark, $bHasAlpha); } if ($bNeedCreatePicture) { if ($io->FileExists($destinationFile)) { $io->Delete($destinationFile); } switch ($arSourceFileSizeTmp[2]) { case IMAGETYPE_GIF: imagegif($picture, $io->GetPhysicalName($destinationFile)); break; case IMAGETYPE_PNG: imagealphablending($picture, false); imagesavealpha($picture, true); imagepng($picture, $io->GetPhysicalName($destinationFile)); break; default: if ($arSourceFileSizeTmp[2] == IMAGETYPE_BMP) { $destinationFile .= ".jpg"; } if ($jpgQuality === false) { $jpgQuality = intval(COption::GetOptionString('main', 'image_resize_quality', '95')); } if ($jpgQuality <= 0 || $jpgQuality > 100) { $jpgQuality = 95; } imagejpeg($picture, $io->GetPhysicalName($destinationFile), $jpgQuality); break; } imagedestroy($picture); } } return true; } return false; }
/** * Lists folder contents * @param $path * @param $folderId * @return mixed */ public function listFolder($path, $folderId) { if ($path === '/') { $folderId = ''; } else { $folderId = $this->getForApiDecodedId($folderId); } $http = new HttpClient(array('socketTimeout' => 10, 'streamTimeout' => 30, 'version' => HttpClient::HTTP_1_1)); $http->setHeader('Content-Type', 'application/json; charset=UTF-8'); $http->setHeader('Authorization', "Bearer {$this->getAccessToken()}"); if ($http->get(self::API_URL . "/metadata/auto/{$folderId}") === false) { $errorString = implode('; ', array_keys($http->getError())); $this->errorCollection->add(array(new Error($errorString, self::ERROR_HTTP_LIST_FOLDER))); return null; } if (!$this->checkHttpResponse($http)) { return null; } $items = Json::decode($http->getResult()); if ($items === null) { $this->errorCollection->add(array(new Error('Could not decode response as json', self::ERROR_BAD_JSON))); return null; } if (!isset($items['contents'])) { $this->errorCollection->add(array(new Error('Could not find items in response', self::ERROR_HTTP_LIST_FOLDER))); return null; } $reformatItems = array(); foreach ($items['contents'] as $item) { $isFolder = (bool) $item['is_dir']; $dateTime = \DateTime::createFromFormat('D, d M Y H:i:s T', $item['modified']); $pseudoId = base64_encode($item['path']); $reformatItems[$pseudoId] = array('id' => $pseudoId, 'name' => bx_basename($item['path']), 'type' => $isFolder ? 'folder' : 'file', 'size' => $isFolder ? '' : \CFile::formatSize($item['bytes']), 'sizeInt' => $isFolder ? '' : $item['bytes'], 'modifyBy' => '', 'modifyDate' => $dateTime->format('d.m.Y'), 'modifyDateInt' => $dateTime->getTimestamp(), 'provider' => static::getCode()); if (!$isFolder) { $reformatItems[$pseudoId]['storage'] = ''; $reformatItems[$pseudoId]['ext'] = getFileExtension($reformatItems[$pseudoId]['name']); } } unset($item); return $reformatItems; }
function CheckFileByName($file, $fields) { $fileName = bx_basename($file); if (!empty($fields) && $fileName != "") { if (empty($this->arElementFiles)) { $this->arElementFiles = array(); $ID = array(); foreach ($this->arElementFilesId as $fileId) { foreach($fileId as $value) $ID[$value] = $value; } $rsFile = CFile::GetList(array(), array( "@ID" => implode(",", $ID), )); while ($arFile = $rsFile->Fetch()) { $arFile["~ORIGINAL_NAME"] = preg_replace("/(\\.resize[0-9]+\\.)/", ".", $arFile["ORIGINAL_NAME"]); $this->arElementFiles[$arFile["ID"]] = $arFile; } } foreach ($fields as $fieldId) { if (isset($this->arElementFilesId[$fieldId])) { foreach ($this->arElementFilesId[$fieldId] as $fileId) { if (isset($this->arElementFiles[$fileId])) { if ($this->arElementFiles[$fileId]["~ORIGINAL_NAME"] === $fileName) return $fileId; } } } } } return false; }
function IncludeLangFile($relativePath = "", $lang = false) { $arLangMessages = array(); if ($this->__folder != '') { $absPath = $_SERVER["DOCUMENT_ROOT"] . $this->__folder . "/lang/"; if ($lang === false) { $lang = LANGUAGE_ID; } if ($relativePath == "") { $relativePath = bx_basename($this->__file); } if ($lang != "en" && $lang != "ru") { $arLangMessages = $this->__IncludeLangFile($absPath . LangSubst($lang) . "/" . $relativePath); } $arLangMessages = $this->__IncludeLangFile($absPath . $lang . "/" . $relativePath) + $arLangMessages; } return $arLangMessages; }
/** * @param $matches * @return string * @throws \Bitrix\Main\IO\FileNotFoundException */ protected function getReplacedImageCid($matches) { $src = $matches[3]; if ($src == "") { return $matches[0]; } if (array_key_exists($src, $this->filesReplacedFromBody)) { $uid = $this->filesReplacedFromBody[$src]["ID"]; return $matches[1] . $matches[2] . "cid:" . $uid . $matches[4] . $matches[5]; } $io = \CBXVirtualIo::GetInstance(); $filePath = $io->GetPhysicalName(\Bitrix\Main\Application::getDocumentRoot() . $src); if (!File::isFileExists($filePath)) { return $matches[0]; } foreach ($this->attachment as $attach) { if ($filePath == $attach['PATH']) { return $matches[1] . $matches[2] . "cid:" . $attach['ID'] . $matches[4] . $matches[5]; } } if ($this->settingMaxFileSize > 0) { $fileIoObject = new File($filePath); if ($fileIoObject->getSize() > $this->settingMaxFileSize) { return $matches[0]; } } $aImage = \CFile::GetImageSize($filePath, true); if (!is_array($aImage)) { return $matches[0]; } if (function_exists("image_type_to_mime_type")) { $contentType = image_type_to_mime_type($aImage[2]); } else { $contentType = $this->imageTypeToMimeType($aImage[2]); } $uid = uniqid(md5($src)); $this->filesReplacedFromBody[$src] = array("SRC" => $src, "PATH" => $filePath, "CONTENT_TYPE" => $contentType, "NAME" => bx_basename($src), "ID" => $uid); return $matches[1] . $matches[2] . "cid:" . $uid . $matches[4] . $matches[5]; }
public function __replace_img($matches) { $io = CBXVirtualIo::GetInstance(); $src = $matches[3]; if ($src == "") { return $matches[0]; } if (array_key_exists($src, $this->aMatches)) { $uid = $this->aMatches[$src]["ID"]; return $matches[1] . $matches[2] . "cid:" . $uid . $matches[4] . $matches[5]; } $filePath = $io->GetPhysicalName($_SERVER["DOCUMENT_ROOT"] . $src); if (!file_exists($filePath)) { return $matches[0]; } if ($this->maxFileSize > 0 && filesize($filePath) > $this->maxFileSize) { return $matches[0]; } $aImage = CFile::GetImageSize($filePath, true); if (!is_array($aImage)) { return $matches[0]; } if (function_exists("image_type_to_mime_type")) { $contentType = image_type_to_mime_type($aImage[2]); } else { $contentType = CMailTools::ImageTypeToMimeType($aImage[2]); } $uid = uniqid(md5($src)); $this->aMatches[$src] = array("SRC" => $src, "PATH" => $filePath, "CONTENT_TYPE" => $contentType, "DEST" => bx_basename($src), "ID" => $uid); return $matches[1] . $matches[2] . "cid:" . $uid . $matches[4] . $matches[5]; }
protected function migrateVersion() { if (!$this->runWorkWithBizproc) { return; } if ($this->isStepFinished(__METHOD__)) { return; } $uploadDir = COption::getOptionString("main", "upload_dir", "upload"); $isCloud = CModule::IncludeModule("clouds"); $useGZipCompressionOption = \Bitrix\Main\Config\Option::get("bizproc", "use_gzip_compression", ""); $isBitrix24 = IsModuleInstalled('bitrix24'); $bucket = null; if ($isBitrix24 && $isCloud) { $bucket = new CCloudStorageBucket(1); $bucket->init(); } if ($useGZipCompressionOption === "Y") { $this->useGZipCompression = true; } elseif ($useGZipCompressionOption === "N") { $this->useGZipCompression = false; } else { $this->useGZipCompression = function_exists("gzcompress") && ($GLOBALS["DB"]->type != "ORACLE" || !defined('BX_UTF')); } $sqlHelper = $this->connection->getSqlHelper(); $lastId = $this->getStorageId(); $versionQuery = $this->connection->query("\n\t\t\tSELECT\n\t\t\t\tobj.*,\n\t\t\t\th.ID VERSION_ID,\n\t\t\t\th.NAME VERSION_NAME,\n\t\t\t\th.DOCUMENT VERSION_DOC,\n\t\t\t\th.USER_ID VERSION_USER_ID,\n\t\t\t\th.MODIFIED VERSION_MODIFIED\n\t\t\tFROM b_disk_object obj\n\t\t\t\tINNER JOIN b_bp_history h ON h.DOCUMENT_ID = obj.WEBDAV_ELEMENT_ID AND h.MODULE_ID = 'webdav'\n\n\t\t\tWHERE obj.TYPE = 3 AND h.ID > {$lastId} ORDER BY h.ID\n\t\t"); while ($version = $versionQuery->fetch()) { $this->abortIfNeeded(); if (strlen($version['VERSION_DOC']) > 0) { if ($this->useGZipCompression) { $version['VERSION_DOC'] = gzuncompress($version['VERSION_DOC']); } $version['VERSION_DOC'] = unserialize($version['VERSION_DOC']); if (!is_array($version['VERSION_DOC'])) { $version['VERSION_DOC'] = array(); } } else { $version['VERSION_DOC'] = array(); } if (empty($version['VERSION_DOC']) || empty($version['VERSION_DOC']['PROPERTIES']['WEBDAV_VERSION']['VALUE']) || empty($version['VERSION_DOC']['PROPERTIES']['FILE']['VALUE'])) { $this->storeStorageId($version['VERSION_ID']); continue; } $version['VERSION_NAME'] = $sqlHelper->forSql($version['VERSION_NAME']); $version['VERSION_MODIFIED'] = $sqlHelper->getCharToDateFunction($version['VERSION_MODIFIED']->format("Y-m-d H:i:s")); $version['UPDATE_TIME'] = $sqlHelper->getCharToDateFunction($version['UPDATE_TIME']->format("Y-m-d H:i:s")); $fullPath = $version['VERSION_DOC']['PROPERTIES']['FILE']['VALUE']; $handlerId = ''; $filename = bx_basename($fullPath); if (substr($fullPath, 0, 4) == "http") { if (!$isCloud) { $this->storeStorageId($version['VERSION_ID']); continue; } if (!$isBitrix24) { $bucket = CCloudStorage::findBucketByFile($fullPath); if (!$bucket) { $this->storeStorageId($version['VERSION_ID']); continue; } } $handlerId = $bucket->ID; $subDir = trim(substr(getDirPath($fullPath), strlen($bucket->getFileSRC('/'))), '/'); $contentType = \Bitrix\Disk\TypeFile::getMimeTypeByFilename($filename); } else { $subDir = trim(substr(getDirPath($fullPath), strlen('/' . $uploadDir)), '/'); $contentType = CFile::getContentType($_SERVER["DOCUMENT_ROOT"] . $fullPath); $contentType = \Bitrix\Disk\TypeFile::normalizeMimeType($contentType, $filename); } $webdavSize = $version['VERSION_DOC']['PROPERTIES']['WEBDAV_SIZE']['VALUE']; if (empty($webdavSize)) { $webdavSize = 0; } $fileId = CFile::doInsert(array('HEIGHT' => 0, 'WIDTH' => 0, 'FILE_SIZE' => $webdavSize, 'CONTENT_TYPE' => $contentType, 'SUBDIR' => $subDir, 'FILE_NAME' => $filename, 'MODULE_ID' => Driver::INTERNAL_MODULE_ID, 'ORIGINAL_NAME' => $filename, 'DESCRIPTION' => '', 'HANDLER_ID' => $handlerId, 'EXTERNAL_ID' => md5(mt_rand()))); if (!$fileId) { $this->storeStorageId($version['VERSION_ID']); continue; } $this->connection->queryExecute("\n\t\t\t\tINSERT INTO b_disk_version (OBJECT_ID, FILE_ID, " . $this->sqlHelper->quote('SIZE') . ", NAME, CREATE_TIME, CREATED_BY, MISC_DATA, OBJECT_CREATE_TIME, OBJECT_CREATED_BY, OBJECT_UPDATE_TIME, OBJECT_UPDATED_BY, GLOBAL_CONTENT_VERSION, BP_VERSION_ID)\n\t\t\t\tVALUES ({$version['ID']}, {$fileId}, {$webdavSize}, '{$version['VERSION_NAME']}', {$version['VERSION_MODIFIED']}, {$version['VERSION_USER_ID']}, null, {$version['VERSION_MODIFIED']}, {$version['CREATED_BY']}, {$version['UPDATE_TIME']}, {$version['UPDATED_BY']}, {$version['VERSION_DOC']['PROPERTIES']['WEBDAV_VERSION']['VALUE']}, {$version['VERSION_ID']})\n\t\t\t"); $this->storeStorageId($version['VERSION_ID']); } $this->abortIfNeeded(); $this->storeStorageId(0); $this->setStepFinished(__METHOD__); }
function ResizePicture($file, $resize, $primaryField, $secondaryField = "") { static $errorFile = array("tmp_name" => "", "del" => "Y"); $external_id = md5($file); if (strlen($file) <= 0) { return $errorFile; } if (file_exists($this->files_dir . $file) && is_file($this->files_dir . $file)) { $file = $this->files_dir . $file; } elseif (file_exists($file) && is_file($file)) { } elseif (($fileId = $this->CheckFileByName($external_id, array($primaryField))) > 0) { return CFile::MakeFileArray($fileId); } elseif ($secondaryField && ($fileId = $this->CheckFileByName($external_id, array($secondaryField))) > 0) { $storedFile = CFile::MakeFileArray($fileId); if ($storedFile) { $tempFile = CTempFile::GetFileName(bx_basename($storedFile["tmp_name"])); CheckDirPath($tempFile); if (copy($storedFile["tmp_name"], $tempFile)) { $storedFile["tmp_name"] = $tempFile; return $storedFile; } else { return $errorFile; } } else { return $errorFile; } } else { return $errorFile; } if (!is_array($resize) || !preg_match("#(\\.)([^./\\\\]+?)\$#", $file)) { $arFile = CFile::MakeFileArray($file, false, false, $external_id); if ($arFile && $this->iblock_resize) { $arFile["COPY_FILE"] = "Y"; } return $arFile; } $i = 1; while (file_exists(preg_replace("#(\\.)([^./\\\\]+?)\$#", ".resize" . $i . ".\\2", $file))) { $i++; } $new_file = preg_replace("#(\\.)([^./\\\\]+?)\$#", ".resize" . $i . ".\\2", $file); if (!CFile::ResizeImageFile($file, $new_file, array("width" => $resize[0], "height" => $resize[1]))) { return CFile::MakeFileArray($file, false, false, $external_id); } $this->arTempFiles[] = $new_file; return CFile::MakeFileArray($new_file, false, false, $external_id); }
function _processFileCallback($matches) { static $sImageAlign = ''; $bLink = false; if ($matches[1] == ':') { $bLink = true; } // if the internal file then get it $sFile = $sFileName = $sPath = trim($matches[3]); $bOur = false; if (is_numeric($sFile) && in_array($sFile, $this->arFile)) { $arFile = CFile::GetFileArray($sFile); if ($arFile != false) { $bOur = true; $sPath = $arFile['SRC']; $sFileName = $arFile['ORIGINAL_NAME']; } } else { if (isset($this->arVersionFile[strtolower($sFile)])) { $sPath = $this->arVersionFile[strtolower($sFile)]; $sFileName = $sFile; } else { if (!empty($this->arFile)) { $arFilter = array('@ID' => implode(',', $this->arFile)); $rsFile = CFile::GetList(array(), $arFilter); while ($arFile = $rsFile->Fetch()) { if ($arFile['ORIGINAL_NAME'] == $sFile) { $bOur = true; $sFile = $arFile['ID']; $sPath = CFile::GetFileSRC($arFile); $sFileName = $arFile['ORIGINAL_NAME']; break; } } } } } // if the image is processed as a picture $sName = bx_basename($sPath); if (CFile::IsImage($sName)) { if ($bOur) { $imageFile = CFile::MakeFileArray($sPath); $checkRes = CFile::CheckImageFile($imageFile); if ($checkRes != null) { return $checkRes; } if ($bLink) { $sReturn = '<a href="' . htmlspecialcharsbx($sPath) . '" title="' . ($s = htmlspecialcharsbx($sFileName)) . '">' . $s . '</a>'; } else { $sReturn = CFile::ShowImage($sFile, COption::GetOptionString('wiki', 'image_max_width', 600), COption::GetOptionString('wiki', 'image_max_height', 600), 'border="0" align="' . $sImageAlign . '"'); } } else { if ($bLink) { $sReturn = '<a href="' . htmlspecialcharsbx($sPath) . '" title="' . ($s = htmlspecialcharsbx($sName)) . '">' . $s . '</a>'; } else { $sReturn = '<img src="' . htmlspecialcharsbx($sPath) . '" alt="' . htmlspecialcharsbx($sFileName) . '"/>'; } } } else { if (strpos($sPath, 'http://') === 0) { $sReturn = ' [ <a href="' . htmlspecialcharsbx($sFile) . '" title="' . GetMessage('FILE_FILE_DOWNLOAD') . '">' . GetMessage('FILE_DOWNLOAD') . '</a> ] '; } else { $sReturn = '[' . GetMessage('FILE_NAME') . ':' . htmlspecialcharsbx(is_numeric($sFile) || empty($sFileName) ? $sFile : $sFileName) . ']'; } } return $sReturn; }
function IncludeLangFile($relativePath = "", $lang = false, $return = false) { $arLangMessages = array(); if ($this->__folder != '') { if ($relativePath == "") { $relativePath = bx_basename($this->__file); } $absPath = $_SERVER["DOCUMENT_ROOT"] . $this->__folder . "/" . $relativePath; if ($lang === false && $return === false) { \Bitrix\Main\Localization\Loc::loadMessages($absPath); } else { if ($lang === false) { $lang = $this->getLanguageId(); } $arLangMessages = \Bitrix\Main\Localization\Loc::loadLanguageFile($absPath, $lang); } } return $arLangMessages; }
function MakeFileArray($path, $mimetype=false) { $io = CBXVirtualIo::GetInstance(); $arFile = Array(); if(intval($path)>0) { $res = CFile::GetByID($path); if($ar = $res->Fetch()) { $bExternalStorage = false; foreach(GetModuleEvents("main", "OnMakeFileArray", true) as $arEvent) { if(ExecuteModuleEventEx($arEvent, array($ar, &$arFile))) { $bExternalStorage = true; break; } } if(!$bExternalStorage) { $arFile["name"] = (strlen($ar['ORIGINAL_NAME'])>0?$ar['ORIGINAL_NAME']:$ar['FILE_NAME']); $arFile["size"] = $ar['FILE_SIZE']; $arFile["type"] = $ar['CONTENT_TYPE']; $arFile["description"] = $ar['DESCRIPTION']; $arFile["tmp_name"] = $io->GetPhysicalName(preg_replace("#[\\\\\\/]+#", "/", $_SERVER['DOCUMENT_ROOT'].'/'.(COption::GetOptionString('main', 'upload_dir', 'upload')).'/'.$ar['SUBDIR'].'/'.$ar['FILE_NAME'])); } return $arFile; } } $path = preg_replace("#(?<!:)[\\\\\\/]+#", "/", $path); if(strlen($path) == 0 || $path == "/") return NULL; if(preg_match("#^(http[s]?)://#", $path)) { $temp_path = ''; $bExternalStorage = false; foreach(GetModuleEvents("main", "OnMakeFileArray", true) as $arEvent) { if(ExecuteModuleEventEx($arEvent, array($path, &$temp_path))) { $bExternalStorage = true; break; } } if(!$bExternalStorage) { $temp_path = CFile::GetTempName('', bx_basename($path)); $ob = new CHTTP; $ob->follow_redirect = true; if($ob->Download($path, $temp_path)) $arFile = CFile::MakeFileArray($temp_path); } elseif($temp_path) { $arFile = CFile::MakeFileArray($temp_path); } } elseif(preg_match("#^(ftp[s]?|php)://#", $path)) { if($fp = fopen($path,"rb")) { $content = ""; while(!feof($fp)) $content .= fgets($fp, 4096); if(strlen($content) > 0) { $temp_path = CFile::GetTempName('', bx_basename($path)); if (RewriteFile($temp_path, $content)) $arFile = CFile::MakeFileArray($temp_path); } fclose($fp); } } else { if(!file_exists($path)) { if (file_exists($_SERVER["DOCUMENT_ROOT"].$path)) $path = $_SERVER["DOCUMENT_ROOT"].$path; else return NULL; } if(is_dir($path)) return NULL; $arFile["name"] = $io->GetLogicalName(bx_basename($path)); $arFile["size"] = filesize($path); $arFile["tmp_name"] = $path; $arFile["type"] = $mimetype; if(strlen($arFile["type"])<=0) $arFile["type"] = CFile::GetContentType($path, true); } if(strlen($arFile["type"])<=0) $arFile["type"] = "unknown"; return $arFile; }