3 * An universal class for file input/output streams.
5 * @author Roland Haeder <webmaster@shipsimu.org>
7 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2015 Core Developer Team
8 * @license GNU GPL 3.0 or any newer version
9 * @link http://www.shipsimu.org
11 * This program is free software: you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation, either version 3 of the License, or
14 * (at your option) any later version.
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
21 * You should have received a copy of the GNU General Public License
22 * along with this program. If not, see <http://www.gnu.org/licenses/>.
24 class FileIoStream extends BaseFrameworkSystem implements FileInputStreamer, FileOutputStreamer {
26 * File header indicator
28 const FILE_IO_FILE_HEADER_ID = '@head';
31 * Data block indicator
33 const FILE_IO_DATA_BLOCK_ID = '@data';
38 const FILE_IO_CHUNKER = ':';
43 const FILE_IO_SEPARATOR = '^';
46 * Protected constructor
48 protected function __construct () {
49 // Call parent constructor
50 parent::__construct(__CLASS__);
54 * Create a file IO stream. This is a class for performing all actions
55 * on files like creating, deleting and loading them.
57 * @return $ioInstance An instance of FileIoStream
59 public static final function createFileIoStream () {
60 // Create new instance
61 $ioInstance = new FileIoStream();
63 // Return the instance
68 * Saves data to a given local file and create missing directory structures
70 * @param $fileName The file name for the to be saved file
71 * @param $dataArray The data we shall store to the file
73 * @see FileOutputStreamer
74 * @todo This method needs heavy rewrite
76 public final function saveFile ($fileName, array $dataArray) {
81 for ($idx = 0; $idx < 5; $idx++) {
82 // Get a file output pointer
84 $fileInstance = ObjectFactory::createObjectByConfiguredName('file_raw_output_class', array($fileName, 'wb'));
85 } catch (FileNotFoundException $e) {
87 ApplicationEntryPoint::app_exit('The application has made a fatal error. Exception: ' . $e->__toString() . ' with message: ' . $e->getMessage());
91 // Write a header information for validation purposes
92 $fileInstance->writeToFile(sprintf('%s%s%s%s%s%s%s%s%s' . PHP_EOL,
93 self::FILE_IO_FILE_HEADER_ID,
94 self::FILE_IO_SEPARATOR,
96 self::FILE_IO_CHUNKER,
98 self::FILE_IO_CHUNKER,
99 strlen($dataArray[1]),
100 self::FILE_IO_CHUNKER,
104 // Encode the (maybe) binary stream with Base64
105 $b64Stream = base64_encode($dataArray[1]);
107 // write the data line by line
108 $line = str_repeat(' ', 50); $idx = 0;
109 while (strlen($line) == 50) {
110 // Get 50 chars or less
111 $line = substr($b64Stream, $idx, 50);
113 // Save it to the stream
114 $fileInstance->writeToFile(sprintf('%s%s%s%s%s' . PHP_EOL,
115 self::FILE_IO_DATA_BLOCK_ID,
116 self::FILE_IO_SEPARATOR,
118 self::FILE_IO_CHUNKER,
122 // Advance to the next 50-chars block
127 unset($fileInstance);
131 * Reads from a local file
133 * @param $fqfn The full-qualified file-name which we shall load
134 * @return $array An array with the element 'header' and 'data'
135 * @see FileInputStreamer
137 public final function loadFileContents ($fqfn) {
138 // Initialize some variables and arrays
143 $readData = ''; // This will contain our read data
145 // Get a file input handler
146 $fileInstance = ObjectFactory::createObjectByConfiguredName('file_raw_input_class', array($fqfn));
148 // Read all it's contents (we very and transparently decompress it below)
149 while ($readRawLine = $fileInstance->readFromFile()) {
150 // Add the read line to the buffer
151 $inputBuffer .= $readRawLine;
153 // Break infinite loop maybe caused by the input handler
154 if ($lastBuffer == $inputBuffer) {
158 // Remember last read line for avoiding possible infinite loops
159 $lastBuffer = $inputBuffer;
162 // Close directory handle
163 unset($fileInstance);
165 // Convert it into an array
166 $inputBuffer = explode(chr(10), $inputBuffer);
168 // Now process the read lines and verify it's content
169 foreach ($inputBuffer as $rawLine) {
170 // Trim it a little but not the leading spaces/tab-stops
171 $rawLine = rtrim($rawLine);
174 if (substr($rawLine, 0, 5) == self::FILE_IO_FILE_HEADER_ID) {
175 // Header found, so let's extract it
176 $header = explode(self::FILE_IO_SEPARATOR, $rawLine);
177 $header = trim($header[1]);
179 // Now we must convert it again into an array
180 $header = explode(self::FILE_IO_CHUNKER, $header);
182 // Is the header (maybe) valid?
183 if (count($header) != 4) {
184 // Throw an exception
185 throw new InvalidArrayCountException(array($this, 'header', count($header), 4), self::EXCEPTION_ARRAY_HAS_INVALID_COUNT);
187 } elseif (substr($rawLine, 0, 5) == self::FILE_IO_DATA_BLOCK_ID) {
189 $data = explode(self::FILE_IO_SEPARATOR, $rawLine);
192 // First element is the data, second the MD5 checksum
193 $data = explode(self::FILE_IO_CHUNKER, $data);
195 // Validate the read line
196 if (count($data) == 2) {
197 if (md5($data[0]) != $data[1]) {
198 // MD5 hash did not match!
199 throw new InvalidMD5ChecksumException(array($this, md5($data[0]), $data[1]), self::EXCEPTION_MD5_CHECKSUMS_MISMATCH);
203 throw new InvalidArrayCountException(array($this, 'data', count($data), 2), self::EXCEPTION_ARRAY_HAS_INVALID_COUNT);
206 // Add this to the readData string
207 $readData .= $data[0];
209 // Other raw lines than header/data tagged lines and re-add the new-line char
210 $readData .= $rawLine . PHP_EOL;
214 // Was raw lines read and no header/data?
215 if ((!empty($readData)) && (count($header) == 0) && (count($data) == 0)) {
216 // Return raw lines back
220 // Was a header found?
221 if (count($header) != 4) {
222 // Throw an exception
223 throw new InvalidArrayCountException(array($this, 'header', count($header), 4), self::EXCEPTION_ARRAY_HAS_INVALID_COUNT);
226 // Decode all from Base64
227 $readData = @base64_decode($readData);
229 // Does the size match?
230 if (strlen($readData) != $header[2]) {
231 // Size did not match
232 throw new InvalidDataLengthException(array($this, strlen($readData), $header[2]), self::EXCEPTION_UNEXPECTED_STRING_SIZE);
235 // Validate the decoded data with the final MD5 hash
236 if (md5($readData) != $header[3]) {
237 // MD5 hash did not match!
238 throw new InvalidMD5ChecksumException(array($this, md5($readData), $header[3]), self::EXCEPTION_MD5_CHECKSUMS_MISMATCH);
241 // Return all in an array
249 * Streams the data and maybe does something to it
251 * @param $data The data (string mostly) to "stream"
252 * @return $data The data (string mostly) to "stream"
253 * @throws UnsupportedOperationException If this method is called
255 public function streamData ($data) {
256 self::createDebugInstance(__CLASS__)->debugOutput('Unhandled ' . strlen($data) . ' bytes in this stream.');
257 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
261 * Determines seek position
263 * @return $seekPosition Current seek position
266 public function determineSeekPosition () {
267 $this->partialStub();
271 * Seek to given offset (default) or other possibilities as fseek() gives.
273 * @param $offset Offset to seek to (or used as "base" for other seeks)
274 * @param $whence Added to offset (default: only use offset to seek to)
275 * @return $status Status of file seek: 0 = success, -1 = failed
277 public function seek ($offset, $whence = SEEK_SET) {
278 $this->partialStub('offset=' . $offset . ',whence=' . $whence);
284 * @return $size Size (in bytes) of file
286 public function size () {
287 $this->partialStub();