This is the API documentation for concrete5 version 5.6 and earlier. View Current API Documentation
  1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35  36  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51  52  53  54  55  56  57  58  59  60  61  62  63  64  65  66  67  68  69  70  71  72  73  74  75  76  77  78  79  80  81  82  83  84  85  86  87  88  89  90  91  92  93  94  95  96  97  98  99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 
<?php

/**
 * File helper
 * 
 * Functions useful for working with files and directories.
 * 
 * Used as follows:
 * <code>
 * $file = Loader::helper('file');
 * $path = 'http://www.concrete5.org/tools/get_latest_version_number';
 * $contents = $file->getContents($path);
 * echo $contents;
 * </code> 
 *
 * @package Helpers
 * @category Concrete
 * @author Andrew Embler <[email protected]>
 * @copyright  Copyright (c) 2003-2008 Concrete5. (http://www.concrete5.org)
 * @license    http://www.concrete5.org/license/     MIT License
 */

defined('C5_EXECUTE') or die("Access Denied.");
class Concrete5_Helper_File {

    public function getDirectoryContents($dir, $ignoreFilesArray = array(), $recursive = false) {
        $env = Environment::get();
        return $env->getDirectoryContents($dir, $ignoreFilesArray, $recursive);
    }
    
    /** 
     * Removes the extension of a filename, uncamelcases it.
     * @param string $filename
     * @return string
     */ 
    public function unfilename($filename) {
        // removes the extension and makes it look nice
        $txt = Loader::helper('text');
        return substr($txt->unhandle($filename), 0, strrpos($filename, '.'));
    }
    
    /** 
     * Recursively copies all items in the source directory or file to the target directory
     * @param string $source Source to copy
     * @param string $target Place to copy the source
     * @param int $mode What to chmod the file to
     */
    public function copyAll($source, $target, $mode = NULL) {
        if (is_dir($source)) {
            if($mode == null) {
                @mkdir($target, DIRECTORY_PERMISSIONS_MODE);
                @chmod($target, DIRECTORY_PERMISSIONS_MODE);
            } else { 
                @mkdir($target, $mode);
                @chmod($target, $mode);
            }
            
            
            $d = dir($source);
            while (FALSE !== ($entry = $d->read())) {
                if (substr($entry, 0, 1) === '.') {
                    continue;
                }
            
                $Entry = $source . '/' . $entry;            
                if (is_dir($Entry)) {
                    $this->copyAll($Entry, $target . '/' . $entry, $mode);
                    continue;
                }

                copy($Entry, $target . '/' . $entry);
                if($mode == null) {
                    @chmod($target . '/' . $entry, $this->getCreateFilePermissions($target)->file);
                } else {
                    @chmod($target . '/' . $entry, $mode);
                }
            }
            
            $d->close();
        } else {
            if ($mode == null) {
                $mode = $this->getCreateFilePermissions(dirname($target))->file;
            }
            copy($source, $target);
            chmod($target, $mode);
        }
    }

    /** 
     * Removes all files from within a specified directory
     * @param string $source Directory
     */
    public function removeAll($source) {
        $r = @glob($source);
        if (is_array($r)) {
            foreach($r as $file) {
                if (is_dir($file)) {
                    $this->removeAll("$file/*");
                    rmdir($file);
                } else {
                    unlink($file);
                }
            }
        }
    }

    /** 
     * Takes a path to a file and sends it to the browser, streaming it, and closing the HTTP connection afterwards. Basically a force download method
     * @param stings $file
     */
    public function forceDownload($file) {
        session_write_close();
        ob_clean();
        header('Content-type: application/octet-stream');
        $filename = basename($file);
        header("Content-Disposition: attachment; filename=\"$filename\"");
        header('Content-Length: ' . filesize($file));
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Cache-Control: private",false);
        header("Content-Transfer-Encoding: binary");
        header("Content-Encoding: plainbinary");  
        
        // This code isn't ready yet. It will allow us to no longer force download
        
        /*
        $h = Loader::helper('mime');
        $mimeType = $h->mimeFromExtension($this->getExtension($file));
        header('Content-type: ' . $mimeType);
        */
        
    
        $buffer = '';
        $chunk = 1024*1024;
        $handle = fopen($file, 'rb');
        if ($handle === false) {
            return false;
        }
        while (!feof($handle)) {
            $buffer = fread($handle, $chunk);
            print $buffer;
        }
        
        fclose($handle);
        exit;       
    }
    
    /** 
     * Returns the full path to the temporary directory
     * @return string
     */
    public function getTemporaryDirectory() {
        if (defined('DIR_TMP')) {
            return DIR_TMP;
        }
        
        if (!is_dir(DIR_BASE . '/files/tmp')) { 
            @mkdir(DIR_BASE . '/files/tmp', DIRECTORY_PERMISSIONS_MODE);
            @chmod(DIR_BASE . '/files/tmp', DIRECTORY_PERMISSIONS_MODE);
            @touch(DIR_BASE . '/files/tmp/index.html');
        }

        if (is_dir(DIR_BASE . '/files/tmp') && is_writable(DIR_BASE . '/files/tmp')) {
            return DIR_BASE . '/files/tmp';
        }

        if ($temp=getenv('TMP')) {
            return $temp;
        }
        if ($temp=getenv('TEMP')) {
            return $temp;
        }
        if ($temp=getenv('TMPDIR')) {
            return $temp;
        }
        
        $temp=tempnam(__FILE__,'');
        if (file_exists($temp)) {
            unlink($temp);
            return dirname($temp);
        }
    }

    
    /**
     * Adds content to a new line in a file. If a file is not there it will be created
     * @param string $filename
     * @param string $content
     * @return {@link http://php.net/manual/en/function.file-put-contents.php#refsect1-function.file-put-contents-returnvalues}
     */
    public function append($filename, $content) {
        return file_put_contents($filename, $content, FILE_APPEND);
    }
    
    
    /**
     * Just a consistency wrapper for file_get_contents
     * Should use curl if it exists and fopen isn't allowed (thanks Remo)
     * @param string $filename
     * @param string $timeout
     * @return string $contents
     */
    public function getContents($file, $timeout = 5) {
        $url = @parse_url($file);
        if (isset($url['scheme']) && isset($url['host'])) {
            if (ini_get('allow_url_fopen')) {
                $ctx = stream_context_create(array( 
                    'http' => array( 'timeout' => $timeout ) 
                )); 
                if ($contents = @file_get_contents($file, 0, $ctx)) {
                    return $contents;
                }
            }
            
            if (function_exists('curl_init')) {
                $curl_handle = curl_init();
            
                // Check to see if there are proxy settings
                if (Config::get('HTTP_PROXY_HOST') != null) {
                    @curl_setopt($curl_handle, CURLOPT_PROXY, Config::get('HTTP_PROXY_HOST'));
                    @curl_setopt($curl_handle, CURLOPT_PROXYPORT, Config::get('HTTP_PROXY_PORT'));

                    // Check if there is a username/password to access the proxy
                    if (Config::get('HTTP_PROXY_USER') != null) {
                        @curl_setopt($curl_handle, CURLOPT_PROXYUSERPWD, Config::get('HTTP_PROXY_USER') . ':' . Config::get('HTTP_PROXY_PWD'));
                    }
                }

                curl_setopt($curl_handle, CURLOPT_URL, $file);
                curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, $timeout);
                curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($curl_handle, CURLOPT_SSL_VERIFYPEER, false);
                $contents = curl_exec($curl_handle);
                $http_code = curl_getinfo($curl_handle, CURLINFO_HTTP_CODE);
                curl_close($curl_handle);
                if ($http_code == 404) {    
                    return false;
                }
                
                return $contents;
            }
        } else {
            if ($contents = @file_get_contents($file)) {
                return $contents;
            }
        }
        
        return false;
    }
    
    /** 
     * Removes contents of the file
     * @param $filename
     * @return {@link http://php.net/manual/en/function.file-put-contents.php#refsect1-function.file-put-contents-returnvalues}
     */
    public function clear($file) {
        return file_put_contents($file, '');
    }
    
    
    /** 
     * Cleans up a filename and returns the cleaned up version
     * @param string $file
     * @return string @file
     */
    public function sanitize($file) {
        // Let's build an ASCII-only version of name, to avoid filesystem-specific encoding issues.
        $asciiName = Loader::helper('text')->asciify($file);
        // Let's keep only letters, numbers, underscore and dots.
        $asciiName = trim(preg_replace(array("/[\\s]/", "/[^0-9A-Z_a-z-.]/"), array("_", ""), $asciiName));
        // Trim underscores at start and end
        $asciiName = trim($asciiName, '_');
        if(!strlen(str_replace('.', '', $asciiName))) {
            // If the resulting name is empty (or we have only dots in it)
            $asciiName = md5($file);
        } 
        elseif(preg_match('/^\.\w+$/', $asciiName)) {
            // If the resulting name is only composed by the file extension
            $asciiName = md5($file) . $asciiName;
        }
        return $asciiName;
    }
    
    /** 
    * Returns the extension for a file name
    * @param string $filename
    * @return string $extension
    */
    public function getExtension($filename) {
        $extension = end(explode(".",$filename));
        return $extension;
    }
    
    /** 
     * Takes a path and replaces the files extension in that path with the specified extension
     * @param string $filename
     * @param string $extension
     * @return string $newFileName
     */
    public function replaceExtension($filename, $extension) {
        $newFileName = substr($filename, 0, strrpos($filename, '.')) . '.' . $extension;
        return $newFileName;
    }
    
    
    /**
     * returns an object with two permissions modes (octal):
     * one for files: $res->file
     * and another for directories: $res->dir
     * @param string $path (optional)
     * @return StdClass
     */
    public function getCreateFilePermissions($path = NULL) {
        try {
            if(!isset($path)) {
                $path = DIR_BASE."/files";
            }
            
            if(!is_dir($path)) {
                $path = @dirname($path);
            }
            $perms = @fileperms($path);
            
            if(!$perms) { throw new Exception(t('An error occured while attempting to determine file permissions.')); }
            clearstatcache();
            $dir_perms = substr(decoct($perms),1);
            
            $file_perms = "0";
            $parts[] = substr($dir_perms,1,1);
            $parts[] = substr($dir_perms,2,1);
            $parts[] = substr($dir_perms,3,1);
            foreach($parts as $p){
                if(intval($p)%2 == 0) {
                    $file_perms.=$p;
                    continue;
                }
                $file_perms .= intval($p)-1;
            }
        } catch(Exception $e) {
            return false;
        }
        $res = new stdClass();
        $res->file  = intval($file_perms,8);
        $res->dir   = intval($dir_perms,8);
        
        return $res;
    }
        
}