3 * An universal class for file input/output streams.
5 * @author Roland Haeder <webmaster@ship-simu.org>
7 * @copyright Copyright (c) 2007 - 2009 Roland Haeder, this is free software
8 * @license GNU GPL 3.0 or any newer version
9 * @link http://www.ship-simu.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 private $fileHeader = '@head';
31 * Data block indicator
33 private $dataBlock = '@data';
38 private $chunker = ':';
43 private $seperator = '^';
46 * Protected constructor
48 protected function __construct () {
49 // Call parent constructor
50 parent::__construct(__CLASS__);
53 $this->removeNumberFormaters();
54 $this->removeSystemArray();
58 * Create a file IO stream. This is a class for performing all actions
59 * on files like creating, deleting and loading them.
61 * @return $ioInstance An instance of FileIoStream
63 public final static function createFileIoStream () {
64 // Create new instance
65 $ioInstance = new FileIoStream();
67 // Return the instance
72 * Saves data to a given local file and create missing directory structures
74 * @param $fileName The file name for the to be saved file
75 * @param $dataArray The data we shall store to the file
77 * @see FileOutputStreamer
78 * @todo This method needs heavy rewrite
80 public final function saveFile ($fileName, $dataArray) {
82 $dirName = ''; $fileInstance = null;
83 for ($idx = 0; $idx < 5; $idx++) {
84 // Get a file output pointer
86 $fileInstance = FrameworkFileOutputPointer::createFrameworkFileOutputPointer($fileName, 'w');
87 } catch (FilePointerNotOpenedException $e) {
88 // Create missing directory
89 $dirName = dirname($fileName);
90 for ($idx2 = 0; $idx2 < (2 - $idx); $idx2++) {
91 $dirName = dirname($dirName);
99 // Write a header information for validation purposes
100 $fileInstance->writeToFile(sprintf("%s%s%s%s%s%s%s%s%s\n",
107 strlen($dataArray[1]),
112 // Encode the (maybe) binary stream with Base64
113 $b64Stream = base64_encode($dataArray[1]);
115 // write the data line by line
116 $line = str_repeat(' ', 50); $idx = 0;
117 while (strlen($line) == 50) {
118 // Get 50 chars or less
119 $line = substr($b64Stream, $idx, 50);
121 // Save it to the stream
122 $fileInstance->writeToFile(sprintf("%s%s%s%s%s\n",
130 // Advance to the next 50-chars block
135 $fileInstance->closeFile();
139 * Reads from a local file
141 * @param $fqfn The full-qualified file-name which we shall load
142 * @return $array An array with the element 'header' and 'data'
143 * @see FileInputStreamer
145 public final function loadFileContents ($fqfn) {
146 // Initialize some variables and arrays
151 $readData = ''; // This will contain our read data
153 // Get a file input handler
154 $fileInstance = FrameworkFileInputPointer::createFrameworkFileInputPointer($fqfn);
156 // Read all it's contents (we very and transparently decompress it below)
157 while ($readRawLine = $fileInstance->readFromFile()) {
158 // Add the read line to the buffer
159 $inputBuffer .= $readRawLine;
161 // Break infinite loop maybe caused by the input handler
162 if ($lastBuffer == $inputBuffer) break;
164 // Remember last read line for avoiding possible infinite loops
165 $lastBuffer = $inputBuffer;
168 // Close directory handle
169 $fileInstance->closeFile();
171 // Convert it into an array
172 $inputBuffer = explode("\n", $inputBuffer);
174 // Now process the read lines and verify it's content
175 foreach ($inputBuffer as $rawLine) {
176 // Trim it a little but not the leading spaces/tab-stops
177 $rawLine = rtrim($rawLine);
180 if (substr($rawLine, 0, 5) == $this->fileHeader) {
181 // Header found, so let's extract it
182 $header = explode($this->seperator, $rawLine);
183 $header = trim($header[1]);
185 // Now we must convert it again into an array
186 $header = explode($this->chunker, $header);
188 // Is the header (maybe) valid?
189 if (count($header) != 4) {
190 // Throw an exception
191 throw new InvalidArrayCountException(array($this, 'header', count($header), 4), self::EXCEPTION_ARRAY_HAS_INVALID_COUNT);
193 } elseif (substr($rawLine, 0, 5) == $this->dataBlock) {
195 $data = explode($this->seperator, $rawLine);
198 // First element is the data, second the MD5 checksum
199 $data = explode($this->chunker, $data);
201 // Validate the read line
202 if (count($data) == 2) {
203 if (md5($data[0]) != $data[1]) {
204 // MD5 hash did not match!
205 throw new InvalidMD5ChecksumException(array($this, md5($data[0]), $data[1]), self::EXCEPTION_MD5_CHECKSUMS_MISMATCH);
209 throw new InvalidArrayCountException(array($this, "data", count($data), 2), self::EXCEPTION_ARRAY_HAS_INVALID_COUNT);
212 // Add this to the readData string
213 $readData .= $data[0];
215 // Other raw lines than header/data tagged lines and re-add the new-line char
216 $readData .= $rawLine . "\n";
220 // Was raw lines read and no header/data?
221 if ((!empty($readData)) && (count($header) == 0) && (count($data) == 0)) {
222 // Return raw lines back
226 // Was a header found?
227 if (count($header) != 4) {
228 // Throw an exception
229 throw new InvalidArrayCountException(array($this, 'header', count($header), 4), self::EXCEPTION_ARRAY_HAS_INVALID_COUNT);
232 // Decode all from Base64
233 $readData = @base64_decode($readData);
235 // Does the size match?
236 if (strlen($readData) != $header[2]) {
237 // Size did not match
238 throw new InvalidDataLengthException(array($this, strlen($readData), $header[2]), self::EXCEPTION_UNEXPECTED_STRING_SIZE);
241 // Validate the decoded data with the final MD5 hash
242 if (md5($readData) != $header[3]) {
243 // MD5 hash did not match!
244 throw new InvalidMD5ChecksumException(array($this, md5($readData), $header[3]), self::EXCEPTION_MD5_CHECKSUMS_MISMATCH);
247 // Return all in an array