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