]> git.mxchange.org Git - core.git/blob - framework/main/classes/file_directories/io_stream/class_FileIoStream.php
Continued:
[core.git] / framework / main / classes / file_directories / io_stream / class_FileIoStream.php
1 <?php
2 // Own namespace
3 namespace Org\Mxchange\CoreFramework\Stream\Filesystem;
4
5 // Import framework stuff
6 use Org\Mxchange\CoreFramework\EntryPoint\ApplicationEntryPoint;
7 use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
8 use Org\Mxchange\CoreFramework\Filesystem\FileNotFoundException;
9 use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
10 use Org\Mxchange\CoreFramework\Generic\UnsupportedOperationException;
11 use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
12 use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
13 use Org\Mxchange\CoreFramework\Stream\Filesystem\FileInputStreamer;
14 use Org\Mxchange\CoreFramework\Stream\Filesystem\FileOutputStreamer;
15
16 // Import SPL stuff
17 use \InvalidArgumentException;
18 use \OutOfBoundsException;
19 use \SplFileInfo;
20
21 /**
22  * An universal class for file input/output streams.
23  *
24  * @author              Roland Haeder <webmaster@shipsimu.org>
25  * @version             0.0.0
26  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
27  * @license             GNU GPL 3.0 or any newer version
28  * @link                http://www.shipsimu.org
29  *
30  * This program is free software: you can redistribute it and/or modify
31  * it under the terms of the GNU General Public License as published by
32  * the Free Software Foundation, either version 3 of the License, or
33  * (at your option) any later version.
34  *
35  * This program is distributed in the hope that it will be useful,
36  * but WITHOUT ANY WARRANTY; without even the implied warranty of
37  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
38  * GNU General Public License for more details.
39  *
40  * You should have received a copy of the GNU General Public License
41  * along with this program. If not, see <http://www.gnu.org/licenses/>.
42  */
43 class FileIoStream extends BaseFrameworkSystem implements FileInputStreamer, FileOutputStreamer {
44         /**
45          * File header indicator
46          */
47         const FILE_IO_FILE_HEADER_ID = '@head';
48
49         /**
50          * Data block indicator
51          */
52         const FILE_IO_DATA_BLOCK_ID = '@data';
53
54         /**
55          * Separator #1
56          */
57         const FILE_IO_CHUNKER = ':';
58
59         /**
60          * Separator #2
61          */
62         const FILE_IO_SEPARATOR = '^';
63
64         /**
65          * Protected constructor
66          */
67         private function __construct () {
68                 // Call parent constructor
69                 parent::__construct(__CLASS__);
70         }
71
72         /**
73          * Create a file IO stream. This is a class for performing all actions
74          * on files like creating, deleting and loading them.
75          *
76          * @return      $ioInstance     An instance of a FileIoStream class
77          */
78         public static final function createFileIoStream () {
79                 // Create new instance
80                 $ioInstance = new FileIoStream();
81
82                 // Return the instance
83                 return $ioInstance;
84         }
85
86         /**
87          * Saves data to a given local file and create missing directory structures
88          *
89          * @param       $fileInfoInstance       An instance of a SplFileInfo class
90          * @param       $dataArray      The data we shall store to the file
91          * @return      void
92          * @see         FileOutputStreamer
93          * @throws      InvalidArgumentException        If an invalid parameter was given
94          * @throws      OutOfBoundsException    If an expected array element wasn't found
95          */
96         public final function saveFile (SplFileInfo $fileInfoInstance, array $dataArray) {
97                 // Trace message
98                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-IO-STREAM: fileInfoInstance=%s,dataArray()=%d - CALLED!', $fileInfoInstance, count($dataArray)));
99                 if (count($dataArray) < 2) {
100                         // Not valid array, at least 2 elements must be there!
101                         throw new InvalidArgumentException(sprintf('Parameter "dataArray" should have at least 2 elements, has %d', count($dataArray)));
102                 } else if (!isset($dataArray[0])) {
103                         // Array element 0 not found
104                         throw new OutOfBoundsException(sprintf('Array element dataArray[0] not found, dataArray=%s', json_encode($dataArray)));
105                 } else if (!isset($dataArray[1])) {
106                         // Array element 1 not found
107                         throw new OutOfBoundsException(sprintf('Array element dataArray[1] not found, dataArray=%s', json_encode($dataArray)));
108                 }
109
110                 try {
111                         // Get a file output pointer
112                         $fileInstance = ObjectFactory::createObjectByConfiguredName('file_raw_output_class', [$fileInfoInstance, 'wb']);
113                 } catch (FileNotFoundException $e) {
114                         // Bail out
115                         ApplicationEntryPoint::exitApplication('The application has made a fatal error. Exception: ' . $e->__toString() . ' with message: ' . $e->getMessage());
116                 }
117
118                 // Write a header information for validation purposes
119                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-IO-STREAM: Writing header to fileInstance=%s ...', $fileInstance->__toString()));
120                 $fileInstance->writeToFile(sprintf('%s%s%s%s%s%s%s%s%s' . PHP_EOL,
121                         self::FILE_IO_FILE_HEADER_ID,
122                         self::FILE_IO_SEPARATOR,
123                         $dataArray[0],
124                         self::FILE_IO_CHUNKER,
125                         time(),
126                         self::FILE_IO_CHUNKER,
127                         strlen($dataArray[1]),
128                         self::FILE_IO_CHUNKER,
129                         md5($dataArray[1])
130                 ));
131
132                 // Encode the (maybe) binary stream with Base64
133                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-IO-STREAM: Encoding %d bytes to BASE64 string ...', strlen($dataArray[1])));
134                 $b64Stream = base64_encode($dataArray[1]);
135
136                 // write the data line-by-line
137                 $line = str_repeat(' ', 50); $idx = 0;
138                 while (strlen($line) == 50) {
139                         // Get 50 chars or less
140                         $line = substr($b64Stream, $idx, 50);
141
142                         // Save it to the stream
143                         /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-IO-STREAM: Writing %d bytes to file ...', strlen($line)));
144                         $fileInstance->writeToFile(sprintf('%s%s%s%s%s' . PHP_EOL,
145                                 self::FILE_IO_DATA_BLOCK_ID,
146                                 self::FILE_IO_SEPARATOR,
147                                 $line,
148                                 self::FILE_IO_CHUNKER,
149                                 md5($line)
150                         ));
151
152                         // Advance to the next 50-chars block
153                         $idx += 50;
154                 }
155
156                 // Close the file
157                 unset($fileInstance);
158
159                 // Trace message
160                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('FILE-IO-STREAM: EXIT!');
161         }
162
163         /**
164          * Reads from a local file
165          *
166          * @param       $infoInstance   An instance of a SplFileInfo class
167          * @return      $array  An array with the element 'header' and 'data'
168          * @see         FileInputStreamer
169          */
170         public final function loadFileContents (SplFileInfo $infoInstance) {
171                 // Initialize some variables and arrays
172                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-IO-STREAM: infoInstance=%s - CALLED!', $infoInstance));
173                 $inputBuffer = '';
174                 $lastBuffer = '';
175                 $header = [];
176                 $data = [];
177                 $readData = ''; // This will contain our read data
178
179                 // Get a file input handler
180                 $fileInstance = ObjectFactory::createObjectByConfiguredName('file_raw_input_class', array($infoInstance));
181
182                 // Read all it's contents (we very and transparently decompress it below)
183                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-IO-STREAM: fileInstance=%s', $fileInstance->__toString()));
184                 while ($readRawLine = $fileInstance->readFromFile()) {
185                         // Add the read line to the buffer
186                         /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-IO-STREAM: Adding %d read bytes to input buffer.', strlen($readRawLine)));
187                         $inputBuffer .= $readRawLine;
188
189                         // Break infinite loop maybe caused by the input handler
190                         if ($lastBuffer == $inputBuffer) {
191                                 // Break out of loop, EOF reached?
192                                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('FILE-IO-STREAM: EOF reached!');
193                                 break;
194                         }
195
196                         // Remember last read line for avoiding possible infinite loops
197                         $lastBuffer = $inputBuffer;
198                 }
199
200                 // Close directory handle
201                 unset($fileInstance);
202
203                 // Convert it into an array
204                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-IO-STREAM: Read inputBuffer=%d bytes from infoInstance=%s', strlen($inputBuffer), $infoInstance));
205                 $inputArray = explode(chr(10), $inputBuffer);
206
207                 // Now process the read lines and verify it's content
208                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-IO-STREAM: inputArray()=%d', count($inputArray)));
209                 foreach ($inputArray as $rawLine) {
210                         // Trim it a little but not the leading spaces/tab-stops
211                         $rawLine = rtrim($rawLine);
212
213                         // Analyze this line
214                         /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-IO-STREAM: rawLine()=%d', strlen($rawLine)));
215                         if (substr($rawLine, 0, 5) == self::FILE_IO_FILE_HEADER_ID) {
216                                 // Header found, so let's extract it
217                                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-IO-STREAM: Found header, rawLine=%s', $rawLine));
218                                 $header = explode(self::FILE_IO_SEPARATOR, $rawLine);
219                                 $headerLine = trim($header[1]);
220
221                                 // Now we must convert it again into an array
222                                 $header = explode(self::FILE_IO_CHUNKER, $headerLine);
223
224                                 // Is the header (maybe) valid?
225                                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-IO-STREAM: header()=%d', count($header)));
226                                 if (count($header) != 4) {
227                                         // Throw an exception
228                                         throw new InvalidArrayCountException(array($this, 'header', count($header), 4), self::EXCEPTION_ARRAY_HAS_INVALID_COUNT);
229                                 }
230                         } elseif (substr($rawLine, 0, 5) == self::FILE_IO_DATA_BLOCK_ID) {
231                                 // Is a data line!
232                                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-IO-STREAM: Data line found rawLine=%s', $rawLine));
233                                 $data = explode(self::FILE_IO_SEPARATOR, $rawLine);
234                                 $dataLine = $data[1];
235
236                                 // First element is the data, second the MD5 checksum
237                                 $data = explode(self::FILE_IO_CHUNKER, $dataLine);
238
239                                 // Validate the read line
240                                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-IO-STREAM: data()=%d', count($data)));
241                                 if (count($data) == 2) {
242                                         // Generate checksum (MD5 is okay here)
243                                         $checksum = md5($data[0]);
244
245                                         // Check if it matches provided one
246                                         /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-IO-STREAM: checksum=%s,data[1]=%s', $checksum, $data[1]));
247                                         if ($checksum != $data[1]) {
248                                                 // MD5 hash did not match!
249                                                 throw new InvalidMD5ChecksumException(array($this, $checksum, $data[1]), self::EXCEPTION_MD5_CHECKSUMS_MISMATCH);
250                                         }
251                                 } else {
252                                         // Invalid count!
253                                         throw new InvalidArrayCountException(array($this, 'data', count($data), 2), self::EXCEPTION_ARRAY_HAS_INVALID_COUNT);
254                                 }
255
256                                 // Add this to the readData string
257                                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-IO-STREAM: Adding %d raw data to input stream', strlen($data[0])));
258                                 $readData .= $data[0];
259                         } else {
260                                 // Other raw lines than header/data tagged lines and re-add the new-line char
261                                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-IO-STREAM: Adding rawLine=%s(%d) + PHP_EOL to input stream', $rawLine, strlen($rawLine)));
262                                 $readData .= $rawLine . PHP_EOL;
263                         }
264                 }
265
266                 // Was raw lines read and no header/data?
267                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-IO-STREAM: readData()=%d,header()=%d,data()=%d', strlen($readData), count($header), count($data)));
268                 if ((!empty($readData)) && (count($header) == 0) && (count($data) == 0)) {
269                         // Return raw lines back
270                         /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-IO-STREAM: readData()=%d - EXIT!', strlen($readData)));
271                         return $readData;
272                 }
273
274                 // Was a header found?
275                 if (count($header) != 4) {
276                         // Throw an exception
277                         throw new InvalidArrayCountException(array($this, 'header', count($header), 4), self::EXCEPTION_ARRAY_HAS_INVALID_COUNT);
278                 }
279
280                 // Decode all from Base64
281                 $decodedData = @base64_decode($readData);
282
283                 // Does the size match?
284                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-IO-STREAM: decodedData()=%d,header[2]=%d', strlen($decodedData), $header[2]));
285                 if (strlen($decodedData) != $header[2]) {
286                         // Size did not match
287                         throw new InvalidDataLengthException(array($this, strlen($decodedData), $header[2]), self::EXCEPTION_UNEXPECTED_STRING_SIZE);
288                 }
289
290                 // Generate checksum from whole read data
291                 $checksum = md5($decodedData);
292
293                 // Validate the decoded data with the final MD5 hash
294                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-IO-STREAM: checksum=%s,header[3]=%s', $checksum, $header[3]));
295                 if ($checksum != $header[3]) {
296                         // MD5 hash did not match!
297                         throw new InvalidMD5ChecksumException(array($this, $checksum, $header[3]), self::EXCEPTION_MD5_CHECKSUMS_MISMATCH);
298                 }
299
300                 // Return all in an array
301                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-IO-STREAM: header()=%d,decodedData()=%d - EXIT!', count($header), strlen($decodedData)));
302                 return [
303                         'header' => $header,
304                         'data'   => $decodedData,
305                 ];
306         }
307
308         /**
309          * Streams the data and maybe does something to it
310          *
311          * @param       $data   The data (string mostly) to "stream"
312          * @return      $data   The data (string mostly) to "stream"
313          * @throws      UnsupportedOperationException   If this method is called
314          */
315         public function streamData (string $data) {
316                 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('Unhandled ' . strlen($data) . ' bytes in this stream.');
317                 throw new UnsupportedOperationException([$this, __FUNCTION__], FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
318         }
319
320         /**
321          * Determines seek position
322          *
323          * @return      $seekPosition   Current seek position
324          * @todo        0% done
325          */
326         public function determineSeekPosition () {
327                 DebugMiddleware::getSelfInstance()->partialStub();
328         }
329
330         /**
331          * Seek to given offset (default) or other possibilities as fseek() gives.
332          *
333          * @param       $offset         Offset to seek to (or used as "base" for other seeks)
334          * @param       $whence         Added to offset (default: only use offset to seek to)
335          * @return      $status         Status of file seek: 0 = success, -1 = failed
336          */
337         public function seek (int $offset, int $whence = SEEK_SET) {
338                 DebugMiddleware::getSelfInstance()->partialStub('offset=' . $offset . ',whence=' . $whence);
339         }
340
341         /**
342          * Size of file stack
343          *
344          * @return      $size   Size (in bytes) of file
345          */
346         public function size () {
347                 DebugMiddleware::getSelfInstance()->partialStub();
348         }
349
350 }