3 * An universal class for file input/output streams.
5 * @author Roland Haeder <webmaster@ship-simu.org>
7 * @copyright Copyright (c) 2007, 2008 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 * Protected constructor
28 protected function __construct () {
29 // Call parent constructor
30 parent::__construct(__CLASS__);
33 $this->removeNumberFormaters();
34 $this->removeSystemArray();
38 * Create a file IO stream. This is a class for performing all actions
39 * on files like creating, deleting and loading them.
41 * @return $ioInstance An instance of FileIoStream
43 public final static function createFileIoStream () {
44 // Create new instance
45 $ioInstance = new FileIoStream();
47 // Return the instance
52 * Saves data to a given local file
54 * @param $fileName The file name for the to be saved file
55 * @param $dataArray The data we shall store to the file
57 * @see FileOutputStreamer
59 public final function saveFile ($fileName, $dataArray) {
61 $dirName = ""; $fileInstance = null;
62 for ($idx = 0; $idx < 5; $idx++) {
63 // Get a file output pointer
65 $fileInstance = FrameworkFileOutputPointer::createFrameworkFileOutputPointer($fileName, 'w');
66 } catch (FilePointerNotOpenedException $e) {
67 // Create missing directory
68 $dirName = dirname($fileName);
69 for ($idx2 = 0; $idx2 < (2 - $idx); $idx2++) {
70 $dirName = dirname($dirName);
77 // Write a header information for validation purposes
78 $fileInstance->writeToFile(sprintf("@head^%s:%s:%s:%s\n",
81 strlen($dataArray[1]),
85 // Encode the (maybe) binary stream with Base64
86 $b64Stream = base64_encode($dataArray[1]);
88 // write the data line by line
89 $line = str_repeat(" ", 50); $idx = 0;
90 while (strlen($line) == 50) {
91 // Get 50 chars or less
92 $line = substr($b64Stream, $idx, 50);
94 // Save it to the stream
95 $fileInstance->writeToFile(sprintf("@data^%s:%s\n",
100 // Advance to the next 50-chars block
105 $fileInstance->closeFile();
109 * Reads from a local file
111 * @param $fqfn The full-qualified file-name which we shall load
112 * @return $array An array with the element 'header' and 'data'
113 * @see FileInputStreamer
115 public final function loadFileContents ($fqfn) {
116 // Initialize some variables and arrays
121 $readData = ""; // This will contain our read data
123 // Get a file input handler
124 $fileInstance = FrameworkFileInputPointer::createFrameworkFileInputPointer($fqfn);
126 // Read all it's contents (we very and transparently decompress it below)
127 while ($readRawLine = $fileInstance->readFromFile()) {
128 // Add the read line to the buffer
129 $inputBuffer .= $readRawLine;
131 // Break infinite loop maybe caused by the input handler
132 if ($lastBuffer == $inputBuffer) break;
134 // Remember last read line for avoiding possible infinite loops
135 $lastBuffer = $inputBuffer;
138 // Close directory handle
139 $fileInstance->closeFile();
141 // Convert it into an array
142 $inputBuffer = explode("\n", $inputBuffer);
144 // Now process the read lines and verify it's content
145 foreach ($inputBuffer as $rawLine) {
146 // Trim it a little but not the leading spaces/tab-stops
147 $rawLine = rtrim($rawLine);
150 if (substr($rawLine, 0, 5) == "@head") {
151 // Header found, so let's extract it
152 $header = explode("^", $rawLine);
153 $header = trim($header[1]);
155 // Now we must convert it again into an array
156 $header = explode(":", $header);
158 // Is the header (maybe) valid?
159 if (count($header) != 4) {
160 // Throw an exception
161 throw new InvalidArrayCountException(array($this, 'header', count($header), 4), self::EXCEPTION_ARRAY_HAS_INVALID_COUNT);
163 } elseif (substr($rawLine, 0, 5) == "@data") {
165 $data = explode("^", $rawLine);
168 // First element is the data, second the MD5 checksum
169 $data = explode(":", $data);
171 // Validate the read line
172 if (count($data) == 2) {
173 if (md5($data[0]) != $data[1]) {
174 // MD5 hash did not match!
175 throw new InvalidMD5ChecksumException(array($this, md5($data[0]), $data[1]), self::EXCEPTION_MD5_CHECKSUMS_MISMATCH);
179 throw new InvalidArrayCountException(array($this, "data", count($data), 2), self::EXCEPTION_ARRAY_HAS_INVALID_COUNT);
182 // Add this to the readData string
183 $readData .= $data[0];
185 // Other raw lines than header/data tagged lines and re-add the new-line char
186 $readData .= $rawLine."\n";
190 // Was raw lines read and no header/data?
191 if ((!empty($readData)) && (count($header) == 0) && (count($data) == 0)) {
192 // Return raw lines back
196 // Was a header found?
197 if (count($header) != 4) {
198 // Throw an exception
199 throw new InvalidArrayCountException(array($this, 'header', count($header), 4), self::EXCEPTION_ARRAY_HAS_INVALID_COUNT);
202 // Decode all from Base64
203 $readData = @base64_decode($readData);
205 // Does the size match?
206 if (strlen($readData) != $header[2]) {
207 // Size did not match
208 throw new InvalidDataLengthException(array($this, strlen($readData), $header[2]), self::EXCEPTION_UNEXPECTED_STRING_SIZE);
211 // Validate the decoded data with the final MD5 hash
212 if (md5($readData) != $header[3]) {
213 // MD5 hash did not match!
214 throw new InvalidMD5ChecksumException(array($this, md5($readData), $header[3]), self::EXCEPTION_MD5_CHECKSUMS_MISMATCH);
217 // Return all in an array