source-class-Com.Tecnick.File.File

It appears that you are using AdBlocking software. The cost of running this website is covered by advertisements. If you like it please feel free to a small amount of money to secure the future of this website.
  1: <?php
  2: /**
  3:  * File.php
  4:  *
  5:  * @since       2015-07-28
  6:  * @category    Library
  7:  * @package     File
  8:  * @author      Nicola Asuni <info@tecnick.com>
  9:  * @copyright   2015-2015 Nicola Asuni - Tecnick.com LTD
 10:  * @license     http://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE.TXT)
 11:  * @link        https://github.com/tecnickcom/tc-lib-file
 12:  *
 13:  * This file is part of tc-lib-file software library.
 14:  */
 15: 
 16: namespace Com\Tecnick\File;
 17: 
 18: use \Com\Tecnick\File\Exception as FileException;
 19: 
 20: /**
 21:  * Com\Tecnick\File\File
 22:  *
 23:  * Function to read byte-level data
 24:  *
 25:  * @since       2015-07-28
 26:  * @category    Library
 27:  * @package     File
 28:  * @author      Nicola Asuni <info@tecnick.com>
 29:  * @copyright   2015-2015 Nicola Asuni - Tecnick.com LTD
 30:  * @license     http://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE.TXT)
 31:  * @link        https://github.com/tecnickcom/tc-lib-file
 32:  */
 33: class File
 34: {
 35:     /**
 36:      * Wrapper to use fopen only with local files
 37:      *
 38:      * @param string $filename Name of the file to open
 39:      * @param string $mode     The fopen mode parameter specifies the type of access you require to the stream
 40:      *
 41:      * @return Returns a file pointer resource on success
 42:      *
 43:      * @throws FileException in case of error
 44:      */
 45:     public function fopenLocal($filename, $mode)
 46:     {
 47:         if (strpos($filename, '://') === false) {
 48:             $filename = 'file://'.$filename;
 49:         } elseif (strpos($filename, 'file://') !== 0) {
 50:             throw new FileException('this is not a local file');
 51:         }
 52:         $handler = @fopen($filename, $mode);
 53:         if ($handler === false) {
 54:             throw new FileException('unable to open the file: '.$filename);
 55:         }
 56:         return $handler;
 57:     }
 58: 
 59:     /**
 60:      * Read a 4-byte (32 bit) integer from file.
 61:      *
 62:      * @param resource $handle A file system pointer resource that is typically created using fopen().
 63:      *
 64:      * @return 4-byte integer
 65:      */
 66:     public function fReadInt($handle)
 67:     {
 68:         $val = unpack('Ni', fread($handle, 4));
 69:         return $val['i'];
 70:     }
 71: 
 72:     /**
 73:      * Binary-safe file read.
 74:      * Reads up to length bytes from the file pointer referenced by handle.
 75:      * Reading stops as soon as one of the following conditions is met:
 76:      * length bytes have been read; EOF (end of file) is reached.
 77:      *
 78:      * @param resource $handle A file system pointer resource that is typically created using fopen().
 79:      * @param int      $length Number of bytes to read.
 80:      *
 81:      * @return string
 82:      *
 83:      * @throws FileException in case of error
 84:      */
 85:     public function rfRead($handle, $length)
 86:     {
 87:         $data = @fread($handle, $length);
 88:         if ($data === false) {
 89:             throw new FileException('unable to read the file');
 90:         }
 91:         $rest = ($length - strlen($data));
 92:         if (($rest > 0) && !feof($handle)) {
 93:             $stream_meta_data = stream_get_meta_data($handle);
 94:             if ($stream_meta_data['unread_bytes'] > 0) {
 95:                 $data .= $this->rfRead($handle, $rest);
 96:             }
 97:         }
 98:         return $data;
 99:     }
100: 
101:     /**
102:      * Reads entire file into a string.
103:      * The file can be also an URL.
104:      *
105:      * @param string $file Name of the file or URL to read.
106:      *
107:      * @return string File content
108:      */
109:     public function fileGetContents($file)
110:     {
111:         $alt = $this->getAltFilePaths($file);
112:         foreach ($alt as $path) {
113:             $ret = $this->getFileData($path);
114:             if ($ret !== false) {
115:                 return $ret;
116:             }
117:         }
118:         throw new FileException('unable to read the file: '.$file);
119:     }
120: 
121:     /**
122:      * Reads entire file into a string.
123:      * The file can be also an URL if the URL wrappers are enabled.
124:      *
125:      * @param string $file Name of the file or URL to read.
126:      *
127:      * @return string File content or FALSE in case the file is unreadable
128:      */
129:     public function getFileData($file)
130:     {
131:         $ret = @file_get_contents($file);
132:         if ($ret !== false) {
133:             return $ret;
134:         }
135:         // try to use CURL for URLs
136:         return $this->getUrlData($file);
137:     }
138: 
139:     /**
140:      * Reads entire remote file into a string using CURL
141:      *
142:      * @param string $url URL to read.
143:      *
144:      * @return string File content or FALSE in case the file is unreadable or curl is not available
145:      */
146:     public function getUrlData($url)
147:     {
148:         if ((ini_get('allow_url_fopen') && !defined('FORCE_CURL'))
149:             || !function_exists('curl_init')
150:             || !preg_match('%^(https?|ftp)://%', $url)
151:         ) {
152:             return false;
153:         }
154:         // try to get remote file data using cURL
155:         $crs = curl_init();
156:         curl_setopt($crs, CURLOPT_URL, $url);
157:         curl_setopt($crs, CURLOPT_BINARYTRANSFER, true);
158:         curl_setopt($crs, CURLOPT_FAILONERROR, true);
159:         curl_setopt($crs, CURLOPT_RETURNTRANSFER, true);
160:         if ((ini_get('open_basedir') == '') && (!ini_get('safe_mode'))) {
161:             curl_setopt($crs, CURLOPT_FOLLOWLOCATION, true);
162:         }
163:         curl_setopt($crs, CURLOPT_CONNECTTIMEOUT, 5);
164:         curl_setopt($crs, CURLOPT_TIMEOUT, 30);
165:         curl_setopt($crs, CURLOPT_SSL_VERIFYPEER, false);
166:         curl_setopt($crs, CURLOPT_SSL_VERIFYHOST, false);
167:         curl_setopt($crs, CURLOPT_USERAGENT, 'tc-lib-file');
168:         $ret = curl_exec($crs);
169:         curl_close($crs);
170:         return $ret;
171:     }
172: 
173:     /**
174:      * Returns an array of possible alternative file paths or URLs
175:      *
176:      * @param string $file Name of the file or URL to read.
177:      *
178:      * @return array
179:      */
180:     public function getAltFilePaths($file)
181:     {
182:         $alt = array($file);
183:         $alt[] = $this->getAltLocalUrlPath($file);
184:         $url = $this->getAltMissingUrlProtocol($file);
185:         $alt[] = $url;
186:         $alt[] = $this->getAltPathFromUrl($url);
187:         $alt[] = $this->getAltUrlFromPath($file);
188:         return array_unique($alt);
189:     }
190: 
191:     /**
192:      * Replace URL relative path with full real server path
193:      *
194:      * @param string $path Relative URL path
195:      *
196:      * @return string
197:      */
198:     protected function getAltLocalUrlPath($file)
199:     {
200:         if ((strlen($file) > 1)
201:             && ($file[0] === '/')
202:             && ($file[1] !== '/')
203:             && !empty($_SERVER['DOCUMENT_ROOT'])
204:             && ($_SERVER['DOCUMENT_ROOT'] !== '/')
205:         ) {
206:             $findroot = strpos($file, $_SERVER['DOCUMENT_ROOT']);
207:             if (($findroot === false) || ($findroot > 1)) {
208:                 $file = htmlspecialchars_decode(urldecode($_SERVER['DOCUMENT_ROOT'].$file));
209:             }
210:         }
211:         return $file;
212:     }
213: 
214:     /**
215:      * Add missing local URL protocol
216:      *
217:      * @param string $file Relative URL path
218:      *
219:      * @return string local path or original $file
220:      */
221:     protected function getAltMissingUrlProtocol($file)
222:     {
223:         if (preg_match('%^//%', $file) && !empty($_SERVER['HTTP_HOST'])) {
224:             $file = $this->getDefaultUrlProtocol().':'.str_replace(' ', '%20', $file);
225:         }
226:         return htmlspecialchars_decode($file);
227:     }
228: 
229:     /**
230:      * Get the default URL protocol (http or https)
231:      *
232:      * @return string
233:      */
234:     protected function getDefaultUrlProtocol()
235:     {
236:         $protocol = 'http';
237:         if (!empty($_SERVER['HTTPS']) && (strtolower($_SERVER['HTTPS']) != 'off')) {
238:             $protocol .= 's';
239:         }
240:         return $protocol;
241:     }
242: 
243:     /**
244:      * Add missing local URL protocol
245:      *
246:      * @param string $file Relative URL path
247:      *
248:      * @return string local path or original $file
249:      */
250:     protected function getAltPathFromUrl($url)
251:     {
252:         if (!preg_match('%^(https?)://%', $url)
253:             || empty($_SERVER['HTTP_HOST'])
254:             || empty($_SERVER['DOCUMENT_ROOT'])
255:         ) {
256:             return $url;
257:         }
258:         $urldata = parse_url($url);
259:         if (!empty($urldata['query'])) {
260:             return $url;
261:         }
262:         $host = $this->getDefaultUrlProtocol().'://'.$_SERVER['HTTP_HOST'];
263:         if (strpos($url, $host) === 0) {
264:             // convert URL to full server path
265:             $tmp = str_replace($host, $_SERVER['DOCUMENT_ROOT'], $url);
266:             return htmlspecialchars_decode(urldecode($tmp));
267:         }
268:         return $url;
269:     }
270: 
271:     /**
272:      * Get an alternate URL from a file path
273:      *
274:      * @param string $file File name and path
275:      *
276:      * @return string
277:      */
278:     protected function getAltUrlFromPath($file)
279:     {
280:         if (isset($_SERVER['SCRIPT_URI'])
281:             && !preg_match('%^(https?|ftp)://%', $file)
282:             && !preg_match('%^//%', $file)
283:         ) {
284:             $urldata = @parse_url($_SERVER['SCRIPT_URI']);
285:             return $urldata['scheme'].'://'.$urldata['host'].(($file[0] == '/') ? '' : '/').$file;
286:         }
287:         return $file;
288:     }
289: }
290: 
 

© 2004-2017 – Nicola Asuni - Tecnick.com - All rights reserved.
about - disclaimer - privacy