Debian Codegraph @

classes/RemoteFilesystems/RemoteFilesystem.php

raw symbols SCIP
1 <?php
2
3 /**
4 * dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
5 * Copyright (C) 2023 Aleksey Andreev (liuch)
6 *
7 * Available at:
8 * https://github.com/liuch/dmarc-srg
9 *
10 * This program is free software: you can redistribute it and/or modify it
11 * under the terms of the GNU General Public License as published by the Free
12 * Software Foundation, either version 3 of the License.
13 *
14 * This program is distributed in the hope that it will be useful, but WITHOUT
15 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
17 * more details.
18 *
19 * You should have received a copy of the GNU General Public License along with
20 * this program. If not, see <http://www.gnu.org/licenses/>.
21 *
22 * =========================
23 *
24 * This file contains the class RemoteFilesystem
25 *
26 * @category API
27 * @package DmarcSrg
28 * @author Aleksey Andreev (liuch)
29 * @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3
30 */
31
32 namespace Liuch\DmarcSrg\RemoteFilesystems;
33
34 use Liuch\DmarcSrg\ErrorHandler;
35 use Liuch\DmarcSrg\Exception\LogicException;
36 use Liuch\DmarcSrg\Exception\RuntimeException;
37
38 /**
39 * This class is designed to work with remote filesystems which are listed in the configuration file.
40 */
41 class RemoteFilesystem
42 {
43 private $id = null;
44 private $fs = null;
45 private $name = null;
46 private $type = null;
47 private $params = null;
48
49 /**
50 * It's the constructor of the class
51 *
52 * @param int $id Id of the remote filesystem. In fact, it is a serial number in the configuration file.
53 * @param array $data An array with the following fields:
54 * `name` (string) - Name of the remote filesystem. It is optional.
55 * `type` (string) - Type of the remote filesystem. The valid types is `s3`.
56 * Other fields for the type `s3` (see conf/conf.sample.php for the details):
57 * `bucket` (string), `path` (string), `key` (string), `secret` (string)
58 * `token` (string), `profile` (string), `endpoit`, `region` (string)
59 *
60 * @return void
61 */
62 public function __construct(int $id, array $data)
63 {
64 if (isset($data['name']) && gettype($data['name']) !== 'string') {
65 throw new LogicException('Remote filesystem name must be either null or a string value');
66 }
67
68 $this->id = $id;
69 $this->name = $data['name'] ?? ('RFS-' . $id);
70
71 $type = $data['type'] ?? null;
72 switch ($type) {
73 case 's3':
74 $this->params = [];
75 foreach ([ 'bucket', 'path' ] as $p) {
76 if (!isset($data[$p])) {
77 throw new LogicException('Missed paramenter ' . $p);
78 }
79 $this->params[$p] = $data[$p];
80 }
81 // AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN
82 foreach ([ 'key', 'secret', 'token' ] as $p) {
83 if (isset($data[$p])) {
84 if (!isset($this->params['credentials'])) {
85 $this->params['credentials'] = [];
86 }
87 $this->params['credentials'][$p] = $data[$p];
88 }
89 }
90 // AWS_PROFILE
91 foreach ([ 'profile', 'endpoint', 'region' ] as $p) {
92 if (isset($data[$p])) {
93 $this->params[$p] = $data[$p];
94 }
95 }
96 $this->params['use_path_style_endpoint'] = isset($this->params['endpoint']);
97 break;
98 default:
99 throw new LogicException("Unknown remote filesystem type [{$type}]");
100 }
101 $this->type = $type;
102 }
103
104 /**
105 * Returns an array with remote filesystem configuration data.
106 *
107 * @return array
108 */
109 public function toArray(): array
110 {
111 return [
112 'id' => $this->id,
113 'name' => $this->name,
114 'location' => "{$this->params['bucket']}::{$this->params['path']}"
115 ];
116 }
117
118 /**
119 * Checks the existence and accessibility of the remote filesystem. Returns the result as an array.
120 *
121 * @return array
122 */
123 public function check(): array
124 {
125 try {
126 $cnt = $this->count();
127 } catch (\Aws\S3\Exception\S3Exception $e) {
128 return ErrorHandler::exceptionResult($e);
129 }
130
131 return [
132 'error_code' => 0,
133 'message' => 'Successfully',
134 'status' => [
135 'files' => $cnt
136 ]
137 ];
138 }
139
140 /**
141 * Returns a value indicating whether the resource is public
142 *
143 * @return bool
144 */
145 public function isPublic(): bool
146 {
147 try {
148 $ls = $this->getFilesystem(false)->listContents($this->params['path'], false);
149 foreach ($ls as $it) {
150 break;
151 }
152 } catch (\Aws\S3\Exception\S3Exception $e) {
153 return false;
154 } catch (\Exception $e) {
155 throw new RuntimeException($e->getMessage());
156 }
157 return true;
158 }
159
160 /**
161 * Returns the total number of files on the remote filesystem.
162 *
163 * @return int
164 */
165 public function count(): int
166 {
167 $cnt = 0;
168 try {
169 $ls = $this->getFilesystem(true)->listContents($this->params['path'], false);
170 foreach ($ls as $it) {
171 if ($it->isFile()) {
172 ++$cnt;
173 }
174 }
175 } catch (\Exception $e) {
176 throw new RuntimeException("Error accessing remote filesystem {$this->name}", -1, $e);
177 }
178 return $cnt;
179 }
180
181 /**
182 * Returns a read-once interable object that contains all files in the directory, not including subdirectories
183 *
184 * @return object
185 */
186 public function listFiles(): object
187 {
188 return $this->getFilesystem(true)->listContents($this->params['path'], false)->filter(
189 function ($attr) {
190 return $attr->isFile();
191 }
192 );
193 }
194
195 /**
196 * Returns file data as a resource
197 *
198 * @param string $path File path
199 *
200 * @return resource
201 */
202 public function readStream(string $path)
203 {
204 return $this->getFilesystem(true)->readStream($path);
205 }
206
207 /**
208 * Move a file within the filesystem
209 *
210 * @param string $sou_path Source file path
211 * @param string $des_path Destination file path
212 *
213 * @return void
214 */
215 public function move(string $sou_path, string $des_path): void
216 {
217 $this->getFilesystem(true)->move($sou_path, $des_path);
218 }
219
220 /**
221 * Deletes a file from the filesystem
222 *
223 * @param string $path File path
224 *
225 * @return void
226 */
227 public function delete(string $path): void
228 {
229 $this->getFilesystem(true)->delete($path);
230 }
231
232 /**
233 * Returns an instance of Filesystem
234 *
235 * @param bool $with_credentials Whether to pass credentials to filesystem adapter
236 *
237 * @return League\Flysystem\Filesystem|null
238 */
239 private function getFilesystem(bool $with_credentials)
240 {
241 $fs = $this->fs;
242 if (!$fs || !$with_credentials) {
243 switch ($this->type) {
244 case 's3':
245 $p = $this->params;
246 if (!$with_credentials) {
247 $p['credentials'] = false;
248 }
249 $adapter = new \League\Flysystem\AwsS3V3\AwsS3V3Adapter(
250 new \Aws\S3\S3Client($p),
251 $this->params['bucket']
252 );
253 break;
254 default:
255 return null;
256 }
257 $fs = new \League\Flysystem\Filesystem($adapter);
258 if ($with_credentials) {
259 $this->fs = $fs;
260 }
261 }
262 return $fs;
263 }
264 }