DownloadObjectRequestClass.php
3.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
<?php
/**
* @class DownloadObjectRequestClass
* @brief Class used for a download request
* @details
*/
class DownloadObjectRequestClass extends RequestAbstractClass
{
/*
* @brief Init a donwload object request
*/
public function init(){
if (!isset($this->requestData))
return false;
if (!is_dir($this->requestData->getWorkingPath())) {
mkdir($this->requestData->getWorkingPath());
}
return true;
}
public function run(){
// Array to hold the paths of the downloaded files
$filePaths = array();
$files = $this->requestData->getFiles();
foreach($files as $fileName => $fileUrl){
$result = $this->downloadFile($fileName, $fileUrl, $this->requestData->getWorkingPath());
if (!$result['success']) {
$this->cleanup($filePaths);
$this->requestData->setLastErrorMessage($result['message']);
$this->requestData->setSuccess(false);
return false;
}
$filePaths[] = $result['filePath'];
}
$result = $this->zipFiles($filePaths, $this->requestData->getOutputPath());
if (!$result['success']) {
$this->cleanup($filePaths);
$this->requestData->setLastErrorMessage($result['message']);
$this->requestData->setSuccess(false);
return false;
}
$this->cleanup($filePaths);
$this->requestData->setSuccess(true);
return true;
}
public function downloadFile($fileName, $fileUrl, $workingDir){
// Initialize cURL session
$ch = curl_init($fileUrl);
// Set cURL options
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
// Execute cURL request
$content = curl_exec($ch);
// Check for cURL errors
if (curl_errno($ch)) {
curl_close($ch);
return array(
"success" => FALSE,
"message" => "Cannot download $fileUrl",
);
}
// Close cURL session
curl_close($ch);
// Write file in working dir
$filePath = $workingDir . '/' . $fileName;
file_put_contents($filePath, $content);
return array(
"success" => TRUE,
"filePath" => $filePath,
);
}
public function zipFiles($filePaths, $outputPath){
// Create a zip file
$zip = new ZipArchive();
if ($zip->open($outputPath, ZipArchive::CREATE) !== TRUE) {
return array(
"success" => FALSE,
"message" => "Cannot create output archive",
);
}
// Add files to the zip archive
foreach ($filePaths as $filePath) {
$zip->addFile($filePath, basename($filePath));
}
// Close the zip archive
$zip->close();
// Return the path of the zip file
return array(
"success" => TRUE,
"zipfilepath" => $outputPath,
);
}
public function cleanup($filePaths) {
// Clean up the temporary files
foreach ($filePaths as $filePath) {
if (file_exists($filePath))
unlink($filePath);
}
}
}