35 if (isset($arFile) && is_array($arFile))
38 (isset($arFile[
"name"]) && $arFile[
"name"] <>
'')
39 || (isset($arFile[
"del"]) && $arFile[
"del"] <>
'')
40 || array_key_exists(
"description", $arFile)
43 $res = static::SaveFile($arFile, $strSavePath);
61 if ($arFile[
"name"] ==
"")
66 $fileName = self::transformName($arFile[
"name"]);
67 return self::validateFile(
$fileName, $arFile);
80 $originalName = ($forceRandom !=
true && COption::GetOptionString(
"main",
"save_original_file_name",
"N") ==
"Y");
86 if (COption::GetOptionString(
"main",
"translit_original_file_name",
"N") ==
"Y")
91 "replace_space" =>
'-',
92 "change_case" =>
false,
97 if (COption::GetOptionString(
"main",
"convert_original_file_name",
"Y") ==
"Y")
124 if ($strFileName ==
'')
130 if (!
$io->ValidateFilenameString($strFileName))
135 if (mb_strlen($strFileName) > 255)
152 if (COption::GetOptionInt(
"main",
"disk_space") > 0)
155 if (!$quota->checkDiskQuota($arFile))
164 public static function SaveFile($arFile, $strSavePath, $forceRandom =
false, $skipExtension =
false, $dirAdd =
'')
168 if (isset($arFile[
"del"]) && $arFile[
"del"] <>
'')
170 static::Delete($arFile[
"old_file"] ?? 0);
171 if ($strFileName ==
'')
177 if (!isset($arFile[
"name"]) || $arFile[
"name"] ==
'')
179 if (isset($arFile[
"description"]) && isset($arFile[
"old_file"]) && intval($arFile[
"old_file"]) > 0)
181 static::UpdateDesc($arFile[
"old_file"], $arFile[
"description"]);
186 if (isset($arFile[
"content"]))
188 if (!isset($arFile[
"size"]))
190 $arFile[
"size"] = strlen($arFile[
"content"]);
198 $arFile[
"size"] = $file->getSize();
202 if (!isset($arFile[
"size"]) || !is_int($arFile[
"size"]))
209 $arFile[
"ORIGINAL_NAME"] = $strFileName;
212 $strFileName = self::transformName($strFileName, $forceRandom, $skipExtension);
215 if (self::validateFile($strFileName, $arFile) !==
"")
229 $bExternalStorage =
false;
232 if (
ExecuteModuleEventEx($arEvent, [&$arFile, $strFileName, $strSavePath, $forceRandom, $skipExtension, $dirAdd]))
234 $bExternalStorage =
true;
239 if (!$bExternalStorage)
244 $upload_dir = COption::GetOptionString(
"main",
"upload_dir",
"upload");
246 if (!$forceRandom && COption::GetOptionString(
"main",
"save_original_file_name",
"N") ==
"Y")
255 $subdir = substr(md5($random), 0, 3) .
"/" . $random;
257 if (!
$io->FileExists(
$_SERVER[
"DOCUMENT_ROOT"] .
"/" . $upload_dir .
"/" . $strSavePath .
"/" . $subdir .
"/" . $strFileName))
263 $strSavePath = rtrim($strSavePath,
"/") .
"/" . $subdir;
268 $fileExtension = ($skipExtension || ($ext =
GetFileExtension($strFileName)) ==
'' ?
'' :
"." . $ext);
271 $subdir = substr(md5($strFileName), 0, 3);
272 $strSavePath = rtrim($strSavePath,
"/") .
"/" . $subdir;
274 if (!
$io->FileExists(
$_SERVER[
"DOCUMENT_ROOT"] .
"/" . $upload_dir .
"/" . $strSavePath .
"/" . $strFileName))
284 $arFile[
"SUBDIR"] = $strSavePath;
285 $arFile[
"FILE_NAME"] = $strFileName;
287 $dirName =
$_SERVER[
"DOCUMENT_ROOT"] .
"/" . $upload_dir .
"/" . $strSavePath .
"/";
288 $physicalFileName =
$io->GetPhysicalName($dirName . $strFileName);
292 if (
is_set($arFile,
"content"))
294 if (file_put_contents($physicalFileName, $arFile[
"content"]) ===
false)
301 if (!copy($arFile[
"tmp_name"], $physicalFileName) && !move_uploaded_file($arFile[
"tmp_name"], $physicalFileName))
307 if (isset($arFile[
"old_file"]))
309 static::Delete($arFile[
"old_file"]);
312 @chmod($physicalFileName, BX_FILE_PERMISSIONS);
315 $flashEnabled = !static::IsImage($arFile[
"ORIGINAL_NAME"], $arFile[
"type"]);
319 $imgInfo = $image->getInfo($flashEnabled);
323 $arFile[
"WIDTH"] = $imgInfo->getWidth();
324 $arFile[
"HEIGHT"] = $imgInfo->getHeight();
328 $arFile[
"WIDTH"] = 0;
329 $arFile[
"HEIGHT"] = 0;
333 $arFile[
"FILE_HASH"] = static::CalculateHash($physicalFileName, $arFile[
"size"]);
336 if ($arFile[
"FILE_HASH"] <>
'')
338 $original = static::FindDuplicate($arFile[
"size"], $arFile[
"FILE_HASH"]);
340 if ($original !==
null)
343 $arFile[
"SUBDIR"] = $original->getFile()->getSubdir();
344 $arFile[
"FILE_NAME"] = $original->getFile()->getFileName();
346 $originalPath =
$_SERVER[
"DOCUMENT_ROOT"] .
"/" . $upload_dir .
"/" . $arFile[
"SUBDIR"] .
"/" . $arFile[
"FILE_NAME"];
348 if ($physicalFileName <>
$io->GetPhysicalName($originalPath))
350 unlink($physicalFileName);
353 rmdir(
$io->GetPhysicalName($dirName));
355 catch (\ErrorException)
366 if (isset($arFile[
"original_file"]) && $arFile[
"original_file"] instanceof
Internal\
EO_FileHash)
368 $original = $arFile[
"original_file"];
372 if ($arFile[
"WIDTH"] == 0 || $arFile[
"HEIGHT"] == 0)
375 if (str_starts_with($arFile[
"type"],
"image/") && $arFile[
"type"] <>
'image/svg+xml')
377 $arFile[
"type"] =
"application/octet-stream";
382 if (COption::GetOptionInt(
"main",
"disk_space") > 0 && $original ===
null)
384 CDiskQuota::updateDiskQuota(
"file", $arFile[
"size"],
"insert");
388 $NEW_IMAGE_ID = static::DoInsert([
389 "HEIGHT" => $arFile[
"HEIGHT"],
390 "WIDTH" => $arFile[
"WIDTH"],
391 "FILE_SIZE" => $arFile[
"size"],
392 "CONTENT_TYPE" => $arFile[
"type"],
393 "SUBDIR" => $arFile[
"SUBDIR"],
394 "FILE_NAME" => $arFile[
"FILE_NAME"],
395 "MODULE_ID" => $arFile[
"MODULE_ID"] ??
'',
396 "ORIGINAL_NAME" => $arFile[
"ORIGINAL_NAME"],
397 "DESCRIPTION" => ($arFile[
"description"] ??
''),
398 "HANDLER_ID" => ($arFile[
"HANDLER_ID"] ??
''),
399 "EXTERNAL_ID" => ($arFile[
"external_id"] ?? md5(mt_rand())),
400 "FILE_HASH" => ($original ===
null ? $arFile[
"FILE_HASH"] :
''),
403 if ($original !==
null)
406 static::AddDuplicate($original->getFileId(), $NEW_IMAGE_ID,
false);
411 static::CleanCache($NEW_IMAGE_ID);
413 return $NEW_IMAGE_ID;
425 if ($size > 0 && COption::GetOptionString(
'main',
'control_file_duplicates',
'N') ===
'Y')
427 $maxSize = (int)COption::GetOptionString(
'main',
'duplicates_max_size',
'100') * 1024 * 1024;
428 if ($size <= $maxSize || $maxSize === 0)
430 $hash = hash_file(
"md5", $file);
445 ->where(
"FILE_SIZE", $size)
446 ->where(
"FILE_HASH",
$hash)
449 if ($handlerId !==
null)
451 $filter->where(
"FILE.HANDLER_ID", $handlerId);
457 ->where(
'FILE.HANDLER_ID',
'')
458 ->whereNull(
'FILE.HANDLER_ID')
463 ->addSelect(
"FILE.*")
465 ->addOrder(
"FILE_ID")
482 public static function AddDuplicate($originalId, $duplicateId =
null,
bool $resolvePossibleOriginCycle =
true)
484 if ($duplicateId ===
null)
486 $duplicateId = $originalId;
489 if ($resolvePossibleOriginCycle || $originalId == $duplicateId)
493 ->addSelect(
"ORIGINAL_ID")
494 ->where(
"DUPLICATE_ID", $originalId)
500 $originalId = $original[
"ORIGINAL_ID"];
509 "DUPLICATE_ID" => $duplicateId,
510 "ORIGINAL_ID" => $originalId,
513 Internal\FileDuplicateTable::merge($insertFields, $updateFields);
527 'select' => [
'FILE_SIZE',
'FILE_HASH',
'FILE.*'],
528 'filter' => [
'=FILE_ID' => $originalId],
535 $originalPath =
'/' . $original->getFile()->getSubdir() .
'/' . $original->getFile()->getFileName();
538 $uploadDir = COption::GetOptionString(
"main",
"upload_dir",
"upload");
541 $fileList = \Bitrix\Main\FileTable::getList([
542 'select' => [
'ID',
'FILE_SIZE',
'SUBDIR',
'FILE_NAME'],
544 '=ID' => $duplicteIds,
545 '=HANDLER_ID' => $original->getFile()->getHandlerId(),
551 while ($duplicate = $fileList->fetchObject())
557 $duplicatePath =
'/' . $duplicate->getSubdir() .
'/' . $duplicate->getFileName();
558 if ($originalPath == $duplicatePath)
579 static::AddDuplicate($originalId, $duplicate->getId(),
false);
581 $update = $helper->prepareUpdate(
'b_file', [
582 'SUBDIR' => $original->getFile()->getSubdir(),
583 'FILE_NAME' => $original->getFile()->getFileName(),
585 $ddl =
'UPDATE b_file SET ' . $update[0] .
'WHERE ID = ' . $duplicate->getId();
588 static::cleanCache($duplicate->getId());
598 $dname =
$_SERVER[
"DOCUMENT_ROOT"] .
'/' . $uploadDir .
'/' . $duplicate->getSubdir();
599 $fname = $dname .
'/' . $duplicate->getFileName();
601 $file =
$io->GetFile($fname);
602 if ($file->isExists() && $file->unlink())
604 $deleteSize += $duplicate->getFileSize();
607 $directory =
$io->GetDirectory($dname);
608 if ($directory->isExists() && $directory->isEmpty())
610 if ($directory->rmdir())
613 if ($parent->isExists() && $parent->isEmpty())
625 if ($deleteSize > 0 && COption::GetOptionInt(
"main",
"disk_space") > 0)
627 CDiskQuota::updateDiskQuota(
"file", $deleteSize,
"delete");
634 $originalFile = static::GetByID($fileId)->Fetch();
640 $originalFile[
'FILE_HASH'] =
'';
642 $cloneId = static::DoInsert($originalFile);
644 static::AddDuplicate($fileId, $cloneId);
645 static::CleanCache($cloneId);
654 $size = round(floatval(
$arFields[
"FILE_SIZE"]));
671 " .
$DB->GetNowFunction() .
"
682 ," . (
$arFields[
"EXTERNAL_ID"] !=
"" ?
"'" .
$DB->ForSql(
$arFields[
"EXTERNAL_ID"], 50) .
"'" :
"null") .
"
685 $fileId =
$DB->LastID();
691 "FILE_ID" => $fileId,
692 "FILE_SIZE" => $size,
718 $res = static::GetByID(
$ID,
true);
722 $delete = static::processDuplicates(
$ID);
724 if ($delete === self::DELETE_NONE)
733 if ($delete & self::DELETE_FILE)
735 $upload_dir = COption::GetOptionString(
"main",
"upload_dir",
"upload");
736 $dname =
$_SERVER[
"DOCUMENT_ROOT"] .
"/" . $upload_dir .
"/" .
$res[
"SUBDIR"];
737 $fname = $dname .
"/" .
$res[
"FILE_NAME"];
741 $file =
$io->GetFile($fname);
742 if ($file->isExists() && $file->unlink())
744 $delete_size +=
$res[
"FILE_SIZE"];
747 $delete_size += static::ResizeImageDelete(
$res);
749 $directory =
$io->GetDirectory($dname);
750 if ($directory->isExists() && $directory->isEmpty())
752 if ($directory->rmdir())
755 if ($parent->isExists() && $parent->isEmpty())
762 foreach (
GetModuleEvents(
"main",
"OnPhysicalFileDelete",
true) as $arEvent)
768 if ($delete & self::DELETE_DB)
778 static::processVersions(
$ID);
780 $connection->query(
"DELETE FROM b_file WHERE ID = {$ID}");
782 static::CleanCache(
$ID);
786 if ($delete_size > 0 && COption::GetOptionInt(
"main",
"disk_space") > 0)
788 CDiskQuota::updateDiskQuota(
"file", $delete_size,
"delete");
803 ->where(
"DUPLICATE_ID",
$ID)
809 ->where(
"ORIGINAL_ID",
$ID)
817 if ($original[
"COUNTER"] > 1)
822 "DUPLICATE_ID" =>
$ID,
823 "ORIGINAL_ID" => $original[
"ORIGINAL_ID"],
837 "DUPLICATE_ID" =>
$ID,
838 "ORIGINAL_ID" => $original[
"ORIGINAL_ID"],
842 if ($original[
"DUPLICATE_ID"] <> $original[
"ORIGINAL_ID"])
844 if ($original[
"ORIGINAL_DELETED"] ===
"Y")
847 static::Delete($original[
"ORIGINAL_ID"]);
875 public static function AddVersion($originalId, $versionId, $metaData = [])
878 'ORIGINAL_ID' => $originalId,
879 'VERSION_ID' => $versionId,
880 ] + (empty($metaData) ? [] : [
884 static::CleanCache($originalId);
894 ->where(
'VERSION_ID',
$ID)
900 static::CleanCache($original[
'ORIGINAL_ID']);
906 ->where(
'ORIGINAL_ID',
$ID)
909 while ($version = $versions->fetch())
911 static::Delete($version[
'VERSION_ID']);
917 if (CACHED_b_file !==
false)
919 $bucket_size = (int)CACHED_b_file_bucket_size;
920 if ($bucket_size <= 0)
925 $bucket = (int)($fileId / $bucket_size);
929 $cache->clean(self::CACHE_DIR .
'01' . $bucket, self::CACHE_DIR);
930 $cache->clean(self::CACHE_DIR .
'11' . $bucket, self::CACHE_DIR);
931 $cache->clean(self::CACHE_DIR .
'00' . $bucket, self::CACHE_DIR);
932 $cache->clean(self::CACHE_DIR .
'10' . $bucket, self::CACHE_DIR);
942 $bucketSize = (int)CACHED_b_file_bucket_size;
943 if ($bucketSize <= 0)
948 $bucket = (int)($fileId / $bucketSize);
949 $https = (int)
Main\Context::getCurrent()->getRequest()->isHttps();
950 $cacheId = self::CACHE_DIR . $https . (int)$realId . $bucket;
952 if ($cache->read(CACHED_b_file, $cacheId, self::CACHE_DIR))
954 $files = $cache->get($cacheId);
956 if (!isset(
$files[$fileId]))
964 if ($file = static::GetFromDb($fileId, $realId)->Fetch())
967 static::CleanCache($fileId);
975 $minId = $bucket * $bucketSize;
976 $maxId = ($bucket + 1) * $bucketSize - 1;
980 {$DB->DateToCharFunction("f.TIMESTAMP_X
")} as TIMESTAMP_X,
981 NULL as VERSION_ORIGINAL_ID, '' as META
983 WHERE f.ID >= {$minId}
987 if ($realId !==
true)
992 {$DB->DateToCharFunction("f.TIMESTAMP_X
")} as TIMESTAMP_X,
993 fv.ORIGINAL_ID as VERSION_ORIGINAL_ID, fv.META as META
995 INNER JOIN b_file_version fv ON fv.VERSION_ID = f.ID
996 WHERE fv.ORIGINAL_ID >= {$minId}
997 AND fv.ORIGINAL_ID <= {$maxId}
1004 while ($file =
$rs->fetch())
1006 $originalId = ($file[
'VERSION_ORIGINAL_ID'] ?: $file[
"ID"]);
1007 $files[$originalId] = $file;
1011 foreach (
$files as $id => $file)
1013 $files[$id][
'SRC'] = static::GetFileSRC($file);
1016 $cache->setImmediate($cacheId,
$files);
1021 public static function GetByID($fileId, $realId =
false)
1023 $fileId = (int)$fileId;
1025 if (CACHED_b_file ===
false)
1027 $result = static::GetFromDb($fileId, $realId);
1031 $files = static::GetFromCache($fileId, $realId);
1045 {$DB->DateToCharFunction("f.TIMESTAMP_X
")} as TIMESTAMP_X,
1046 NULL as VERSION_ORIGINAL_ID, '' as META
1048 WHERE f.ID = {$fileId}
1051 if ($realId !==
true)
1056 {$DB->DateToCharFunction("f.TIMESTAMP_X
")} as TIMESTAMP_X,
1057 fv.ORIGINAL_ID as VERSION_ORIGINAL_ID, fv.META as META
1059 INNER JOIN b_file_version fv ON fv.VERSION_ID = f.ID
1060 WHERE fv.ORIGINAL_ID = {$fileId}
1066 return $DB->Query($strSql);
1083 if (str_starts_with(
$key,
"@"))
1086 $strOperation =
"IN";
1089 foreach ($arIn as $v)
1091 $val .= (
$val <> '' ?
',' :
'') .
"'" .
$DB->ForSql(trim($v)) .
"'";
1111 case "ORIGINAL_NAME":
1112 case "CONTENT_TYPE":
1114 if ($strOperation ==
"IN")
1116 $arSqlSearch[] =
"f." .
$key .
" IN (" .
$val .
")";
1120 $arSqlSearch[] =
"f." .
$key .
" = '" .
$val .
"'";
1126 if (!empty($arSqlSearch))
1128 $strSqlSearch =
" WHERE (" . implode(
") AND (", $arSqlSearch) .
")";
1131 if (is_array($arOrder))
1140 "CONTENT_TYPE" => 1,
1143 "ORIGINAL_NAME" => 1,
1146 foreach ($arOrder as $by => $ord)
1148 $by = strtoupper($by);
1149 if (array_key_exists($by, $aCols))
1151 $arSqlOrder[] =
"f." . $by .
" " . (strtoupper($ord) ==
"DESC" ?
"DESC" :
"ASC");
1155 if (empty($arSqlOrder))
1157 $arSqlOrder[] =
"f.ID ASC";
1159 $strSqlOrder =
" ORDER BY " . implode(
", ", $arSqlOrder);
1162 "SELECT f.*, " .
$DB->DateToCharFunction(
"f.TIMESTAMP_X") .
" as TIMESTAMP_X " .
1172 public static function GetFileSRC($file, $uploadDir =
false, $external =
true)
1189 if ($uploadDir ===
false)
1191 $uploadDir = COption::GetOptionString(
'main',
'upload_dir',
'upload');
1194 $src =
'/' . $uploadDir .
'/' . $file[
'SUBDIR'] .
'/' . $file[
'FILE_NAME'];
1196 $src = str_replace(
'//',
'/', $src);
1198 if (defined(
"BX_IMG_SERVER"))
1200 $src = BX_IMG_SERVER . $src;
1209 if (!is_array($fileId) && intval($fileId) > 0)
1211 $file = static::GetByID($fileId)->Fetch();
1215 if (!isset($file[
'SRC']) || $uploadDir !==
false)
1217 $file[
'SRC'] = static::GetFileSRC($file, $uploadDir);
1228 if ($field ===
false)
1230 foreach ($source as $field => $sub_source)
1232 self::ConvertFilesToPost($sub_source, $target, $field);
1237 foreach ($source as $id => $sub_source)
1239 if (!array_key_exists($id, $target))
1243 if (is_array($sub_source))
1245 self::ConvertFilesToPost($sub_source, $target[$id], $field);
1249 $target[$id][$field] = $sub_source;
1259 public static function CopyFile($FILE_ID, $bRegister =
true, $newPath =
"")
1261 $z = static::GetByID($FILE_ID);
1262 if (
$zr =
$z->Fetch())
1265 if (COption::GetOptionInt(
"main",
"disk_space") > 0)
1268 if (!$quota->checkDiskQuota(
$zr))
1277 $bExternalStorage =
false;
1282 $bExternalStorage =
true;
1289 if (!$bExternalStorage)
1291 $strDirName =
$_SERVER[
"DOCUMENT_ROOT"] .
"/" . (COption::GetOptionString(
"main",
"upload_dir",
"upload"));
1292 $strDirName = rtrim(str_replace(
"//",
"/", $strDirName),
"/");
1294 $zr[
"SUBDIR"] = trim(
$zr[
"SUBDIR"],
"/");
1295 $zr[
"FILE_NAME"] = ltrim(
$zr[
"FILE_NAME"],
"/");
1297 $strOldFile = $strDirName .
"/" .
$zr[
"SUBDIR"] .
"/" .
$zr[
"FILE_NAME"];
1301 $strNewFile = $strDirName .
"/" . ltrim($newPath,
"/");
1305 $strNewFile = $strDirName .
"/" .
$zr[
"SUBDIR"] .
"/" . md5(uniqid(mt_rand())) . strrchr(
$zr[
"FILE_NAME"],
".");
1309 $zr[
"SUBDIR"] = mb_substr($strNewFile, mb_strlen($strDirName) + 1, -(mb_strlen(
bx_basename($strNewFile)) + 1));
1316 $bSaved = copy(
$io->GetPhysicalName($strOldFile),
$io->GetPhysicalName($strNewFile));
1323 $NEW_FILE_ID = static::DoInsert(
$zr);
1325 if (COption::GetOptionInt(
"main",
"disk_space") > 0)
1327 CDiskQuota::updateDiskQuota(
"file",
$zr[
"FILE_SIZE"],
"copy");
1330 static::CleanCache($NEW_FILE_ID);
1332 return $NEW_FILE_ID;
1336 if (!$bExternalStorage)
1338 return mb_substr($strNewFile, mb_strlen(rtrim(
$_SERVER[
"DOCUMENT_ROOT"],
"/")));
1359 DESCRIPTION = '" .
$DB->ForSql(
$desc, 255) .
"',
1360 TIMESTAMP_X = " .
$DB->GetNowFunction() .
"
1361 WHERE ID=" . intval(
$ID)
1363 static::CleanCache(
$ID);
1369 $external_id = trim($external_id);
1372 EXTERNAL_ID = " . ($external_id !=
"" ?
"'" .
$DB->ForSql($external_id, 50) .
"'" :
"null") .
",
1373 TIMESTAMP_X = " .
$DB->GetNowFunction() .
"
1374 WHERE ID=" . intval(
$ID)
1376 static::CleanCache(
$ID);
1379 public static function InputFile($strFieldName, $int_field_size, $strImageID, $strImageStorePath =
false, $int_max_file_size = 0, $strFileType =
"IMAGE", $field_file =
"class=typefile", $description_size = 0, $field_text =
"class=typeinput", $field_checkbox =
"", $bShowNotes =
true, $bShowFilePath =
true)
1382 if ($int_max_file_size != 0)
1384 $strReturn1 .=
"<input type=\"hidden\" name=\"MAX_FILE_SIZE\" value=\"" . $int_max_file_size .
"\" /> ";
1387 $strReturn1 .=
' <input name="' . $strFieldName .
'" ' . $field_file .
' size="' . $int_field_size .
'" type="file" />';
1388 $strReturn2 =
'<span class="bx-input-file-desc">';
1389 $strDescription =
"";
1390 $db_img_arr = static::GetFileArray($strImageID, $strImageStorePath);
1394 $strDescription = $db_img_arr[
"DESCRIPTION"];
1396 if ((
$p = mb_strpos($strFieldName,
"[")) > 0)
1398 $strDelName = mb_substr($strFieldName, 0,
$p) .
"_del" . mb_substr($strFieldName,
$p);
1402 $strDelName = $strFieldName .
"_del";
1409 $filePath = $db_img_arr[
"SRC"];
1413 $filePath = $db_img_arr[
'ORIGINAL_NAME'];
1416 if (
$io->FileExists(
$_SERVER[
"DOCUMENT_ROOT"] . $db_img_arr[
"SRC"]) || $db_img_arr[
"HANDLER_ID"])
1419 if (mb_strtoupper($strFileType) ==
"IMAGE")
1421 $intWidth = intval($db_img_arr[
"WIDTH"]);
1422 $intHeight = intval($db_img_arr[
"HEIGHT"]);
1423 if ($intWidth > 0 && $intHeight > 0)
1425 $strReturn2 .=
"<br> " .
GetMessage(
"FILE_WIDTH") .
": $intWidth";
1426 $strReturn2 .=
"<br> " .
GetMessage(
"FILE_HEIGHT") .
": $intHeight";
1429 $strReturn2 .=
"<br> " .
GetMessage(
"FILE_SIZE") .
": " . static::FormatSize($db_img_arr[
"FILE_SIZE"]);
1436 $strReturn2 .=
"<br><input " . $field_checkbox .
" type=\"checkbox\" name=\"" . $strDelName .
"\" value=\"Y\" id=\"" . $strDelName .
"\" /> <label for=\"" . $strDelName .
"\">" .
GetMessage(
"FILE_DELETE") .
"</label>";
1439 $strReturn2 .=
'</span>';
1441 return $strReturn1 . (
1442 $description_size > 0 ?
1443 '<br><input type="text" value="' .
htmlspecialcharsbx($strDescription) .
'" name="' . $strFieldName .
'_descr" ' . $field_text .
' size="' . $description_size .
'" title="' .
GetMessage(
"MAIN_FIELD_FILE_DESC") .
'" />'
1455 static $a = [
"b",
"Kb",
"Mb",
"Gb",
"Tb"];
1457 $size = (float)$size;
1459 while ($size >= 1024 && $pos < 4)
1469 return "jpg,bmp,jpeg,jpe,gif,png,webp";
1482 if (in_array($ext, explode(
",", static::GetImageExtensions())))
1493 public static function CheckImageFile($arFile, $iMaxSize = 0, $iMaxWidth = 0, $iMaxHeight = 0, $access_typies = [], $bForceMD5 =
false, $bSkipExt =
false)
1495 if (!isset($arFile[
"name"]) || $arFile[
"name"] ==
"")
1500 if (empty($arFile[
"tmp_name"]))
1502 return GetMessage(
"FILE_BAD_FILE_TYPE") .
".<br>";
1505 if (preg_match(
"#^(php://|phar://)#i", $arFile[
"tmp_name"]))
1507 return GetMessage(
"FILE_BAD_FILE_TYPE") .
".<br>";
1513 $flashEnabled =
false;
1514 if (!in_array($file_type, $access_typies))
1516 $file_type =
"IMAGE";
1519 if ($file_type ==
"FLASH")
1521 $flashEnabled =
true;
1522 static $flashMime = [
"application/x-shockwave-flash",
"application/vnd.adobe.flash.movie"];
1523 $res = static::CheckFile($arFile, $iMaxSize, $flashMime, static::GetFlashExtensions(), $bForceMD5, $bSkipExt);
1527 $res = static::CheckFile($arFile, $iMaxSize,
"image/", static::GetImageExtensions(), $bForceMD5, $bSkipExt);
1535 $imgInfo = (
new File\Image($arFile[
"tmp_name"]))->getInfo($flashEnabled);
1539 $intWIDTH = $imgInfo->getWidth();
1540 $intHEIGHT = $imgInfo->getHeight();
1544 return GetMessage(
"FILE_BAD_FILE_TYPE") .
".<br>";
1548 if ($iMaxWidth > 0 && ($intWIDTH > $iMaxWidth || $intWIDTH == 0) || $iMaxHeight > 0 && ($intHEIGHT > $iMaxHeight || $intHEIGHT == 0))
1550 return GetMessage(
"FILE_BAD_MAX_RESOLUTION") .
" (" . $iMaxWidth .
" * " . $iMaxHeight .
" " .
GetMessage(
"main_include_dots") .
").<br>";
1556 public static function CheckFile($arFile, $intMaxSize = 0, $mimeType =
false, $strExt =
false, $bForceMD5 =
false, $bSkipExt =
false)
1558 if ($arFile[
"name"] ==
"")
1564 $strFileName = self::transformName($arFile[
"name"], $bForceMD5, $bSkipExt);
1567 if ((
$error = self::validateFile($strFileName, $arFile)) <>
'')
1572 if ($intMaxSize > 0 && $arFile[
"size"] > $intMaxSize)
1574 return GetMessage(
"FILE_BAD_SIZE") .
" (" . static::FormatSize($intMaxSize) .
").";
1581 if ($strFileExt ==
'')
1588 if ($mimeType !==
false)
1590 if (!is_array($mimeType))
1592 $mimeType = [$mimeType];
1595 foreach ($mimeType as $strMimeType)
1597 if (str_starts_with($arFile[
"type"], $strMimeType))
1610 if ($strExt ===
false)
1615 $IsExtCorrect =
true;
1618 $IsExtCorrect =
false;
1619 $tok = strtok($strExt,
",");
1622 if (strtolower(trim($tok)) == strtolower($strFileExt))
1624 $IsExtCorrect =
true;
1636 return GetMessage(
"FILE_BAD_TYPE") .
" (" . strip_tags($strFileExt) .
")";
1639 public static function ShowFile($iFileID, $max_file_size = 0, $iMaxW = 0, $iMaxH = 0, $bPopup =
false, $sParams =
false, $sPopupTitle =
false, $iSizeWHTTP = 0, $iSizeHHTTP = 0)
1643 $arFile = static::GetFileArray($iFileID);
1646 $max_file_size = intval($max_file_size);
1647 if ($max_file_size <= 0)
1649 $max_file_size = 1000000000;
1652 $ct = $arFile[
"CONTENT_TYPE"];
1653 if ($arFile[
"FILE_SIZE"] <= $max_file_size && static::IsImage($arFile[
"SRC"], $ct))
1655 $strResult = static::ShowImage($arFile, $iMaxW, $iMaxH, $sParams,
"", $bPopup, $sPopupTitle, $iSizeWHTTP, $iSizeHHTTP);
1678function ImgShw(ID, width, height, alt)
1683 if(navigator.userAgent.toLowerCase().indexOf("opera") != -1)
1685 w = document.body.offsetWidth;
1686 h = document.body.offsetHeight;
1693 if(width > w-10 || height > h-28)
1696 top = Math.floor((h - height)/2-14);
1698 left = Math.floor((w - width)/2-5);
1699 width = Math.min(width, w-10);
1700 height = Math.min(height, h-28);
1701 var wnd = window.open("","","scrollbars="+scroll+",resizable=yes,width="+width+",height="+height+",left="+left+",top="+top);
1705 "function KeyPress(e)"+
1707 " if (!e) e = window.event;"+
1708 " if(e.keyCode == 27) "+
1712 "<title>"+(alt == ""? "' .
GetMessage(
"main_js_img_title") .
'":alt)+"</title></head>"+
1713 "<body topmargin=\"0\" leftmargin=\"0\" marginwidth=\"0\" marginheight=\"0\" onKeyDown=\"KeyPress(arguments[0])\">"+
1714 "<img src=\""+ID+"\" border=\"0\" alt=\""+alt+"\" />"+
1717 wnd.document.close();
1726 public static function _GetImgParams($strImage, $iSizeWHTTP = 0, $iSizeHHTTP = 0)
1732 if ($strImage ==
'')
1738 if (intval($strImage) > 0)
1740 $db_img_arr = static::GetFileArray($strImage);
1743 $strImage = $db_img_arr[
"SRC"];
1744 $intWidth = intval($db_img_arr[
"WIDTH"]);
1745 $intHeight = intval($db_img_arr[
"HEIGHT"]);
1746 $strAlt = $db_img_arr[
"DESCRIPTION"];
1755 if (!preg_match(
"#^https?://#", $strImage))
1757 $imageInfo = (
new File\Image(
$io->GetPhysicalName(
$_SERVER[
"DOCUMENT_ROOT"] . $strImage)))->getInfo();
1760 $intWidth = $imageInfo->getWidth();
1761 $intHeight = $imageInfo->getHeight();
1775 $intWidth = intval($iSizeWHTTP);
1776 $intHeight = intval($iSizeHHTTP);
1782 "WIDTH" => $intWidth,
1783 "HEIGHT" => $intHeight,
1796 $img_id = intval($img_id);
1799 $res = static::_GetImgParams($img_id);
1800 return is_array(
$res) ?
$res[
"SRC"] :
null;
1805 public static function ShowImage($strImage, $iMaxW = 0, $iMaxH = 0, $sParams =
null, $strImageUrl =
"", $bPopup =
false, $sPopupTitle =
false, $iSizeWHTTP = 0, $iSizeHHTTP = 0, $strImageUrlTemplate =
"")
1807 if (is_array($strImage))
1809 $arImgParams = $strImage;
1810 $iImageID = isset($arImgParams[
'ID']) ? (int)$arImgParams[
'ID'] : 0;
1814 $arImgParams = static::_GetImgParams($strImage, $iSizeWHTTP, $iSizeHHTTP);
1815 $iImageID = (int)$strImage;
1823 $iMaxW = (int)$iMaxW;
1824 $iMaxH = (int)$iMaxH;
1825 $intWidth = (int)$arImgParams[
'WIDTH'];
1826 $intHeight = (int)$arImgParams[
'HEIGHT'];
1830 && ($intWidth > $iMaxW || $intHeight > $iMaxH)
1833 $coeff = ($intWidth / $iMaxW > $intHeight / $iMaxH ? $intWidth / $iMaxW : $intHeight / $iMaxH);
1834 $iHeight = (int)
roundEx($intHeight / $coeff);
1835 $iWidth = (int)
roundEx($intWidth / $coeff);
1840 $iHeight = $intHeight;
1841 $iWidth = $intWidth;
1844 $strImageUrlTemplate = strval($strImageUrlTemplate);
1845 if ($strImageUrlTemplate ===
'' || $iImageID <= 0)
1847 $strImage = $arImgParams[
'SRC'];
1851 $strImage = CComponentEngine::MakePathFromTemplate($strImageUrlTemplate, [
'file_id' => $iImageID]);
1860 classid="clsid:D27CDB6E-AE6D-11CF-96B8-444553540000"
1861 codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0"
1863 WIDTH="' . $iWidth .
'"
1864 HEIGHT="' . $iHeight .
'"
1867 <PARAM NAME="quality" VALUE="high" />
1868 <PARAM NAME="bgcolor" VALUE="#FFFFFF" />
1873 WIDTH="' . $iWidth .
'"
1874 HEIGHT="' . $iHeight .
'"
1877 TYPE="application/x-shockwave-flash"
1878 PLUGINSPAGE="http://www.macromedia.com/go/getflashplayer"
1885 $strAlt = $arImgParams[
'ALT'] ?? ($arImgParams[
'DESCRIPTION'] ??
'');
1887 if ($sParams ===
null || $sParams ===
false)
1891 elseif (!preg_match(
'/(^|\\s)alt\\s*=\\s*(["\']?)(.*?)(\\2)/is', $sParams))
1896 if ($coeff === 1 || !$bPopup)
1898 $strReturn =
'<img src="' .
htmlspecialcharsbx($strImage) .
'" ' . $sParams .
' width="' . $iWidth .
'" height="' . $iHeight .
'" />';
1902 if ($sPopupTitle ===
false)
1907 if ($strImageUrl <>
'')
1910 '<a href="' . $strImageUrl .
'" title="' .
htmlspecialcharsEx($sPopupTitle) .
'" target="_blank">' .
1916 static::OutputJSImgShw();
1919 '<a title="' . $sPopupTitle .
'" ' .
1921 'href="' . htmlspecialcharsbx($strImage) . '" ' .
1924 '<img src="' . htmlspecialcharsbx($strImage) . '" ' . $sParams . ' width="' . $iWidth . '" height="' . $iHeight . '" />' .
1930 return $bPopup ? $strReturn : print_url($strImageUrl, $strReturn);
1933 public static function Show2Images($strImage1, $strImage2, $iMaxW = 0, $iMaxH = 0, $sParams = false, $sPopupTitle = false, $iSizeWHTTP = 0, $iSizeHHTTP = 0)
1935 if (!($arImgParams = static::_GetImgParams($strImage1, $iSizeWHTTP, $iSizeHHTTP)))
1940 $strImage1 = Uri::urnEncode($arImgParams["SRC
"]);
1942 $intWidth = $arImgParams["WIDTH
"];
1943 $intHeight = $arImgParams["HEIGHT
"];
1944 $strAlt = $arImgParams["ALT
"];
1948 $sParams = 'border="0
" alt="' . htmlspecialcharsEx($strAlt) . '"';
1950 elseif (!preg_match("/(^|\\s)alt\\s*=\\s*([\
"']?)(.*?)(\\2)/is", $sParams))
1956 $iMaxW > 0 && $iMaxH > 0
1957 && ($intWidth > $iMaxW || $intHeight > $iMaxH)
1960 $coeff = ($intWidth / $iMaxW > $intHeight / $iMaxH ? $intWidth / $iMaxW : $intHeight / $iMaxH);
1961 $iHeight = intval(
roundEx($intHeight / $coeff));
1962 $iWidth = intval(
roundEx($intWidth / $coeff));
1966 $iHeight = $intHeight;
1967 $iWidth = $intWidth;
1970 if ($arImgParams = static::_GetImgParams($strImage2, $iSizeWHTTP, $iSizeHHTTP))
1972 if ($sPopupTitle ===
false)
1977 $strImage2 = Uri::urnEncode($arImgParams[
"SRC"]);
1978 $intWidth2 = $arImgParams[
"WIDTH"];
1979 $intHeight2 = $arImgParams[
"HEIGHT"];
1980 $strAlt2 = $arImgParams[
"ALT"];
1982 static::OutputJSImgShw();
1986 "<img src=\"" . $strImage1 .
"\" " . $sParams .
" width=" . $iWidth .
" height=" . $iHeight .
" /></a>";
1990 $strReturn =
"<img src=\"" . $strImage1 .
"\" " . $sParams .
" width=" . $iWidth .
" height=" . $iHeight .
" />";
2010 if (intval(
$path) > 0)
2020 $bExternalStorage =
false;
2021 foreach (
GetModuleEvents(
"main",
"OnMakeFileArray",
true) as $arEvent)
2025 $bExternalStorage =
true;
2030 if (!$bExternalStorage)
2032 $arFile[
"name"] = (
$ar[
'ORIGINAL_NAME'] <>
'' ?
$ar[
'ORIGINAL_NAME'] :
$ar[
'FILE_NAME']);
2033 $arFile[
"size"] =
$ar[
'FILE_SIZE'];
2034 $arFile[
"type"] =
$ar[
'CONTENT_TYPE'];
2035 $arFile[
"description"] =
$ar[
'DESCRIPTION'];
2036 $arFile[
"tmp_name"] =
$io->GetPhysicalName(preg_replace(
"#[\\\\/]+#",
"/",
$_SERVER[
'DOCUMENT_ROOT'] .
'/' . (COption::GetOptionString(
'main',
'upload_dir',
'upload')) .
'/' .
$ar[
'SUBDIR'] .
'/' .
$ar[
'FILE_NAME']));
2038 if (!isset($arFile[
"external_id"]))
2040 $arFile[
"external_id"] = $external_id !=
"" ? $external_id :
$ar[
"EXTERNAL_ID"];
2046 $path = preg_replace(
"#(?<!:)[\\\\/]+#",
"/",
$path);
2053 if (preg_match(
"#^(php://|phar://)#i",
$path) && !preg_match(
"#^php://input$#i",
$path))
2058 if (preg_match(
"#^https?://#i",
$path))
2061 $bExternalStorage =
false;
2062 foreach (
GetModuleEvents(
"main",
"OnMakeFileArray",
true) as $arEvent)
2066 $bExternalStorage =
true;
2071 if (!$bExternalStorage)
2074 $http->setPrivateIp(
false);
2075 $temp_path = static::GetTempName(
'',
'tmp.' . md5(mt_rand()));
2076 if ($http->download(
$path, $temp_path))
2078 $arFile = static::MakeFileArray($temp_path);
2081 $urlComponents = parse_url(
$path);
2082 if ($urlComponents && $urlComponents[
"path"] <>
'')
2084 $arFile[
"name"] =
$io->GetLogicalName(
bx_basename($urlComponents[
"path"]));
2095 $arFile = static::MakeFileArray($temp_path);
2098 elseif (preg_match(
"#^(ftps?://|php://input)#i",
$path))
2100 if ($fp = fopen(
$path,
"rb"))
2110 $temp_path = static::GetTempName(
'',
'tmp.' . md5(mt_rand()));
2113 $arFile = static::MakeFileArray($temp_path);
2126 if (!file_exists(
$path))
2144 $arFile[
"size"] = filesize(
$path);
2145 $arFile[
"tmp_name"] =
$path;
2146 $arFile[
"type"] = $mimetype;
2148 if ($arFile[
"type"] ==
'')
2150 $arFile[
"type"] = static::GetContentType(
$path,
true);
2154 if ($arFile[
"type"] ==
'')
2156 $arFile[
"type"] =
"unknown";
2159 if (!isset($arFile[
"external_id"]) && ($external_id !=
""))
2161 $arFile[
"external_id"] = $external_id;
2167 public static function GetTempName($dir_name =
false, $file_name =
'')
2170 if (($pos = mb_strpos($file_name,
"?")) !==
false)
2172 $file_name = mb_substr($file_name, 0, $pos);
2174 return CTempFile::GetFileName($file_name);
2181 if ($old_subdir != $new_subdir)
2185 SUBDIR = REPLACE(SUBDIR,'" .
$DB->ForSQL($old_subdir) .
"','" .
$DB->ForSQL($new_subdir) .
"'),
2186 TIMESTAMP_X = " .
$DB->GetNowFunction() .
"
2190 if (
$DB->Query($strSql))
2192 $from =
"/" . COption::GetOptionString(
"main",
"upload_dir",
"upload") .
"/" . $old_subdir;
2193 $to =
"/" . COption::GetOptionString(
"main",
"upload_dir",
"upload") .
"/" . $new_subdir;
2198 $cache->cleanDir(self::CACHE_DIR);
2208 $destinationFile = CTempFile::GetFileName(basename($arFile[
"tmp_name"]));
2209 $sourceFile =
$io->GetLogicalName($arFile[
"tmp_name"]);
2213 if (static::ResizeImageFile($sourceFile, $destinationFile, $arSize, $resizeType))
2215 $arFile[
"tmp_name"] =
$io->GetPhysicalName($destinationFile);
2217 $imageInfo = (
new File\Image($arFile[
"tmp_name"]))->getInfo();
2220 $arFile[
"type"] = $imageInfo->getMime();
2222 $arFile[
"size"] = filesize($arFile[
"tmp_name"]);
2232 $temp_dir = CTempFile::GetAbsoluteRoot() .
"/";
2233 if (mb_strpos($arFile[
"tmp_name"], $temp_dir) === 0)
2235 if (file_exists($arFile[
"tmp_name"]))
2237 unlink($arFile[
"tmp_name"]);
2244 if (!is_array($file) && intval($file) > 0)
2246 $file = static::GetFileArray($file);
2249 if (!is_array($file) || !array_key_exists(
"FILE_NAME", $file) || $file[
"FILE_NAME"] ==
'')
2259 if (!is_array($arSize))
2263 if (!array_key_exists(
"width", $arSize) || intval($arSize[
"width"]) <= 0)
2265 $arSize[
"width"] = 0;
2267 if (!array_key_exists(
"height", $arSize) || intval($arSize[
"height"]) <= 0)
2269 $arSize[
"height"] = 0;
2271 $arSize[
"width"] = intval($arSize[
"width"]);
2272 $arSize[
"height"] = intval($arSize[
"height"]);
2274 $uploadDirName = COption::GetOptionString(
"main",
"upload_dir",
"upload");
2276 $imageFile =
"/" . $uploadDirName .
"/" . $file[
"SUBDIR"] .
"/" . $file[
"FILE_NAME"];
2277 $arImageSize =
false;
2278 $bFilters = is_array($arFilters) && !empty($arFilters);
2281 ($arSize[
"width"] <= 0 || $arSize[
"width"] >= $file[
"WIDTH"])
2282 && ($arSize[
"height"] <= 0 || $arSize[
"height"] >= $file[
"HEIGHT"])
2288 $arSize[
"width"] = $file[
"WIDTH"];
2289 $arSize[
"height"] = $file[
"HEIGHT"];
2294 if (isset($file[
"SRC"]))
2301 trigger_error(
"Parameter \$file for CFile::ResizeImageGet does not have SRC element. You'd better pass an b_file.ID as a value for the \$file parameter.", E_USER_WARNING);
2305 "src" => $file[
"SRC"],
2306 "width" => intval($file[
"WIDTH"]),
2307 "height" => intval($file[
"HEIGHT"]),
2308 "size" => $file[
"FILE_SIZE"],
2315 $cacheImageFile =
"/" . $uploadDirName .
"/resize_cache/" . $file[
"SUBDIR"] .
"/" . $arSize[
"width"] .
"_" . $arSize[
"height"] .
"_" . $resizeType . (is_array($arFilters) ? md5(serialize($arFilters)) :
"") .
"/" . $file[
"FILE_NAME"];
2316 $cacheImageFileCheck = $cacheImageFile;
2319 $cache_id = $cacheImageFileCheck;
2320 if (isset($cache[$cache_id]))
2322 return $cache[$cache_id];
2324 elseif (!file_exists(
$io->GetPhysicalName(
$_SERVER[
"DOCUMENT_ROOT"] . $cacheImageFileCheck)))
2326 if (!is_array($arFilters))
2329 [
"name" =>
"sharpen",
"precision" => 15],
2333 $sourceImageFile =
$_SERVER[
"DOCUMENT_ROOT"] . $imageFile;
2334 $cacheImageFileTmp =
$_SERVER[
"DOCUMENT_ROOT"] . $cacheImageFile;
2335 $bNeedResize =
true;
2336 $callbackData =
null;
2338 foreach (
GetModuleEvents(
"main",
"OnBeforeResizeImage",
true) as $arEvent)
2342 [$arSize, $resizeType, [],
false, $arFilters, $bImmediate],
2346 &$cacheImageFileTmp,
2353 if ($bNeedResize && static::ResizeImageFile($sourceImageFile, $cacheImageFileTmp, $arSize, $resizeType, [], $jpgQuality, $arFilters))
2355 $cacheImageFile = mb_substr($cacheImageFileTmp, mb_strlen(
$_SERVER[
"DOCUMENT_ROOT"]));
2358 if (COption::GetOptionInt(
"main",
"disk_space") > 0)
2360 CDiskQuota::updateDiskQuota(
"file", filesize(
$io->GetPhysicalName($cacheImageFileTmp)),
"insert");
2366 $cacheImageFile = $imageFile;
2369 foreach (
GetModuleEvents(
"main",
"OnAfterResizeImage",
true) as $arEvent)
2373 [$arSize, $resizeType, [],
false, $arFilters],
2376 &$cacheImageFileTmp,
2384 $cacheImageFileCheck = $cacheImageFile;
2386 elseif (defined(
"BX_FILE_USE_FLOCK"))
2388 $hLock =
$io->OpenFile(
$_SERVER[
"DOCUMENT_ROOT"] . $imageFile,
"r+");
2391 flock($hLock, LOCK_EX);
2392 flock($hLock, LOCK_UN);
2397 if ($bInitSizes && !is_array($arImageSize))
2399 $imageInfo = (
new File\Image(
$_SERVER[
"DOCUMENT_ROOT"] . $cacheImageFileCheck))->getInfo();
2402 $arImageSize[0] = $imageInfo->getWidth();
2403 $arImageSize[1] = $imageInfo->getHeight();
2407 $arImageSize = [0, 0];
2410 $f =
$io->GetFile(
$_SERVER[
"DOCUMENT_ROOT"] . $cacheImageFileCheck);
2411 $arImageSize[2] =
$f->GetFileSize();
2414 if (!is_array($arImageSize))
2416 $arImageSize = [0, 0, 0];
2419 $cache[$cache_id] = [
2420 "src" => $cacheImageFileCheck,
2421 "width" => intval($arImageSize[0]),
2422 "height" => intval($arImageSize[1]),
2423 "size" => $arImageSize[2],
2425 return $cache[$cache_id];
2428 public static function ResizeImageDelete($arImage)
2431 $upload_dir = COption::GetOptionString(
"main",
"upload_dir",
"upload");
2432 $disk_space = COption::GetOptionInt(
"main",
"disk_space");
2435 $d =
$io->GetDirectory(
$_SERVER[
"DOCUMENT_ROOT"] .
"/" . $upload_dir .
"/resize_cache/" . $arImage[
"SUBDIR"]);
2438 foreach ($d->GetChildren() as $dir_entry)
2440 if ($dir_entry->IsDirectory())
2442 $f =
$io->GetFile($dir_entry->GetPathWithName() .
"/" . $arImage[
"FILE_NAME"]);
2445 if ($disk_space > 0)
2447 $fileSizeTmp =
$f->GetFileSize();
2448 if (
$io->Delete(
$f->GetPathWithName()))
2450 $delete_size += $fileSizeTmp;
2455 $io->Delete(
$f->GetPathWithName());
2461 @rmdir(
$io->GetPhysicalName($dir_entry->GetPathWithName()));
2463 catch (\ErrorException)
2472 @rmdir(
$io->GetPhysicalName($d->GetPathWithName()));
2474 catch (\ErrorException)
2479 return $delete_size;
2502 public static function ScaleImage($sourceImageWidth, $sourceImageHeight, $arSize, $resizeType, &$bNeedCreatePicture, &$arSourceSize, &$arDestinationSize)
2504 $source =
new Rectangle($sourceImageWidth, $sourceImageHeight);
2505 $destination =
new Rectangle($arSize[
"width"], $arSize[
"height"]);
2507 $bNeedCreatePicture = $source->resize($destination, $resizeType);
2510 "x" => $source->getX(),
2511 "y" => $source->getY(),
2512 "width" => $source->getWidth(),
2513 "height" => $source->getHeight(),
2515 $arDestinationSize = [
2516 "x" => $destination->getX(),
2517 "y" => $destination->getY(),
2518 "width" => $destination->getWidth(),
2519 "height" => $destination->getHeight(),
2536 if (!
$io->FileExists($sourceFile))
2546 if (!is_array($arSize))
2550 if (!array_key_exists(
"width", $arSize) || intval($arSize[
"width"]) <= 0)
2552 $arSize[
"width"] = 0;
2554 if (!array_key_exists(
"height", $arSize) || intval($arSize[
"height"]) <= 0)
2556 $arSize[
"height"] = 0;
2558 $arSize[
"width"] = intval($arSize[
"width"]);
2559 $arSize[
"height"] = intval($arSize[
"height"]);
2561 $sourceImage =
new File\Image(
$io->GetPhysicalName($sourceFile));
2562 $sourceInfo = $sourceImage->getInfo();
2564 if ($sourceInfo ===
null || !$sourceInfo->isSupported())
2569 $fileType = $sourceInfo->getFormat();
2572 if ($fileType ==
File\Image::FORMAT_JPEG)
2574 $exifData = $sourceImage->getExifData();
2575 if (isset($exifData[
'Orientation']))
2577 $orientation = $exifData[
'Orientation'];
2579 if ($orientation >= 5 && $orientation <= 8)
2581 $sourceInfo->swapSides();
2588 $sourceRectangle = $sourceInfo->toRectangle();
2589 $destinationRectangle =
new Rectangle($arSize[
"width"], $arSize[
"height"]);
2591 $needResize = $sourceRectangle->resize($destinationRectangle, $resizeType);
2593 $hLock =
$io->OpenFile($sourceFile,
"r+");
2594 $useLock = defined(
"BX_FILE_USE_FLOCK");
2600 flock($hLock, LOCK_EX);
2602 if (
$io->FileExists($destinationFile))
2604 $destinationInfo = (
new File\Image(
$io->GetPhysicalName($destinationFile)))->getInfo();
2605 if ($destinationInfo)
2607 if ($destinationInfo->getWidth() == $destinationRectangle->getWidth() && $destinationInfo->getHeight() == $destinationRectangle->getHeight())
2618 if (
$io->Copy($sourceFile, $destinationFile))
2620 $destinationImage =
new File\Image(
$io->GetPhysicalName($destinationFile));
2622 if ($destinationImage->load())
2624 if ($orientation > 1)
2626 $destinationImage->autoRotate($orientation);
2633 $sourceRectangle = $destinationImage->getDimensions();
2634 $destinationRectangle =
new Rectangle($arSize[
"width"], $arSize[
"height"]);
2636 $sourceRectangle->resize($destinationRectangle, $resizeType);
2638 $modified = $destinationImage->resize($sourceRectangle, $destinationRectangle);
2641 if (!is_array($arFilters))
2646 if (is_array($arWaterMark))
2648 $arWaterMark[
"name"] =
"watermark";
2649 $arFilters[] = $arWaterMark;
2661 $modified |= $destinationImage->drawWatermark($watermark);
2667 if ($quality ===
false)
2669 $quality = COption::GetOptionString(
'main',
'image_resize_quality');
2672 $io->Delete($destinationFile);
2674 if ($fileType ==
File\Image::FORMAT_BMP)
2676 $destinationImage->saveAs(
$io->GetPhysicalName($destinationFile), $quality,
File\Image::FORMAT_JPEG);
2680 $destinationImage->save($quality);
2683 $destinationImage->clear();
2695 flock($hLock, LOCK_UN);
2721 $engine->setResource($picture);
2726 return static::WaterMark($picture,
$arFilter);
2741 $engine->setResource($picture);
2753 if ($orientation <= 1)
2758 if (!is_resource($sourceImage))
2764 if ($image->autoRotate($orientation))
2766 $quality = COption::GetOptionString(
'main',
'image_resize_quality');
2767 $image->save($quality);
2778 $engine->setResource($sourceImage);
2782 $image->autoRotate($orientation);
2784 return $engine->getResource();
2792 public static function ViewByUser($arFile,
$arOptions = [])
2794 $previewManager =
new Viewer\PreviewManager();
2795 if ($previewManager->isInternalRequest($arFile,
$arOptions))
2797 $previewManager->processViewByUserRequest($arFile,
$arOptions);
2805 $attachment_name =
"";
2807 $specialchars =
false;
2808 $force_download =
false;
2809 $cache_time = 10800;
2810 $fromClouds =
false;
2826 $force_download =
$arOptions[
"force_download"];
2830 $cache_time = intval(
$arOptions[
"cache_time"]);
2834 $attachment_name =
$arOptions[
"attachment_name"];
2838 $fastDownload = (bool)
$arOptions[
"fast_download"];
2842 if ($cache_time < 0)
2847 if (is_array($arFile))
2849 if (isset($arFile[
"SRC"]))
2853 elseif (isset($arFile[
"tmp_name"]))
2855 if (mb_strpos($arFile[
'tmp_name'],
$_SERVER[
'DOCUMENT_ROOT']) === 0)
2857 $filename =
'/' . ltrim(mb_substr($arFile[
'tmp_name'], mb_strlen(
$_SERVER[
'DOCUMENT_ROOT'])),
'/');
2859 elseif (defined(
'BX_TEMPORARY_FILES_DIRECTORY') && mb_strpos($arFile[
'tmp_name'], BX_TEMPORARY_FILES_DIRECTORY) === 0)
2863 $filename = $tmpPath . ltrim(mb_substr($arFile[
'tmp_name'], mb_strlen(BX_TEMPORARY_FILES_DIRECTORY)),
'/');
2868 $filename = static::GetFileSRC($arFile);
2871 elseif (($arFile = static::GetFileArray($arFile)))
2881 if ($content_type ==
'' && isset($arFile[
"CONTENT_TYPE"]))
2883 $content_type = $arFile[
"CONTENT_TYPE"];
2887 if ($content_type ==
'' || $content_type ==
"image/bmp")
2889 if (isset($arFile[
"tmp_name"]))
2891 $content_type = static::GetContentType($arFile[
"tmp_name"],
true);
2899 if (isset($arFile[
"ORIGINAL_NAME"]) && $arFile[
"ORIGINAL_NAME"] !=
'')
2901 $name = $arFile[
"ORIGINAL_NAME"];
2903 elseif ($arFile[
"name"] <>
'')
2905 $name = $arFile[
"name"];
2909 $name = $arFile[
"FILE_NAME"];
2911 if (isset($arFile[
"EXTENSION_SUFFIX"]) && $arFile[
"EXTENSION_SUFFIX"] <>
'')
2913 $name = mb_substr(
$name, 0, -mb_strlen($arFile[
"EXTENSION_SUFFIX"]));
2916 $name = str_replace([
"\n",
"\r"],
'',
$name);
2918 if ($attachment_name)
2920 $attachment_name = str_replace([
"\n",
"\r"],
'', $attachment_name);
2924 $attachment_name =
$name;
2927 if (!$force_download)
2929 if (!static::IsImage(
$name, $content_type) || $arFile[
"HEIGHT"] <= 0 || $arFile[
"WIDTH"] <= 0)
2932 $force_download =
true;
2936 $content_type = Web\MimeType::normalize($content_type);
2938 if ($force_download)
2940 $specialchars =
false;
2946 if ((str_starts_with(
$filename,
'/')) && !$fromTemp)
2950 elseif (isset($arFile[
'tmp_name']))
2952 $file =
new IO\File($arFile[
'tmp_name']);
2955 if ((str_starts_with(
$filename,
'/')) && ($file instanceof IO\File))
2961 catch (IO\IoException)
2970 $src =
new Web\HttpClient();
2972 elseif (intval($arFile[
'HANDLER_ID']) > 0)
2982 $filesize = (isset($arFile[
"FILE_SIZE"]) && (int)$arFile[
"FILE_SIZE"] > 0 ? (
int)$arFile[
"FILE_SIZE"] : (int)($arFile[
"size"] ?? 0));
2983 $size = $filesize - 1;
2984 $p = strpos(
$_SERVER[
"HTTP_RANGE"] ??
'',
"=");
2991 $cur_pos = (float)substr(
$bytes, 0,
$p);
2992 $size = (float)substr(
$bytes,
$p + 1);
2995 $size = $filesize - 1;
2997 if ($cur_pos > $size)
3000 $size = $filesize - 1;
3005 if ($file instanceof IO\File)
3007 $filetime = $file->getModificationTime();
3009 elseif (isset($arFile[
"tmp_name"]) && $arFile[
"tmp_name"] <>
'')
3011 $tmpFile =
new IO\File($arFile[
"tmp_name"]);
3012 $filetime = $tmpFile->getModificationTime();
3019 $response = \Bitrix\Main\Context::getCurrent()->getResponse();
3021 if (
$_SERVER[
"REQUEST_METHOD"] ==
"HEAD")
3024 ->addHeader(
"Accept-Ranges",
"bytes")
3025 ->addHeader(
"Content-Type", $content_type)
3026 ->addHeader(
"Content-Length", ($size - $cur_pos + 1))
3031 $response->addHeader(
"Last-Modified", date(
"r", $filetime));
3037 if ($cache_time > 0)
3040 $ETag = md5(
$filename . $filesize . $filetime);
3041 if (array_key_exists(
"HTTP_IF_NONE_MATCH",
$_SERVER) && (
$_SERVER[
'HTTP_IF_NONE_MATCH'] === $ETag))
3043 $response->setStatus(
"304 Not Modified");
3044 $response->addHeader(
"Cache-Control",
"private, max-age=" . $cache_time .
", pre-check=" . $cache_time);
3055 $lastModified = gmdate(
'D, d M Y H:i:s', $filetime) .
' GMT';
3056 if (array_key_exists(
"HTTP_IF_MODIFIED_SINCE",
$_SERVER) && (
$_SERVER[
'HTTP_IF_MODIFIED_SINCE'] === $lastModified))
3058 $response->setStatus(
"304 Not Modified");
3059 $response->addHeader(
"Cache-Control",
"private, max-age=" . $cache_time .
", pre-check=" . $cache_time);
3067 $utfName = Uri::urnEncode($attachment_name);
3070 "safe_chars" =>
".",
3071 "replace_space" =>
'-',
3072 "change_case" =>
false,
3075 if ($force_download)
3079 if (ini_get(
'zlib.output_compression'))
3081 ini_set(
'zlib.output_compression',
'Off');
3087 $response->setStatus(
"206 Partial Content");
3094 $response->addHeader(
"Content-Type", $content_type)
3095 ->addHeader(
"Content-Disposition",
"attachment; filename=\"" . $translitName .
"\"; filename*=utf-8''" . $utfName)
3096 ->addHeader(
"Content-Transfer-Encoding",
"binary")
3097 ->addHeader(
"Content-Length", ($size - $cur_pos + 1))
3100 if (is_resource($src))
3102 $response->addHeader(
"Accept-Ranges",
"bytes");
3103 $response->addHeader(
"Content-Range",
"bytes " . $cur_pos .
"-" . $size .
"/" . $filesize);
3108 $response->addHeader(
"Content-Type", $content_type);
3109 $response->addHeader(
"Content-Disposition",
"inline; filename=\"" . $translitName .
"\"; filename*=utf-8''" . $utfName);
3112 if ($cache_time > 0)
3114 $response->addHeader(
"Cache-Control",
"private, max-age=" . $cache_time .
", pre-check=" . $cache_time);
3117 $response->addHeader(
'Last-Modified', $lastModified);
3122 $response->addHeader(
"Cache-Control",
"no-cache, must-revalidate, post-check=0, pre-check=0");
3126 $response->addHeader(
"Pragma",
"public");
3128 $filenameEncoded = Uri::urnEncode(
$filename);
3134 $filenameDisableProto = preg_replace(
'~^(https?)(\://)~i',
'\\1.', $filenameEncoded);
3136 $response->addHeader(
'X-Accel-Redirect', rawurlencode($cloudUploadPath . $filenameDisableProto));
3140 $response->addHeader(
'X-Accel-Redirect', $filenameEncoded);
3147 session_write_close();
3153 echo
"<",
"pre",
">";
3154 if (is_resource($src))
3167 echo
"<",
"/pre",
">";
3171 if (is_resource($src))
3174 $file->seek($cur_pos);
3175 while (!feof($src) && ($cur_pos <= $size))
3178 if ($cur_pos + $bufsize > $size)
3180 $bufsize = $size - $cur_pos + 1;
3182 $cur_pos += $bufsize;
3183 echo fread($src, $bufsize);
3189 $fp = fopen(
"php://output",
"wb");
3191 $src->setOutputStream($fp);
3192 $src->get($filenameEncoded);
3202 private static function terminate(): void
3205 if (function_exists(
"fastcgi_finish_request"))
3208 fastcgi_finish_request();
3211 Main\Application::getInstance()->terminate();
3226 if ($Params[
'type'] ==
'text')
3228 $result = static::WatermarkText($obj, $Params);
3232 $result = static::WatermarkImage($obj, $Params);
3254 return $engine->drawTextWatermark($watermark);
3277 return $engine->drawImageWatermark($watermark);
3289 if (!$image->load())
3294 $quality = COption::GetOptionString(
'main',
'image_resize_quality');
3296 $result = ($image->rotate($angle) && $image->save($quality));
3314 return $image->getResource();
3327 return (
new File\
Image($src))->getExifData();
3349 $pathX =
$io->GetPhysicalName(
$path);
3353 if (function_exists(
"mime_content_type"))
3355 $type = mime_content_type($pathX);
3358 if (
$type ==
"" && function_exists(
"image_type_to_mime_type"))
3384 if (!$bPhysicalName)
3392 if ((
$info = $image->getInfo($flashEnabled)) !==
null)
3395 0 =>
$info->getWidth(),
3396 1 =>
$info->getHeight(),
3397 2 =>
$info->getFormat(),
3398 3 =>
$info->getAttributes(),
3399 "mime" =>
$info->getMime(),
3409 $res =
$DB->Query(
"select distinct h1.FILE_ID
3410 FROM b_file_hash h1, b_file_hash h2
3411 WHERE h1.FILE_ID > h2.FILE_ID
3412 AND h1.FILE_SIZE = h2.FILE_SIZE
3413 AND h1.FILE_HASH = h2.FILE_HASH
3420 $delete[] =
$ar[
'FILE_ID'];
3423 if (!empty($delete))
3425 $DB->Query(
"DELETE FROM b_file_hash WHERE FILE_ID IN (" . implode(
',', $delete) .
")");
3427 return __METHOD__ .
'();';
static getConnection($name="")
static createSharpen($precision)
static createFromArray($params)
static markDeleted($originalId)
static convertPhysicalToLogical($path)
static getList(array $parameters=array())
static update($primary, array $data)
static getString($length, $caseSensitive=false)
static normalize($contentType)
static getByFileExtension($extension)
static urnEncode($str, $charset='UTF-8')
static GetOptionString($module_id, $name, $def="", $site=false, $bExactSite=false)
static GetFromDb($fileId, $realId)
static checkForDb($arFields, $field)
static ImageCreateFromBMP($filename)
static CloneFile(int $fileId)
static GetList($arOrder=[], $arFilter=[])
static ShowImage($strImage, $iMaxW=0, $iMaxH=0, $sParams=null, $strImageUrl="", $bPopup=false, $sPopupTitle=false, $iSizeWHTTP=0, $iSizeHHTTP=0, $strImageUrlTemplate="")
static processVersions($ID)
static UpdateDesc($ID, $desc)
static GetTempName($dir_name=false, $file_name='')
static ResizeImageGet($file, $arSize, $resizeType=BX_RESIZE_IMAGE_PROPORTIONAL, $bInitSizes=false, $arFilters=false, $bImmediate=false, $jpgQuality=false)
static Watermark($obj, $Params)
static FindDuplicate($size, $hash, $handlerId=null)
static DeleteDuplicates($originalId, array $duplicteIds)
static CheckFile($arFile, $intMaxSize=0, $mimeType=false, $strExt=false, $bForceMD5=false, $bSkipExt=false)
static AddVersion($originalId, $versionId, $metaData=[])
static AddDuplicate($originalId, $duplicateId=null, bool $resolvePossibleOriginCycle=true)
static ImageHandleOrientation($orientation, $sourceImage)
static ShowFile($iFileID, $max_file_size=0, $iMaxW=0, $iMaxH=0, $bPopup=false, $sParams=false, $sPopupTitle=false, $iSizeWHTTP=0, $iSizeHHTTP=0)
static WatermarkImage($obj, $Params=[])
static DisableJSFunction($b=true)
static ChangeSubDir($module_id, $old_subdir, $new_subdir)
static SaveFile($arFile, $strSavePath, $forceRandom=false, $skipExtension=false, $dirAdd='')
static ResizeImageFile($sourceFile, $destinationFile, $arSize, $resizeType=BX_RESIZE_IMAGE_PROPORTIONAL, $arWaterMark=[], $quality=false, $arFilters=false)
static GetFromCache($fileId, $realId=false)
static ExtractImageExif($src)
static GetImageExtensions()
static GetFileArray($fileId, $uploadDir=false)
static processDuplicates($ID)
static _GetImgParams($strImage, $iSizeWHTTP=0, $iSizeHHTTP=0)
static CopyFile($FILE_ID, $bRegister=true, $newPath="")
static GetFileSRC($file, $uploadDir=false, $external=true)
static CheckImageFile($arFile, $iMaxSize=0, $iMaxWidth=0, $iMaxHeight=0, $access_typies=[], $bForceMD5=false, $bSkipExt=false)
static InputFile($strFieldName, $int_field_size, $strImageID, $strImageStorePath=false, $int_max_file_size=0, $strFileType="IMAGE", $field_file="class=typefile", $description_size=0, $field_text="class=typeinput", $field_checkbox="", $bShowNotes=true, $bShowFilePath=true)
static UpdateExternalId($ID, $external_id)
static CleanCache($fileId)
static ResizeImage(&$arFile, $arSize, $resizeType=BX_RESIZE_IMAGE_PROPORTIONAL)
static GetImageSize($path, $bPhysicalName=false, $flashEnabled=false)
static CreateImage($path)
static SaveForDB(&$arFields, $field, $strSavePath)
static GetFlashExtensions()
static transformName($name, $forceRandom=false, $bSkipExt=false)
static ImageRotate($sourceFile, $angle)
static IsImage($filename, $mime_type=false)
static GetContentType($path, $bPhysicalName=false)
static WatermarkText($obj, $Params=[])
static validateFile($strFileName, $arFile)
static NormalizeContentType($contentType)
static FormatSize($size, $precision=2)
static DoInsert($arFields)
static ScaleImage($sourceImageWidth, $sourceImageHeight, $arSize, $resizeType, &$bNeedCreatePicture, &$arSourceSize, &$arDestinationSize)
static ApplyImageFilter($picture, $arFilter)
static ResizeImageDeleteCache($arFile)
static ImageFlipHorizontal($picture)
static ConvertFilesToPost($source, &$target, $field=false)
static CalculateHash($file, $size)
static MakeFileArray($path, $mimetype=false, $skipInternal=false, $external_id="")
static GetByID($fileId, $realId=false)
static translit($str, $lang, $params=[])
</td ></tr ></table ></td ></tr >< tr >< td class="bx-popup-label bx-width30"><?=GetMessage("PAGE_NEW_TAGS")?> array( $site)
$_SERVER["DOCUMENT_ROOT"]
global $arCloudImageSizeCache
const BX_RESIZE_IMAGE_EXACT
const BX_RESIZE_IMAGE_PROPORTIONAL
const BX_RESIZE_IMAGE_PROPORTIONAL_ALT
if($NS['step']==6) if( $NS[ 'step']==7) if(COption::GetOptionInt('main', 'disk_space', 0) > 0) $info
ExecuteModuleEventEx($arEvent, $arParams=[])
bxstrrpos($haystack, $needle)
RemoveScriptExtension($check_name)
bx_basename($path, $ext="")
RewriteFile($abs_path, $strContent)
htmlspecialcharsbx($string, $flags=ENT_COMPAT, $doubleEncode=true)
GetModuleEvents($MODULE_ID, $MESSAGE_ID, $bReturnArray=false)
IncludeModuleLangFile($filepath, $lang=false, $bReturnArray=false)
CopyDirFiles($path_from, $path_to, $ReWrite=true, $Recursive=false, $bDeleteAfterCopy=false, $strExclude="")
GetMessage($name, $aReplace=null)
GetFileNameWithoutExtension($path)
MakeTimeStamp($datetime, $format=false)
if(mb_strlen($order)< 6) $desc
if( $daysToExpire >=0 &&$daysToExpire< 60 elseif)( $daysToExpire< 0)
if(empty($signedUserToken)) $key