0eff6c5a9c3923e17e23f3f235f82a537e46efa6
[core.git] / inc / classes / main / io / class_FileIoStream.php
1 <?php
2 /**
3  * An universal class for file input/output streams.
4  *
5  * @author              Roland Haeder <webmaster@ship-simu.org>
6  * @version             0.0.0
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
10  *
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.
15  *
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.
20  *
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/>.
23  */
24 class FileIoStream extends BaseFrameworkSystem implements FileInputStreamer, FileOutputStreamer {
25         /**
26          * Protected constructor
27          */
28         protected function __construct () {
29                 // Call parent constructor
30                 parent::__construct(__CLASS__);
31
32                 // Clean-up a little
33                 $this->removeNumberFormaters();
34                 $this->removeSystemArray();
35         }
36
37         /**
38          * Create a file IO stream. This is a class for performing all actions
39          * on files like creating, deleting and loading them.
40          *
41          * @return      $ioInstance     An instance of FileIoStream
42          */
43         public final static function createFileIoStream () {
44                 // Create new instance
45                 $ioInstance = new FileIoStream();
46
47                 // Return the instance
48                 return $ioInstance;
49         }
50
51         /**
52          * Saves data to a given local file
53          *
54          * @param               $fileName               The file name for the to be saved file
55          * @param               $dataArray      The data we shall store to the file
56          * @return      void
57          * @see         FileOutputStreamer
58          */
59         public final function saveFile ($fileName, $dataArray) {
60                 // Try it five times
61                 $dirName = ""; $fileInstance = null;
62                 for ($idx = 0; $idx < 5; $idx++) {
63                         // Get a file output pointer
64                         try {
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);
71                                 }
72                                 // Try to create it
73                                 @mkdir($dirName);
74                         }
75                 }
76
77                 // Write a header information for validation purposes
78                 $fileInstance->writeToFile(sprintf("@head^%s:%s:%s:%s\n",
79                         $dataArray[0],
80                         time(),
81                         strlen($dataArray[1]),
82                         md5($dataArray[1])
83                 ));
84
85                 // Encode the (maybe) binary stream with Base64
86                 $b64Stream = base64_encode($dataArray[1]);
87
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);
93
94                         // Save it to the stream
95                         $fileInstance->writeToFile(sprintf("@data^%s:%s\n",
96                                 $line,
97                                 md5($line)
98                         ));
99
100                         // Advance to the next 50-chars block
101                         $idx += 50;
102                 }
103
104                 // Close the file
105                 $fileInstance->closeFile();
106         }
107
108         /**
109          * Reads from a local file
110          *
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
114          */
115         public final function loadFileContents ($fqfn) {
116                 // Initialize some variables and arrays
117                 $inputBuffer = "";
118                 $lastBuffer = "";
119                 $header = array();
120                 $data = array();
121                 $readData = ""; // This will contain our read data
122
123                 // Get a file input handler
124                 $fileInstance = FrameworkFileInputPointer::createFrameworkFileInputPointer($fqfn);
125
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;
130
131                         // Break infinite loop maybe caused by the input handler
132                         if ($lastBuffer == $inputBuffer) break;
133
134                         // Remember last read line for avoiding possible infinite loops
135                         $lastBuffer = $inputBuffer;
136                 }
137
138                 // Close directory handle
139                 $fileInstance->closeFile();
140
141                 // Convert it into an array
142                 $inputBuffer = explode("\n", $inputBuffer);
143
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);
148
149                         // Analyze this line
150                         if (substr($rawLine, 0, 5) == "@head") {
151                                 // Header found, so let's extract it
152                                 $header = explode("^", $rawLine);
153                                 $header = trim($header[1]);
154
155                                 // Now we must convert it again into an array
156                                 $header = explode(":", $header);
157
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);
162                                 }
163                         } elseif (substr($rawLine, 0, 5) == "@data") {
164                                 // Is a data line!
165                                 $data = explode("^", $rawLine);
166                                 $data = $data[1];
167
168                                 // First element is the data, second the MD5 checksum
169                                 $data = explode(":", $data);
170
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);
176                                         }
177                                 } else {
178                                         // Invalid count!
179                                         throw new InvalidArrayCountException(array($this, "data", count($data), 2), self::EXCEPTION_ARRAY_HAS_INVALID_COUNT);
180                                 }
181
182                                 // Add this to the readData string
183                                 $readData .= $data[0];
184                         } else {
185                                 // Other raw lines than header/data tagged lines and re-add the new-line char
186                                 $readData .= $rawLine."\n";
187                         }
188                 }
189
190                 // Was raw lines read and no header/data?
191                 if ((!empty($readData)) && (count($header) == 0) && (count($data) == 0)) {
192                         // Return raw lines back
193                         return $readData;
194                 }
195
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);
200                 }
201
202                 // Decode all from Base64
203                 $readData = @base64_decode($readData);
204
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);
209                 }
210
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);
215                 }
216
217                 // Return all in an array
218                 return array(
219                         'header' => $header,
220                         'data'   => $readData
221                 );
222         }
223 }
224
225 // [EOF]
226 ?>