3 namespace CoreFramework\Stream\Filesystem;
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;
14 * An universal class for file input/output streams.
16 * @author Roland Haeder <webmaster@shipsimu.org>
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
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.
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.
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/>.
35 class FileIoStream extends BaseFrameworkSystem implements FileInputStreamer, FileOutputStreamer {
37 * File header indicator
39 const FILE_IO_FILE_HEADER_ID = '@head';
42 * Data block indicator
44 const FILE_IO_DATA_BLOCK_ID = '@data';
49 const FILE_IO_CHUNKER = ':';
54 const FILE_IO_SEPARATOR = '^';
57 * Protected constructor
59 protected function __construct () {
60 // Call parent constructor
61 parent::__construct(__CLASS__);
65 * Create a file IO stream. This is a class for performing all actions
66 * on files like creating, deleting and loading them.
68 * @return $ioInstance An instance of a FileIoStream class
70 public static final function createFileIoStream () {
71 // Create new instance
72 $ioInstance = new FileIoStream();
74 // Return the instance
79 * Saves data to a given local file and create missing directory structures
81 * @param $fileName The file name for the to be saved file
82 * @param $dataArray The data we shall store to the file
84 * @see FileOutputStreamer
85 * @todo This method needs heavy rewrite
87 public final function saveFile ($fileName, array $dataArray) {
92 for ($idx = 0; $idx < 5; $idx++) {
93 // Get a file output pointer
95 $fileInstance = ObjectFactory::createObjectByConfiguredName('file_raw_output_class', array($fileName, 'wb'));
96 } catch (FileNotFoundException $e) {
98 ApplicationEntryPoint::app_exit('The application has made a fatal error. Exception: ' . $e->__toString() . ' with message: ' . $e->getMessage());
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,
107 self::FILE_IO_CHUNKER,
109 self::FILE_IO_CHUNKER,
110 strlen($dataArray[1]),
111 self::FILE_IO_CHUNKER,
115 // Encode the (maybe) binary stream with Base64
116 $b64Stream = base64_encode($dataArray[1]);
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);
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,
129 self::FILE_IO_CHUNKER,
133 // Advance to the next 50-chars block
138 unset($fileInstance);
142 * Reads from a local file
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
148 public final function loadFileContents ($fqfn) {
149 // Initialize some variables and arrays
154 $readData = ''; // This will contain our read data
156 // Get a file input handler
157 $fileInstance = ObjectFactory::createObjectByConfiguredName('file_raw_input_class', array($fqfn));
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;
164 // Break infinite loop maybe caused by the input handler
165 if ($lastBuffer == $inputBuffer) {
169 // Remember last read line for avoiding possible infinite loops
170 $lastBuffer = $inputBuffer;
173 // Close directory handle
174 unset($fileInstance);
176 // Convert it into an array
177 $inputBuffer = explode(chr(10), $inputBuffer);
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);
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]);
190 // Now we must convert it again into an array
191 $header = explode(self::FILE_IO_CHUNKER, $header);
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);
198 } elseif (substr($rawLine, 0, 5) == self::FILE_IO_DATA_BLOCK_ID) {
200 $data = explode(self::FILE_IO_SEPARATOR, $rawLine);
203 // First element is the data, second the MD5 checksum
204 $data = explode(self::FILE_IO_CHUNKER, $data);
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);
214 throw new InvalidArrayCountException(array($this, 'data', count($data), 2), self::EXCEPTION_ARRAY_HAS_INVALID_COUNT);
217 // Add this to the readData string
218 $readData .= $data[0];
220 // Other raw lines than header/data tagged lines and re-add the new-line char
221 $readData .= $rawLine . PHP_EOL;
225 // Was raw lines read and no header/data?
226 if ((!empty($readData)) && (count($header) == 0) && (count($data) == 0)) {
227 // Return raw lines back
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);
237 // Decode all from Base64
238 $readData = @base64_decode($readData);
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);
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);
252 // Return all in an array
260 * Streams the data and maybe does something to it
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
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);
272 * Determines seek position
274 * @return $seekPosition Current seek position
277 public function determineSeekPosition () {
278 $this->partialStub();
282 * Seek to given offset (default) or other possibilities as fseek() gives.
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
288 public function seek ($offset, $whence = SEEK_SET) {
289 $this->partialStub('offset=' . $offset . ',whence=' . $whence);
295 * @return $size Size (in bytes) of file
297 public function size () {
298 $this->partialStub();