Joywork/download_file.php
2026-05-22 21:21:54 +03:00

394 lines
15 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
require_once($_SERVER['DOCUMENT_ROOT'] . "/config.php");
if (!isset($_GET['download']) && isset($_GET['preview'])) {
$get = clearInputData($_GET);
require($_SERVER['DOCUMENT_ROOT'] . "/templates/new-header.php");
}
ini_set('display_errors', 1);
error_reporting(E_ALL & ~E_DEPRECATED & ~E_STRICT & ~E_NOTICE);
$pdo = new MysqlPdo(hst, ndb, user, pass);
$sql = "SET NAMES 'utf8'";
$pdo->query($sql);
function file_force_download($file, $name)
{
if (file_exists($file)) {
// сбрасываем буфер вывода PHP, чтобы избежать переполнения памяти выделенной под скрипт
// если этого не сделать файл будет читаться в память полностью!
if (ob_get_level()) {
ob_end_clean();
}
//echo $name;
// заставляем браузер показать окно сохранения файла
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header("Content-Disposition: attachment; filename=\"" . $name . "\"");
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
// читаем файл и отправляем его пользователю
readfile($file);
exit;
}
}
function file_force_download_url($url, $name) {
$res = doesFileUrlExists($url);
if ($res[0]) {
// сбрасываем буфер вывода PHP, чтобы избежать переполнения памяти выделенной под скрипт
// если этого не сделать файл будет читаться в память полностью!
if (ob_get_level()) {
ob_end_clean();
}
//echo $name;
// заставляем браузер показать окно сохранения файла
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header("Content-Disposition: attachment; filename=\"" . $name . "\"");
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . $res[1]);
// читаем файл и отправляем его пользователю
echo file_get_contents($url);
exit;
}
}
function doesFileUrlExists($url) {
$headers = get_headers($url, true);
return [(stripos($headers[0], "200 OK") ? true : false), (isset($headers['Content-Length']) ? (int) $headers['Content-Length'] : 0)];
}
function endsWith($haystack, $needle) {
return $needle === "" || (substr($haystack, -strlen($needle)) === $needle);
}
if (isset($_GET['id']) && (int)$_GET['id'] > 0) {
$id = (int)$_GET['id'];
$name = '';
// $file = $_SERVER['DOCUMENT_ROOT'] . "/upload/";
// Убрал документ рут для просмотра файла (формирование урла для google viewer)
$file = "/upload/";
$sql = "SELECT * FROM `clients_files` WHERE id = {$id}";
$q = $pdo->query($sql, true);
$r = $pdo->fetch_assoc($q);
if ($r['client_id'] > 0) {
$file .= "clients/" . $r['client_id'] . "/";
$file = "https://uf.joywork.ru" . $file;
} else if ($r['req_id'] > 0) {
$file .= "/reqs/" . $r['req_id'] . "/";
$file = "https://uf.joywork.ru" . $file;
} else if ($r['object_id'] > 0) {
$file .= "/objects/" . $r['object_id'] . "/";
$file = "https://uf.joywork.ru" . $file;
}
$file .= $r['guid'] . '.' . $r['type'];
$extension = $r['type'];
$name = $r['name'];
// Если есть параметр - отдаем файл для скачивания
if ((isset($_GET['download']) && $_GET['download']) || !isset($_GET['preview'])) {
if ($r['req_id'] > 0 || $r['object_id'] > 0 || $r['client_id'] > 0) {
file_force_download_url($file, $name . '.' . $extension);
} else {
file_force_download($_SERVER["DOCUMENT_ROOT"] . $file, $name . '.' . $extension);
}
}
}
if (isset($_GET['userFileId']) && (int)$_GET['userFileId'] > 0) {
$id = (int)$_GET['userFileId'];
$name = '';
$sql = "SELECT * FROM `users_files` WHERE id = {$id}";
$q = $pdo->query($sql, true);
$r = $pdo->fetch_assoc($q);
$file = $r['path'];
$extension = explode('.', $file);
if(count($extension) > 0) {
$extension = $extension[1];
}
$name = $r['filename'];
// Если есть параметр - отдаем файл для скачивания
if ((isset($_GET['download']) && $_GET['download']) || !isset($_GET['preview'])) {
file_force_download($_SERVER["DOCUMENT_ROOT"] . $file, $name . '.' . $extension);
}
}
if (isset($_GET['guid']) && !empty($_GET['guid'])) {
$guid = $_GET['guid'];
$name = '';
// $file = $_SERVER['DOCUMENT_ROOT'] . "/upload/funnels/";
// Убрал документ рут для просмотра файла (формирование урла для google viewer)
$file = "/upload/funnels/";
$sql = "SELECT * FROM `funnel_files` WHERE guid = '{$guid}'";
$q = $pdo->query($sql, true);
$r = $pdo->fetch_assoc($q);
if ($r['client_id'] > 0) {
$file .= "clients/" . $r['client_id'] . "/";
} else if ($r['req_id'] > 0) {
$file .= "req/" . $r['req_id'] . "/";
}
$file .= $r['guid'] . '.' . $r['type'];
$extension = $r['type'];
$name = $r['name'];
$file = "https://uf.joywork.ru" . $file;
// Если есть параметр - отдаем файл для скачивания
if ((isset($_GET['download']) && $_GET['download']) || !isset($_GET['preview'])) {
if (endsWith($name, $extension)) {
$extension = "";
}
if ($extension) {
file_force_download_url($file, $name . '.' . $extension);
} else {
file_force_download_url($file, $name);
}
}
}
if (isset($_GET['arhive'])) {
$id_arhive = 0;
$selector = $_GET['selector'];
$type = $_GET['type'];
$id = (int)$_GET['id_type'];
if ((int)$_GET['arhive'] > 0) {
$id_arhive = (int)$_GET['arhive'];
}
$time = time();
$zip_name = $_SERVER['DOCUMENT_ROOT'] . '/upload/zip/' . $time . '.zip';
echo $zip_name;
$zip = new ZipArchive();
if ($zip->open($zip_name, ZipArchive::CREATE) !== TRUE) {
throw new \Exception('Cannot create a zip file');
}
$pole = '';
if ($type == 'client') {
$pole = 'client_id';
} else if ($type == 'req') {
$pole = 'req_id';
} else if ($type == 'object') {
$pole = 'object_id';
}
if ($selector == 'id') {
$sql = "SELECT * FROM clients_files WHERE {$pole} = {$id} AND event_id > 0 AND name_id = {$id_arhive}";
$q = $pdo->query($sql, true);
if ($pdo->num_rows($q) > 0) {
while ($r = $pdo->fetch_assoc($q)) {
if (!empty($r['name'])) {
$file = $_SERVER['DOCUMENT_ROOT'] . "/upload/";
if ($r['client_id'] > 0) {
$file .= "clients/" . $r['client_id'] . "/";
} else if ($r['req_id'] > 0) {
$file .= "reqs/" . $r['req_id'] . "/";
} else if ($r['object_id'] > 0) {
$file .= "objects/" . $r['object_id'] . "/";
}
$file .= $r['guid'] . '.' . $r['type'];
if (file_exists($file)) {
$zip->addFile($file, $r['name']);
}
}
}
}
} else if ($selector == 'guid') {
$sql = "SELECT * FROM `funnel_files` WHERE {$pole} = {$id} AND etap_id = {$id_arhive}";
$q = $pdo->query($sql, true);
if ($pdo->num_rows($q) > 0) {
while ($r = $pdo->fetch_assoc($q)) {
if (!empty($r['name'])) {
$file = $_SERVER['DOCUMENT_ROOT'] . "/upload/funnels/";
if ($r['client_id'] > 0) {
$file .= "clients/" . $r['client_id'] . "/";
} else if ($r['req_id'] > 0) {
$file .= "req/" . $r['req_id'] . "/";
}
$file .= $r['guid'] . '.' . $r['type'];
if (file_exists($file)) {
$zip->addFile($file, $r['name']);
}
}
}
}
}
$zip->close();
file_force_download($zip_name, $time . '.zip');
}
if(isset($_GET['afd_id']) && (int)$_GET['afd_id'] > 0){
$id = (int)$_GET['afd_id'];
$sql = "SELECT * FROM `agency_folders_docs` WHERE id = {$id}";
$q = $pdo->query($sql, true);
$r = $pdo->fetch_assoc($q);
// Убираю протокол и хост и урл (видимо ранее это писалось в базу)
$file = str_replace('http://joywork.ru','', $r['url']);
$file = str_replace('https://joywork.ru','', $file);
$extension = explode('.', $file);
if(count($extension) > 0) {
$extension = $extension[1];
}
$name = $r['name'];
// Если есть параметр - отдаем файл для скачивания
if ((isset($_GET['download']) && $_GET['download']) || !isset($_GET['preview'])) {
if (endsWith($name, $extension)) {
$extension = "";
}
if ($extension) {
file_force_download($_SERVER["DOCUMENT_ROOT"] . urldecode($file), $name . '.' . $extension);
} else {
file_force_download($_SERVER["DOCUMENT_ROOT"] . urldecode($file), $name);
}
}
}
if (!isset($_GET['download']) && isset($_GET['preview'])) {
?>
<div class="content-right" style="min-height: 100%;">
<div class="inner">
<div class="main-title">
<h1>Просмотр файла</h1>
</div>
<div class="crm new">
<div class="file-viewer-wrapper">
<div class="file-viewer-wrapper__actions">
<a href="<?php echo $_SERVER['REQUEST_URI'] ?>&download=1" download class="jw__g-button file-viewer-wrapper__btn">Скачать</a>
</div>
<?php
if (strpos($file, "https") !== false) {
$path = $file;
} else {
$path = 'https://' . $_SERVER["HTTP_HOST"] . $file;
}
$ifrSrc = 'https://docs.google.com/viewer?url=' . $path . '&embedded=true&rm=minimal';
if (in_array($extension, [
'doc', 'docx', 'odt', 'pdf', 'xps', 'pages',
'rtf', 'sxw', 'sdw', 'txt',
'xls', 'xlsx',
'sdc',
'ppt', 'pptx',
'dfx', 'eps', 'psd', 'svg', 'tif', 'ttf',
'ai', 'PPTX'
])) {
?>
<div class="holds-the-iframe">
<iframe id="viewer-dc" onselectstart="return false"
src="<?= $ifrSrc ?>"
frameborder="0" style="width: 100%; height: 90vh; /**
* Для эксплорера
*/
-ms-user-select: none;
/**
* Для мозилы
*/
-moz-user-select: none;
/**
* Для конкверора
*/
-khtml-user-select: none;
/**
* Для Сафари и Хрома
*/
user-select: none;
-webkit-user-select: none;"></iframe>
<script>
function reloadIFrame() {
document.getElementById("viewer-dc").src=document.getElementById("viewer-dc").src;
}
timerId = setInterval(reloadIFrame, 2000);
$( document ).ready(function() {
$('#viewer-dc').on('load', function() {
clearInterval(timerId);
});
});
</script>
</div>
<?php } elseif (in_array($extension, [
'jpg', 'jpeg', 'png', 'JPG', 'JPEG', 'PNG'
])) { ?>
<img style="overflow-x: auto;" class="hh" src="<?= $path ?>" alt="">
<?php } elseif (in_array($extension, [
'avi', 'mp4', '3gp', 'wma', 'MP4', '3GP'
])) { ?>
<video
id="my-video"
class="video-js"
controls
preload="auto"
style="width: 100%; height: 70vh"
data-setup="{}"
>
<source src="<?= $path ?>" type="video/<?= $extension ?>"/>
<p class="vjs-no-js">
To view this video please enable JavaScript, and consider upgrading to a
web browser that
<a href="https://videojs.com/html5-video-support/" target="_blank"
>supports HTML5 video</a
>
</p>
</video>
<link href="https://vjs.zencdn.net/7.10.2/video-js.css" rel="stylesheet"/>
<script src="https://vjs.zencdn.net/7.10.2/video.min.js"></script>
<?php } else { ?>
<p>Предпросмотр данного формата недоступен.</p>
<?php } ?>
</div>
</div>
</div>
</div>
<style>
.file-viewer-wrapper {
padding: 15px;
overflow-x: auto;
}
.file-viewer-wrapper__actions {
margin-bottom: 15px;
}
.file-viewer-wrapper__btn {
padding: 5px 15px;
}
</style>
<?php require($_SERVER['DOCUMENT_ROOT'] . "/templates/footer.php"); ?>
<?php } ?>