Use realpath() to secure file and path names.
[core.git] / inc / classes / main / file_directories / directory / class_FrameworkDirectoryPointer.php
1 <?php
2 /**
3  * A class for directory reading and getting its contents, no recursion!
4  *
5  * @author              Roland Haeder <webmaster@shipsimu.org>
6  * @version             0.0.0
7  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2013 Core Developer Team
8  * @license             GNU GPL 3.0 or any newer version
9  * @link                http://www.shipsimu.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 FrameworkDirectoryPointer extends BaseFrameworkSystem {
25         /**
26          * The current path we are working in
27          */
28         private $pathName = '';
29
30         /**
31          * The directory iterator instance
32          */
33         private $directoryInstance = NULL;
34
35         /**
36          * Protected constructor
37          */
38         protected function __construct () {
39                 // Call parent constructor
40                 parent::__construct(__CLASS__);
41         }
42
43         /**
44          * Destructor for cleaning purposes, etc
45          */
46         public function __destruct() {
47                 // Is there a resource pointer? Then we have to close the directory here!
48                 if ($this->getDirectoryInstance() instanceof DirectoryIterator) {
49                         // Try to close a directory
50                         $this->closeDirectory();
51                 } // END - if
52
53                 // Call the parent destructor
54                 parent::__destruct();
55         }
56
57         /**
58          * Create a directory pointer based on the given path. The path will also
59          * be verified here.
60          *
61          * @param       $pathName               The path name we shall pass to opendir()
62          * @param       $inConstructor  If we are in de/con-structor or from somewhere else
63          * @return      $pointerInstance        A prepared instance of FrameworkDirectoryPointer
64          * @throws      PathIsEmptyException    If the provided path name is empty
65          * @throws      InvalidPathStringException      If the provided path name is not a string
66          * @throws      PathIsNoDirectoryException      If the provided path name is not valid
67          * @throws      PathReadProtectedException      If the provided path name is read-protected
68          * @todo        Get rid of inConstructor, could be old-lost code.
69          */
70         public static final function createFrameworkDirectoryPointer ($pathName, $inConstructor = FALSE) {
71                 // Secure with realpath()
72                 $pathName = realpath($pathName);
73
74                 // Some pre-sanity checks...
75                 if (is_null($pathName)) {
76                         // No pathname given
77                         if ($inConstructor) {
78                                 return NULL;
79                         } else {
80                                 throw new PathIsEmptyException(NULL, self::EXCEPTION_UNEXPECTED_EMPTY_STRING);
81                         }
82                 } elseif (!is_string($pathName)) {
83                         // Is not a string
84                         if ($inConstructor) {
85                                 return NULL;
86                         } else {
87                                 throw new InvalidPathStringException(NULL, self::EXCEPTION_INVALID_STRING);
88                         }
89                 } elseif (!is_dir($pathName)) {
90                         // Not a directory
91                         if ($inConstructor) {
92                                 return NULL;
93                         } else {
94                                 throw new PathIsNoDirectoryException($pathName, self::EXCEPTION_INVALID_PATH_NAME);
95                         }
96                 } elseif (!is_readable($pathName)) {
97                         // Not readable
98                         if ($inConstructor) {
99                                 return NULL;
100                         } else {
101                                 throw new PathReadProtectedException($pathName, self::EXCEPTION_READ_PROTECED_PATH);
102                         }
103                 }
104
105                 // Get an iterator for the directory
106                 $directoryInstance = new DirectoryIterator($pathName);
107
108                 // Create new instance
109                 $pointerInstance = new FrameworkDirectoryPointer();
110
111                 // Set directory pointer and path name
112                 $pointerInstance->setDirectoryInstance($directoryInstance);
113                 $pointerInstance->setPathName($pathName);
114
115                 // Return the instance
116                 return $pointerInstance;
117         }
118
119         /**
120          * Read raw lines of data from a directory pointer and return the data
121          *
122          * @return      $current        Current entry from encapsulated iterator
123          */
124         public function readRawDirectory () {
125                 // Can the next entry be read?
126                 assert($this->getDirectoryInstance()->valid());
127
128                 // Default is FALSE
129                 $current = FALSE;
130
131                 // Is it a dot directory?
132                 if (!$this->getDirectoryInstance()->isDot()) {
133                         // Read data from the directory pointer and return it
134                         $current = $this->getDirectoryInstance()->current();
135                 } // END - if
136
137                 // Advance to next entry
138                 $this->getDirectoryInstance()->next();
139
140                 // Return found entry
141                 return $current;
142         }
143
144         /**
145          * Read lines from the current directory pointer except some parts
146          *
147          * @param       $except         Some parts of a directory we want to ignore. Valid: directory and file names, other values will be silently ignored
148          * @return      string          Directory and/or file names read from the current directory pointer
149          */
150         public function readDirectoryExcept (array $except = array()) {
151                 // No exceptions given?
152                 if (count($except) == 0) {
153                         // No exception given, so read all files and directories, but not recursive
154                         self::createDebugInstance(__CLASS__)->debugOutput('DIRECTORY[' . __METHOD__ . ':' . __LINE__ . ']: No exceptions given, please use readRawDirectory() instead!');
155                         return $this->readRawDirectory();
156                 } // END - if
157
158                 // Read a raw line...
159                 $rawLine = $this->readRawDirectory();
160                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DIRECTORY[' . __METHOD__ . ':' . __LINE__ . ']: rawLine[' . gettype($rawLine) . ']=' . $rawLine);
161
162                 // Shall we exclude directories?
163                 if ((!is_null($rawLine)) && ($rawLine !== FALSE) && (!in_array($rawLine, $except))) {
164                         // Return read data
165                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DIRECTORY[' . __METHOD__ . ':' . __LINE__ . ']: rawLine[' . gettype($rawLine) . ']=' . $rawLine);
166                         return $rawLine;
167                 } elseif ((!is_null($rawLine)) && ($rawLine !== FALSE)) {
168                         // Exclude this part
169                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DIRECTORY[' . __METHOD__ . ':' . __LINE__ . ']: rawline[' . gettype($rawLine) . ']=' . $rawLine . ' - Recursive call!');
170                         return $this->readDirectoryExcept($except);
171                 }
172
173                 // End pointer reached
174                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DIRECTORY[' . __METHOD__ . ':' . __LINE__ . ']: Returning NULL!');
175                 return NULL;
176         }
177
178         /**
179          * Close a directory source and set it's instance to null and the path name
180          * to empty
181          *
182          * @return      void
183          */
184         public function closeDirectory () {
185                 // Close the directory by unsetting it
186                 $this->setDirectoryInstance(NULL);
187                 $this->setPathName('');
188         }
189
190         /**
191          * Setter for the directory pointer
192          *
193          * @param       $directoryInstance      An instanceof a DirectoryIterator class or NULL to unset ("close") it.
194          * @return      void
195          */
196         protected final function setDirectoryInstance (DirectoryIterator $directoryInstance = NULL) {
197                 // Set instance (or NULL)
198                 $this->directoryInstance = $directoryInstance;
199         }
200
201         /**
202          * Getter for the directory pointer
203          *
204          * @return      $directoryInstance      The directory pointer which shall be a valid directory resource
205          */
206         public final function getDirectoryInstance () {
207                 return $this->directoryInstance;
208         }
209
210         /**
211          * Setter for path name
212          *
213          * @param       $pathName       The new path name
214          * @return      void
215          */
216         public final function setPathName ($pathName) {
217                 $pathName = (string) $pathName;
218                 $this->pathName = $pathName;
219         }
220
221         /**
222          * Getter for path name
223          *
224          * @return      $pathName       The current path name
225          */
226         public final function getPathName () {
227                 return $this->pathName;
228         }
229 }
230
231 // [EOF]
232 ?>