/** * Directory Setter/Getter * * @param string $dir * @throws Exception * @return string|FileExplorer */ public function dir($dir = null) { if ($dir === null) { return $this->_dir; } if (!is_string($dir)) { throw new Exception('Invalid Argument'); } //sanitize dir input $dir = self::cleanDirname($dir); $dir = self::slashTerm($dir); if (Folder::isAbsolute($dir)) { if (Folder::isWindowsPath($dir)) { throw new Exception(__('Cannot use absolute windows path as directory')); } } else { $dir = $this->_dir . $dir; } $this->_dir = $dir; //TODO check if path has changed $this->_Folder = $this->getFolder(); if (!$this->_Folder->pwd()) { throw new Exception(__("Folder %s not found", $dir)); } // reset contents $this->_contents = null; if ($this->autoLoadContents) { $this->readContents(); } return $this; }
/** * Initialization. * * It loads the required classes for web and cli environments. * * @throws ConfigureException if needed configuration parameters are not found. * @param array $config Configuration options. * @return void */ public static function init($config = null) { self::loadConfig($config); if (!($redis = Configure::read('CakeResque.Redis')) || !($resqueLib = Configure::read('CakeResque.Resque.lib')) || !($schedulerLib = Configure::read('CakeResque.Scheduler.lib')) || !($statusLib = Configure::read('CakeResque.Status.lib'))) { throw new ConfigureException(__d('cake_resque', 'There is an error in the configuration file.')); } if (empty($redis['host']) || empty($redis['port']) || empty($redis['database']) && !is_numeric($redis['database']) || empty($redis['namespace'])) { throw new ConfigureException(__d('cake_resque', 'There is an error in the Redis configuration key.')); } $pluginVendorPath = CakePlugin::path('CakeResque') . 'vendor' . DS; if (!Folder::isAbsolute($resqueLib)) { $resqueLib = $pluginVendorPath . $resqueLib; } $resqueLib .= DS . 'lib' . DS; if (!Folder::isAbsolute($schedulerLib)) { $schedulerLib = $pluginVendorPath . $schedulerLib; } $schedulerLib .= DS . 'lib' . DS . 'ResqueScheduler' . DS; if (!Folder::isAbsolute($statusLib)) { $statusLib = $pluginVendorPath . $statusLib; } require_once realpath($resqueLib . 'Resque.php'); require_once realpath($resqueLib . 'Resque' . DS . 'Worker.php'); require_once realpath($schedulerLib . 'ResqueScheduler.php'); require_once realpath($schedulerLib . 'Stat.php'); require_once realpath($schedulerLib . 'Job' . DS . 'Status.php'); require_once realpath($statusLib . DS . 'src' . DS . 'ResqueStatus' . DS . 'ResqueStatus.php'); Resque::setBackend($redis['host'] . ':' . $redis['port'], $redis['database'], $redis['namespace']); }
/** * Create new project */ public function create() { $project = '.'; $root = ROOT; $app = APP_DIR; $working = APP; $core = "{$root}/{$app}/Vendor/cakephp/cakephp/lib"; $skel = "{$core}/Cake/Console/Templates/skel"; $this->out(__d('cake_console', '<info>Create project `%s` in `%s`</info>', $app, $working)); if (!empty($project) && !Folder::isAbsolute($project) && isset($_SERVER['PWD'])) { $project = $_SERVER['PWD'] . DS . $project; } if ($this->_bake($project, $skel)) { $path = Folder::slashTerm($project); $this->_fixConfigureFiles($path); $this->_fixCakeCoreIncludePath($path); $this->_fixDebugKitPlugin($path); $this->_fixAutoloader($path); $this->_fixPermissionForDirs($path); $this->_fixGitIgnore($path); } }
/** * Checks that given project path does not already exist, and * finds the app directory in it. Then it calls bake() with that information. * * @return mixed */ public function execute() { $project = null; if (isset($this->args[0])) { $project = $this->args[0]; } else { $appContents = array_diff(scandir(APP), array('.', '..')); if (empty($appContents)) { $suggestedPath = rtrim(APP, DS); } else { $suggestedPath = APP . 'myapp'; } } while (!$project) { $prompt = __d('cake_console', "What is the path to the project you want to bake?"); $project = $this->in($prompt, null, $suggestedPath); } if ($project && !Folder::isAbsolute($project) && isset($_SERVER['PWD'])) { $project = $_SERVER['PWD'] . DS . $project; } $response = false; while (!$response && is_dir($project) === true && file_exists($project . 'Config' . 'core.php')) { $prompt = __d('cake_console', '<warning>A project already exists in this location:</warning> %s Overwrite?', $project); $response = $this->in($prompt, array('y', 'n'), 'n'); if (strtolower($response) === 'n') { $response = $project = false; } } $success = true; if ($this->bake($project)) { $path = Folder::slashTerm($project); if ($this->securitySalt($path) === true) { $this->out(__d('cake_console', ' * Random hash key created for \'Security.salt\'')); } else { $this->err(__d('cake_console', 'Unable to generate random hash for \'Security.salt\', you should change it in %s', APP . 'Config' . DS . 'core.php')); $success = false; } if ($this->securityCipherSeed($path) === true) { $this->out(__d('cake_console', ' * Random seed created for \'Security.cipherSeed\'')); } else { $this->err(__d('cake_console', 'Unable to generate random seed for \'Security.cipherSeed\', you should change it in %s', APP . 'Config' . DS . 'core.php')); $success = false; } if ($this->cachePrefix($path)) { $this->out(__d('cake_console', ' * Cache prefix set')); } else { $this->err(__d('cake_console', 'The cache prefix was <error>NOT</error> set')); $success = false; } if ($this->consolePath($path) === true) { $this->out(__d('cake_console', ' * app/Console/cake.php path set.')); } else { $this->err(__d('cake_console', 'Unable to set console path for app/Console.')); $success = false; } $hardCode = false; if ($this->cakeOnIncludePath()) { $this->out(__d('cake_console', '<info>CakePHP is on your `include_path`. CAKE_CORE_INCLUDE_PATH will be set, but commented out.</info>')); } else { $this->out(__d('cake_console', '<warning>CakePHP is not on your `include_path`, CAKE_CORE_INCLUDE_PATH will be hard coded.</warning>')); $this->out(__d('cake_console', 'You can fix this by adding CakePHP to your `include_path`.')); $hardCode = true; } $success = $this->corePath($path, $hardCode) === true; if ($success) { $this->out(__d('cake_console', ' * CAKE_CORE_INCLUDE_PATH set to %s in %s', CAKE_CORE_INCLUDE_PATH, 'webroot/index.php')); $this->out(__d('cake_console', ' * CAKE_CORE_INCLUDE_PATH set to %s in %s', CAKE_CORE_INCLUDE_PATH, 'webroot/test.php')); } else { $this->err(__d('cake_console', 'Unable to set CAKE_CORE_INCLUDE_PATH, you should change it in %s', $path . 'webroot' . DS . 'index.php')); $success = false; } if ($success && $hardCode) { $this->out(__d('cake_console', ' * <warning>Remember to check these values after moving to production server</warning>')); } $Folder = new Folder($path); if (!$Folder->chmod($path . 'tmp', 0777)) { $this->err(__d('cake_console', 'Could not set permissions on %s', $path . DS . 'tmp')); $this->out('chmod -R 0777 ' . $path . DS . 'tmp'); $success = false; } if ($success) { $this->out(__d('cake_console', '<success>Project baked successfully!</success>')); } else { $this->out(__d('cake_console', 'Project baked but with <warning>some issues.</warning>.')); } return $path; } }
/** * Get the real path (taking ".." and such into account) * * @param string $path Path to resolve * @return string The resolved path * @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#Folder::realpath */ public function realpath($path) { $path = str_replace('/', DS, trim($path)); if (strpos($path, '..') === false) { if (!Folder::isAbsolute($path)) { $path = Folder::addPathElement($this->path, $path); } return $path; } $parts = explode(DS, $path); $newparts = array(); $newpath = ''; if ($path[0] === DS) { $newpath = DS; } while (($part = array_shift($parts)) !== NULL) { if ($part === '.' || $part === '') { continue; } if ($part === '..') { if (!empty($newparts)) { array_pop($newparts); continue; } else { return false; } } $newparts[] = $part; } $newpath .= implode(DS, $newparts); return Folder::slashTerm($newpath); }
/** * Creates a file with contents from base64 encoded string. * * TestData::getFile('image-png.png'); * TestData::getFile(array('image-png.png' => TMP . 'other-name.png')); * TestData::getFile(array('image-png.png' => 'other-name.png')); * TestData::getFile('file.txt', 'I am the content'); * * @param mixed $key * @param string $string * @return string Absolute path to the created file */ public function getFile($key = null, $string = '') { if (is_array($key)) { $file = current($key); $key = key($key); if (!Folder::isAbsolute($file)) { $file = $this->settings['base'] . $file; } $alias = $file; } else { $alias = $key; $file = $this->settings['base'] . $key; } if ($string === '') { $string = $this->getString($key); } $File = new File($file); if ($File->exists()) { $File->delete(); } $File->write($string); $File->offset(0); $File->close(); $this->Files[$alias] =& $File; return $File->pwd(); }
private function __advancedFolderFind($conditions) { if (empty($this->fileList[0])) { $this->return = array(); return true; } $i = 0; foreach ($this->fileList[0] as $folder) { if (in_array($folder, $this->ignore)) { continue; } if ($this->recursive > -2) { $Folder = new Folder($this->path . DS . $folder); $this->return[$i]['Folder']['path'] = $Folder->path; $this->return[$i]['Folder']['name'] = basename($this->return[$i]['Folder']['path']); $this->return[$i]['Folder']['parent'] = dirname($this->return[$i]['Folder']['path']); $this->return[$i]['Folder']['relative'] = $this->__relativePath($this->return[$i]['Folder']['path']); $stat = stat($this->return[$i]['Folder']['path']); $this->__fileStatus($i, $stat); if ($this->recursive > -1) { $this->return[$i]['Folder']['accessed'] = date('Y-m-d H:i:s', $stat['atime']); $this->return[$i]['Folder']['modified'] = date('Y-m-d H:i:s', $stat['mtime']); $this->return[$i]['Folder']['created'] = date('Y-m-d H:i:s', $stat['ctime']); if ($this->recursive > 0) { $this->return[$i]['Folder']['size'] = $Folder->dirsize(); $this->return[$i]['Folder']['absolute'] = $Folder->isAbsolute($this->return[$i]['Folder']['path']); $children = $Folder->tree($this->return[$i]['Folder']['path']); $this->return[$i]['Folder']['sub_folders'] = count($children[0]) - 1; $this->return[$i]['Folder']['sub_files'] = count($children[1]); if ($this->recursive > 1) { $this->return[$i]['Folder']['realpath'] = $Folder->realpath($this->return[$i]['Folder']['path']); $this->return[$i]['Folder']['windows'] = $Folder->isWindowsPath($this->return[$i]['Folder']['path']); $this->return[$i]['Folder']['Children'] = $children; $this->return[$i]['Folder']['Extended'] = $stat; $i++; continue; } $i++; } $i++; } $i++; } $i++; } return true; }
/** * testIsAbsolute method * * @return void */ public function testIsAbsolute() { $this->assertFalse(Folder::isAbsolute('path/to/file')); $this->assertFalse(Folder::isAbsolute('cake/')); $this->assertFalse(Folder::isAbsolute('path\\to\\file')); $this->assertFalse(Folder::isAbsolute('0:\\path\\to\\file')); $this->assertFalse(Folder::isAbsolute('\\path/to/file')); $this->assertFalse(Folder::isAbsolute('\\path\\to\\file')); $this->assertFalse(Folder::isAbsolute('notRegisteredStreamWrapper://example')); $this->assertFalse(Folder::isAbsolute('://example')); $this->assertTrue(Folder::isAbsolute('/usr/local')); $this->assertTrue(Folder::isAbsolute('//path/to/file')); $this->assertTrue(Folder::isAbsolute('C:\\cake')); $this->assertTrue(Folder::isAbsolute('C:\\path\\to\\file')); $this->assertTrue(Folder::isAbsolute('d:\\path\\to\\file')); $this->assertTrue(Folder::isAbsolute('\\\\vmware-host\\Shared Folders\\file')); $this->assertTrue(Folder::isAbsolute('http://www.example.com')); }
/** * Resolves partial path to an absolute path by trying to find an existing file matching the * pattern `{<base path 1>, <base path 2>, [...]}/<provided partial path without ext>.*`. * The base paths are coming from the `_paths` property. * * Examples: * img/cern >>> MEDIA_STATIC/img/cern.png * img/mit.jpg >>> MEDIA_TRANSFER/img/mit.jpg * s/<...>/img/hbk.jpg >>> MEDIA_FILTER/s/<...>/img/hbk.png * * @param string $path A relative or absolute path to a file. * @return string|boolean False on error or if path couldn't be resolved otherwise * an absolute path to the file. */ function file($path) { // Most recent paths are probably searched more often $bases = array_reverse(array_keys($this->_paths)); if (Folder::isAbsolute($path)) { return file_exists($path) ? $path : null; } $extension = null; extract(pathinfo($path), EXTR_OVERWRITE); if (!isset($filename)) { /* PHP < 5.2.0 */ $filename = substr($basename, 0, isset($extension) ? -(strlen($extension) + 1) : 0); } foreach ($bases as $base) { if (file_exists($base . $path)) { return $base . $path; } $files = glob($base . $dirname . DS . $filename . '.*', GLOB_NOSORT | GLOB_NOESCAPE); if (count($files) > 1) { $message = "MediaHelper::file - "; $message .= "A relative path (`{$path}`) was given which triggered search for "; $message .= "files with the same name but not the same extension."; $message .= "This resulted in multiple files being found. "; $message .= "However the first file being found has been picked."; trigger_error($message, E_USER_NOTICE); } if ($files) { return array_shift($files); } } }
/** * testIsAbsolute method * * @return void */ public function testIsAbsolute() { $this->assertFalse(Folder::isAbsolute('path/to/file')); $this->assertFalse(Folder::isAbsolute('cake/')); $this->assertFalse(Folder::isAbsolute('path\\to\\file')); $this->assertFalse(Folder::isAbsolute('0:\\path\\to\\file')); $this->assertFalse(Folder::isAbsolute('\\path/to/file')); $this->assertFalse(Folder::isAbsolute('\\path\\to\\file')); $this->assertTrue(Folder::isAbsolute('/usr/local')); $this->assertTrue(Folder::isAbsolute('//path/to/file')); $this->assertTrue(Folder::isAbsolute('C:\\cake')); $this->assertTrue(Folder::isAbsolute('C:\\path\\to\\file')); $this->assertTrue(Folder::isAbsolute('d:\\path\\to\\file')); $this->assertTrue(Folder::isAbsolute('\\\\vmware-host\\Shared Folders\\file')); }
/** * If path provided is not absolute, attempts to make it absolute using * the CAKE_CORE_INCLUDE_PATH, APP, and the any supplied $roots * * @param string $path The path to convert to an absolute path. * @param array $roots Paths to serve as root dirs to convert paths into absolute paths. * @return string */ public function makeAbsolute($path, $roots = array()) { if (Folder::isAbsolute($path)) { return $path; } $coreFile = CAKE . $path; if (file_exists($coreFile)) { return $coreFile; } $appFile = APP . $path; if (file_exists($appFile)) { return $appFile; } foreach ($roots as $rootDir) { if (file_exists($rootDir . $path)) { return $rootDir . $path; } } return $path; }
/** * Resolves partial path (compat) * * Examples: * img/cern >>> MEDIA_STATIC/img/cern.png * transfer/img/image.jpg >>> MEDIA_TRANSFER/img/image.jpg * s/img/image.jpg >>> MEDIA_FILTER/s/static/img/image.jpg * * @param string|array $path Either a string or an array with dirname and basename keys * @return string|boolean False on error or if path couldn't be resolbed otherwise * an absolute path to the file * @deprecated */ function __compatFile($path) { $path = array(); foreach (func_get_args() as $arg) { if (is_array($arg)) { if (isset($arg['dirname'])) { $path[] = rtrim($arg['dirname'], '/\\'); } if (isset($arg['basename'])) { $path[] = $arg['basename']; } } else { $path[] = rtrim($arg, '/\\'); } } $path = implode(DS, $path); $path = str_replace(array('/', '\\'), DS, $path); if (isset($this->__cached[$path])) { return $this->__cached[$path]; } if (Folder::isAbsolute($path)) { return file_exists($path) ? $path : false; } $parts = explode(DS, $path); if (in_array($parts[0], $this->_versions)) { array_unshift($parts, basename(key($this->_map['filter']))); } if (!in_array($parts[0], array_keys($this->_directories))) { array_unshift($parts, basename(key($this->_map['static']))); } if (in_array($parts[1], $this->_versions) && !in_array($parts[2], array_keys($this->_directories))) { array_splice($parts, 2, 0, basename(key($this->_map['static']))); } $path = implode(DS, $parts); if (isset($this->__cached[$path])) { return $this->__cached[$path]; } $file = $this->_directories[array_shift($parts)] . implode(DS, $parts); if (file_exists($file)) { return $this->__cached[$path] = $file; } $short = current(array_intersect(Media::short(), $parts)); if (!$short) { $message = "MediaHelper::file - "; $message .= "You've provided a partial path without a media directory (e.g. img) "; $message .= "which is required to resolve the path."; trigger_error($message, E_USER_NOTICE); return false; } $extension = null; extract(pathinfo($file), EXTR_OVERWRITE); if (!isset($filename)) { /* PHP < 5.2.0 */ $filename = substr($basename, 0, isset($extension) ? -(strlen($extension) + 1) : 0); } for ($i = 0; $i < 2; $i++) { $file = $i ? $dirname . DS . $filename : $dirname . DS . $basename; foreach ($this->_extensions[$short] as $extension) { $try = $file . '.' . $extension; if (file_exists($try)) { return $this->__cached[$path] = $try; } } } return false; }
/** * Checks if path is within given locations * * @param string $check Absolute path * @param mixed $allow True or * allows any location, * an array containing absolute paths to locations * @return boolean */ function location($check, $allow = false) { $allow = self::_normalize($allow); if ($allow === true) { return true; } elseif ($allow === false) { return false; } if (!is_array($allow)) { $allow = array($allow); } else { $allow = array_unique($allow); } if (Validation::url($check)) { foreach ($allow as $path) { if (preg_match('/^' . preg_quote($path, '/') . '/', $check)) { return true; } } } elseif (MediaValidation::file($check, false)) { $check = dirname($check); if (!Folder::isAbsolute($check)) { return false; } $Check = new Folder($check); foreach ($allow as $path) { if (!Folder::isAbsolute($path) || Validation::url($path)) { continue; } if ($Check->inPath($path)) { return true; } } } return false; }
/** * If path provided is not absolute, prepends CORE_PATH, evaluates .. and * corrects directory separators for the current OS * * @param string $path * @return string */ public function makeAbsolute($path) { if (Folder::isAbsolute($path)) { return $path; } $path = CORE_PATH . $path; $Folder = new Folder($path); return $Folder->path; }
/** * Resolves partial path to an absolute path by trying to find an existing file matching the * pattern `{<base path 1>, <base path 2>, [...]}/<provided partial path without ext>.*`. * The base paths are coming from the `_paths` property. * * Examples: * img/cern >>> MEDIA_STATIC/img/cern.png * img/mit.jpg >>> MEDIA_TRANSFER/img/mit.jpg * s/<...>/img/hbk.jpg >>> MEDIA_FILTER/s/<...>/img/hbk.png * * @param string $path A relative or absolute path to a file. * @return string|boolean False on error or if path couldn't be resolved otherwise * an absolute path to the file. */ public function file($path) { if (strpos($path, '://') !== false) { return false; } $path = str_replace('/', DS, trim($path)); // Most recent paths are probably searched more often $bases = array_reverse(array_keys($this->_paths)); if (Folder::isAbsolute($path)) { return file_exists($path) ? $path : false; } $extension = null; extract(pathinfo($path), EXTR_OVERWRITE); /* @var $dirname string */ /* @var $basename string */ /* @var $extension string */ /* @var $filename string */ foreach ($bases as $base) { if (file_exists($base . $path)) { return $base . $path; } $files = glob($base . $dirname . DS . $filename . '.*', GLOB_NOSORT | GLOB_NOESCAPE); if (count($files) > 1) { $message = "MediaHelper::file - "; $message .= "A relative path (`{$path}`) was given which triggered search for "; $message .= "files with the same name but not the same extension."; $message .= "This resulted in multiple files being found. "; $message .= "However the first file being found has been picked."; trigger_error($message, E_USER_NOTICE); } if ($files) { return array_shift($files); } } return false; }
/** * Checks that given project path does not already exist, and * finds the app directory in it. Then it calls bake() with that information. * * @param string $project Project path */ public function execute() { $project = null; if (isset($this->args[0])) { $project = $this->args[0]; } while (!$project) { $prompt = __d('cake_console', "What is the path to the project you want to bake?"); $project = $this->in($prompt, null, APP_PATH . 'myapp'); } if ($project && !Folder::isAbsolute($project) && isset($_SERVER['PWD'])) { $project = $_SERVER['PWD'] . DS . $project; } $response = false; while ($response == false && is_dir($project) === true && file_exists($project . 'Config' . 'core.php')) { $prompt = __d('cake_console', '<warning>A project already exists in this location:</warning> %s Overwrite?', $project); $response = $this->in($prompt, array('y', 'n'), 'n'); if (strtolower($response) === 'n') { $response = $project = false; } } $success = true; if ($this->bake($project)) { $path = Folder::slashTerm($project); if ($this->createHome($path)) { $this->out(__d('cake_console', ' * Welcome page created')); } else { $this->err(__d('cake_console', 'The Welcome page was <error>NOT</error> created')); $success = false; } if ($this->securitySalt($path) === true) { $this->out(__d('cake_console', ' * Random hash key created for \'Security.salt\'')); } else { $this->err(__d('cake_console', 'Unable to generate random hash for \'Security.salt\', you should change it in %s', APP . 'Config' . DS . 'core.php')); $success = false; } if ($this->securityCipherSeed($path) === true) { $this->out(__d('cake_console', ' * Random seed created for \'Security.cipherSeed\'')); } else { $this->err(__d('cake_console', 'Unable to generate random seed for \'Security.cipherSeed\', you should change it in %s', APP . 'Config' . DS . 'core.php')); $success = false; } if ($this->consolePath($path) === true) { $this->out(__d('cake_console', ' * app/Console/cake.php path set.')); } else { $this->err(__d('cake_console', 'Unable to set console path for app/Console.')); $success = false; } $this->out(__d('cake_console', 'The value for CAKE_CORE_INCLUDE_PATH can be hardcoded set to %s in webroot/index.php', CAKE_CORE_INCLUDE_PATH)); $this->out(__d('cake_console', '<warning>If you hard code it, the project will possibly run only in your computer.</warning>')); $setConstants = $this->in(__d('cake_console', 'Do you want to set CAKE_CORE_INCLUDE_PATH in webroot/index.php?'), array('y', 'n'), 'n'); if (strtolower($setConstants) === 'y') { if ($this->corePath($path) === true) { $this->out(__d('cake_console', ' * CAKE_CORE_INCLUDE_PATH set to %s in webroot/index.php', CAKE_CORE_INCLUDE_PATH)); $this->out(__d('cake_console', ' * CAKE_CORE_INCLUDE_PATH set to %s in webroot/test.php', CAKE_CORE_INCLUDE_PATH)); $this->out(__d('cake_console', ' * <warning>Remember to check these values after moving to production server</warning>')); } else { $this->err(__d('cake_console', 'Unable to set CAKE_CORE_INCLUDE_PATH, you should change it in %s', $path . 'webroot' . DS . 'index.php')); $success = false; } } else { $this->out(__d('cake_console', '<warning>Please make sure your cake core is accessible, if you have problems edit CAKE_CORE_INCLUDE_PATH in webroot/index.php</warning>')); } $Folder = new Folder($path); if (!$Folder->chmod($path . 'tmp', 0777)) { $this->err(__d('cake_console', 'Could not set permissions on %s', $path . DS . 'tmp')); $this->out(__d('cake_console', 'chmod -R 0777 %s', $path . DS . 'tmp')); $success = false; } if ($success) { $this->out(__d('cake_console', '<success>Project baked successfully!</success>')); } else { $this->out(__d('cake_console', 'Project baked but with <warning>some issues.</warning>.')); } return $path; } }