3 * An universal class for file input/output streams.
5 * @author Roland Haeder <webmaster@mxchange.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__);
32 // Set part description
33 $this->setObjectDescription("Universal file I/O stream system");
36 $this->createUniqueID();
39 $this->removeNumberFormaters();
40 $this->removeSystemArray();
44 * Create a file IO stream. This is a class for performing all actions
45 * on files like creating, deleting and loading them.
47 * @return $ioInstance An instance of FileIoStream
49 public final static function createFileIoStream () {
50 // Create new instance
51 $ioInstance = new FileIoStream();
53 // Return the instance
58 * Saves data to a given local file
60 * @param $fileName The file name for the to be saved file
61 * @param $dataArray The data we shall store to the file
63 * @see FileOutputStreamer
65 public final function saveFile ($fileName, $dataArray) {
67 $dirName = ""; $fileInstance = null;
68 for ($idx = 0; $idx < 5; $idx++) {
69 // Get a file output pointer
71 $fileInstance = FrameworkFileOutputPointer::createFrameworkFileOutputPointer($fileName, 'w');
72 } catch (FilePointerNotOpenedException $e) {
73 // Create missing directory
74 $dirName = dirname($fileName);
75 for ($idx2 = 0; $idx2 < (2 - $idx); $idx2++) {
76 $dirName = dirname($dirName);
83 // Write a header information for validation purposes
84 $fileInstance->writeToFile(sprintf("@head^%s:%s:%s:%s\n",
87 strlen($dataArray[1]),
91 // Encode the (maybe) binary stream with Base64
92 $b64Stream = base64_encode($dataArray[1]);
94 // write the data line by line
95 $line = str_repeat(" ", 50); $idx = 0;
96 while (strlen($line) == 50) {
97 // Get 50 chars or less
98 $line = substr($b64Stream, $idx, 50);
100 // Save it to the stream
101 $fileInstance->writeToFile(sprintf("@data^%s:%s\n",
106 // Advance to the next 50-chars block
111 $fileInstance->closeFile();
115 * Reads from a local file
117 * @param $fqfn The full-qualified file-name which we shall load
118 * @return $array An array with the element 'header' and 'data'
119 * @see FileInputStreamer
121 public final function loadFileContents ($fqfn) {
122 // Initialize some variables and arrays
127 $readData = ""; // This will contain our read data
129 // Get a file input handler
130 $fileInstance = FrameworkFileInputPointer::createFrameworkFileInputPointer($fqfn);
132 // Read all it's contents (we very and transparently decompress it below)
133 while ($readRawLine = $fileInstance->readFromFile()) {
134 // Add the read line to the buffer
135 $inputBuffer .= $readRawLine;
137 // Break infinite loop maybe caused by the input handler
138 if ($lastBuffer == $inputBuffer) break;
140 // Remember last read line for avoiding possible infinite loops
141 $lastBuffer = $inputBuffer;
144 // Close directory handle
145 $fileInstance->closeFile();
147 // Convert it into an array
148 $inputBuffer = explode("\n", $inputBuffer);
150 // Now process the read lines and verify it's content
151 foreach ($inputBuffer as $rawLine) {
152 // Trim it a little but not the leading spaces/tab-stops
153 $rawLine = rtrim($rawLine);
156 if (substr($rawLine, 0, 5) == "@head") {
157 // Header found, so let's extract it
158 $header = explode("^", $rawLine);
159 $header = trim($header[1]);
161 // Now we must convert it again into an array
162 $header = explode(":", $header);
164 // Is the header (maybe) valid?
165 if (count($header) != 4) {
166 // Throw an exception
167 throw new InvalidArrayCountException(array($this, "header", count($header), 4), self::EXCEPTION_ARRAY_HAS_INVALID_COUNT);
169 } elseif (substr($rawLine, 0, 5) == "@data") {
171 $data = explode("^", $rawLine);
174 // First element is the data, second the MD5 checksum
175 $data = explode(":", $data);
177 // Validate the read line
178 if (count($data) == 2) {
179 if (md5($data[0]) != $data[1]) {
180 // MD5 hash did not match!
181 throw new InvalidMD5ChecksumException(array($this, md5($data[0]), $data[1]), self::EXCEPTION_MD5_CHECKSUMS_MISMATCH);
185 throw new InvalidArrayCountException(array($this, "data", count($data), 2), self::EXCEPTION_ARRAY_HAS_INVALID_COUNT);
188 // Add this to the readData string
189 $readData .= $data[0];
191 // Other raw lines than header/data tagged lines and re-add the new-line char
192 $readData .= $rawLine."\n";
196 // Was raw lines read and no header/data?
197 if ((!empty($readData)) && (count($header) == 0) && (count($data) == 0)) {
198 // Return raw lines back
202 // Was a header found?
203 if (count($header) != 4) {
204 // Throw an exception
205 throw new InvalidArrayCountException(array($this, "header", count($header), 4), self::EXCEPTION_ARRAY_HAS_INVALID_COUNT);
208 // Decode all from Base64
209 $readData = @base64_decode($readData);
211 // Does the size match?
212 if (strlen($readData) != $header[2]) {
213 // Size did not match
214 throw new InvalidDataLengthException(array($this, strlen($readData), $header[2]), self::EXCEPTION_UNEXPECTED_STRING_SIZE);
217 // Validate the decoded data with the final MD5 hash
218 if (md5($readData) != $header[3]) {
219 // MD5 hash did not match!
220 throw new InvalidMD5ChecksumException(array($this, md5($readData), $header[3]), self::EXCEPTION_MD5_CHECKSUMS_MISMATCH);
223 // Return all in an array