function setupThumbs($filedef, $imagedef) { $path_helper = new PathHelper(); foreach ($imagedef['thumbs'] as &$thumb) { $thumb[1] = $path_helper->join(array($imagedef['base_dir'], $thumb[1], $filedef['filename']), '/'); } if ($imagedef['admin_dir'] !== false) { #For the list $path_1 = $path_helper->join(array('{public}/' . DEFAULT_MODULE . '/admin', $imagedef['admin_dir'], 'small', $filedef['value']), '/'); $admin_thumb_1 = array('crop', $path_1, 30, 30); $imagedef['thumbs'][] = $admin_thumb_1; #For the gallery $path_2 = $path_helper->join(array('{public}/' . DEFAULT_MODULE . '/admin', $imagedef['admin_dir'], $filedef['value']), '/'); $admin_thumb_2 = array('filled', $path_2, 160); $imagedef['thumbs'][] = $admin_thumb_2; } $thumbs = $imagedef['thumbs']; if ($thumbs) { $last = $thumbs[count($thumbs) - 1]; $parts = explode('/', $last[1]); $dir = implode('/', array_slice($parts, 3, count($parts) - 4)); $this->setBasePath(UrlHelper::resource('/' . DEFAULT_MODULE . '/admin/' . $dir)); } $this->setThumbsTarget($thumbs); }
function setupFile($base_dir, $filename = '{name}.{ext}', $value = null) { if (!$value) { $value = $filename; } $this->filedef = array('filename' => $filename, 'base_dir' => $base_dir, 'value' => $value); $path_helper = new PathHelper(); $path = $path_helper->join(array($base_dir, $filename), '/'); $this->setSavingTarget($path, $value); }
/** * Validates if source xor destiny are s3 paths. * @return bool */ public function validate() { if (PathHelper::isS3Path($this->source) xor PathHelper::isS3Path($this->destination)) { return true; } return false; }
private function forceCd($directory) { if (!$this->pathHelper->isValid($directory)) { mkdir($directory, 0777, true); } chdir($directory); }
function saveFileAs($target, $chmod = 0644, &$substitutions = array()) { if (!$this->hasFile()) { return false; } $info = pathinfo($this->_value['name']); $replacements = array('name' => $info['filename'], 'ext' => $info['extension']); $target = PathHelper::parse($target, $replacements, $substitutions); $dirname = dirname($target); if (!file_exists($dirname)) { $old = umask(0); mkdir($dirname, 0777, true); umask($old); } if (!$this->_saved_to) { $success = @move_uploaded_file($this->_value["tmp_name"], $target); $this->_saved_to = $target; } else { $success = @copy($this->_saved_to, $target); } if (!$success) { return false; } @chmod($target, $chmod); return $target; }
/** * Rolls back any changes made to the DB during the update process. * * @param $backupPath * * @return null */ public static function rollBackDatabaseChanges($backupPath) { $dbBackup = new DbBackup(); $fileName = $backupPath . '.sql'; $fullBackupPath = craft()->path->getDbBackupPath() . $fileName; if (PathHelper::ensurePathIsContained($fileName)) { $dbBackup->restore($fullBackupPath); } else { Craft::log('Someone tried to restore a database from outside of the Craft backups folder: ' . $fullBackupPath, LogLevel::Warning); } }
/** * Escreve configuração em um arquivo usando padrão do Laravel * * @param mixed $config * @param mixed $value * @return bool|int */ public static function setLaravelConfig($config, $value) { $path = explode(Strings::MODULE_CONFIG_CONFIGS_SEPARATOR, $config); if ($path != array()) { $variable = "'" . array_pop($path) . "'"; $path = PathHelper::getConfigDir(implode(Strings::PATH_SEPARATOR, $path) . Strings::PHP_EXTENSION); if ($variable != '\'\'' && $path != base_path() . Strings::PATH_SEPARATOR . Strings::PHP_EXTENSION) { if (file_exists($path)) { return self::setConfig($path, $variable, $value); } } } return false; }
/** * Scans a dir and return the content * in it * * @param string $dir * @param boolean $recursive * @return array */ public static function scanDir($dir, $recursive = false) { $tree = array(); foreach (scandir($dir) as $result) { if ($result == '.' || $result == '..') { continue; } $resultPath = PathHelper::getRealPath($dir) . $result; if (true == $recursive && is_dir($resultPath)) { $tree[] = array('type' => 'dir', 'name' => $result, 'path' => $resultPath, 'content' => self::scanDir($resultPath)); continue; } $tree[] = array('type' => is_dir($resultPath) ? 'dir' : 'file', 'name' => $result, 'path' => $resultPath); } return $tree; }
public function load(AbstractMetaModelFactory $factory, AbstractMetaModel $metamodel, array $filters = NULL, $finalAttempt) { $metamodelTypeFolder = $this->getMetaModelFolderName(); $filecount = 0; $metamodelConfigurations = module_invoke_all('dc_metamodel'); foreach ($metamodelConfigurations as $metamodelConfiguration) { $path = $metamodelConfiguration['path'] . DIRECTORY_SEPARATOR . $metamodelTypeFolder . DIRECTORY_SEPARATOR . 'metadata'; // initial name space is not defined. It will be based on subfolder name, if any $namespace = NULL; $simplifiedPath = PathHelper::simplifyPath($path); LogHelper::log_info(t("Loading configuration from '@path' ...", array('@path' => $simplifiedPath))); if (!file_exists($path)) { throw new IllegalStateException(t('Folder could not be found: @path', array('@path' => $simplifiedPath))); } $filecount += $this->loadFromDirectory($metamodel, $filters, $path, $namespace); } LogHelper::log_info(t('Processed @filecount files', array('@filecount' => $filecount))); return self::LOAD_STATE__SUCCESSFUL; }
/** * Sends a resource back to the browser. * * @param string $path * * @throws HttpException * @return null */ public function sendResource($path) { if (PathHelper::ensurePathIsContained($path) === false) { throw new HttpException(404); } $cachedPath = $this->getCachedResourcePath($path); if ($cachedPath) { if ($cachedPath == ':(') { // 404 $realPath = false; } else { // We've got it already $realPath = $cachedPath; } } else { // We don't have a cache of the file system path, so let's get it $realPath = $this->getResourcePath($path); // Now cache it $this->cacheResourcePath($path, $realPath); } if ($realPath === false || !IOHelper::fileExists($realPath)) { throw new HttpException(404); } // If there is a timestamp and HTTP_IF_MODIFIED_SINCE exists, check the timestamp against requested file's last // modified date. If the last modified date is less than the timestamp, return a 304 not modified and let the // browser serve it from cache. $timestamp = craft()->request->getParam($this->dateParam, null); if ($timestamp !== null && array_key_exists('HTTP_IF_MODIFIED_SINCE', $_SERVER)) { $requestDate = DateTime::createFromFormat('U', $timestamp); $lastModifiedFileDate = IOHelper::getLastTimeModified($realPath); if ($lastModifiedFileDate && $lastModifiedFileDate <= $requestDate) { // Let the browser serve it from cache. HeaderHelper::setHeader('HTTP/1.1 304 Not Modified'); craft()->end(); } } // Note that $content may be empty -- they could be requesting a blank text file or something. It doens't matter. // No need to throw a 404. $content = IOHelper::getFileContents($realPath); // Normalize URLs in CSS files $mimeType = IOHelper::getMimeTypeByExtension($realPath); if (mb_strpos($mimeType, 'css') !== false) { $content = preg_replace_callback('/(url\\(([\'"]?))(.+?)(\\2\\))/', array(&$this, '_normalizeCssUrl'), $content); } if (!craft()->config->get('useXSendFile')) { $options['forceDownload'] = false; if (craft()->request->getQuery($this->dateParam)) { $options['cache'] = true; } craft()->request->sendFile($realPath, $content, $options); } else { craft()->request->xSendFile($realPath); } // You shall not pass. craft()->end(); }
/** * @dataProvider isS3PathProvider * @param $expected * @param $path */ public function testIsS3Path($expected, $path) { $this->assertEquals($expected, PathHelper::isS3Path($path)); }
protected function getFilesToDelete($rows, $delete_files = array()) { $file_columns = $this->getColumnsByType(array('filename', 'image')); foreach ($rows as $row) { foreach ($file_columns as $column) { $target_dirs = $column->getTargetDirs(); foreach ($target_dirs as $dir) { $delete_files[] = PathHelper::parse($dir . DS . $row[$column->getName()]); } $delete_files[] = PathHelper::parse(PathHelper::join(array('{public}/' . DEFAULT_MODULE . '/admin', $this->name . '/' . $column->getName()))) . DS . $row[$column->getName()]; $delete_files[] = PathHelper::parse(PathHelper::join(array('{public}/' . DEFAULT_MODULE . '/admin', $this->name . '/' . $column->getName() . '/small'))) . DS . $row[$column->getName()]; } } return $delete_files; }
/** * Ensures that a template name isn't null, and that it doesn't lead outside the template folder. Borrowed from * {@link Twig_Loader_Filesystem}. * * @param string $name * * @throws \Twig_Error_Loader */ private function _validateTemplateName($name) { if (mb_strpos($name, "") !== false) { throw new \Twig_Error_Loader(Craft::t('A template name cannot contain NUL bytes.')); } if (PathHelper::ensurePathIsContained($name) === false) { throw new \Twig_Error_Loader(Craft::t('Looks like you try to load a template outside the template folder: {template}.', array('template' => $name))); } }
/** * Retrieve paths where to find the layout files. * * @param string $dir * @return string The full path * @since 2.0 */ protected function _getPath($dir = '') { return $this->_path->path($dir); }
/** * * @example * * $this->createThumbs( * array('best', '[programa]/{random[10]}_{width}x{height}.{ext}' 300, 500), * array('width', '[programa]/{random[10]}_width.{ext}', 110), * array('square', '[programa]/{random[10]}_square.{ext}', 80), * array('crop', '[programa]/{random[10]}_crop_{width}x{height}.{ext}', 300, 500), * array('height', '[programa]/{random[10]}_height.{ext}', 180), * array('filled', '[programa]/{random[10]}_filled.{ext}', 365), * array('original','[programa]/{random[10]}.{ext}') * ); * * @return array */ function createThumbs() { if (!$this->hasFile()) { return false; } $thumbs = func_get_args(); #No thumbs specified if (!count($thumbs)) { return false; } #Save temporarily the original image in the tmp directory $path = APPD_TMP . DS . '{random}.{ext}'; $source = $this->saveFileAs($path); if (!$source) { trigger_error("Could not create temporary thumbnail.", E_USER_WARNING); return false; } Loader::includeLibrary('phaxsithumb/PhaxsiThumb.php'); $fk_thumb = new PhaxsiThumb($source); if ($fk_thumb->isError()) { @unlink($source); return false; } #Generate filenames if needed. $names will be returned. $names = array(); for ($i = 0; $i < count($thumbs); $i++) { $info = pathinfo($this->_value['name']); $replacements = array('size' => isset($thumbs[$i][2]) ? $thumbs[$i][2] : '', 'width' => isset($thumbs[$i][2]) ? $thumbs[$i][2] : '', 'height' => isset($thumbs[$i][3]) ? $thumbs[$i][3] : '', 'name' => $info['filename'], 'ext' => $info['extension']); $thumbs[$i][1] = PathHelper::replaceUploadsDir($thumbs[$i][1]); $thumbs[$i][1] = PathHelper::parse($thumbs[$i][1], $replacements); $dir = dirname($thumbs[$i][1]); if (!file_exists($dir)) { $old = umask(0); mkdir($dir, 0777, true); umask($old); } $names[$i] = $thumbs[$i][1]; } $success = call_user_func_array(array(&$fk_thumb, 'batchCreateThumbs'), $thumbs); @unlink($source); if (!$success) { return false; } return $names; }
/** * Escreve aquivo de rotas definitivo apartir do RouteBuilder array * * @param array $routeBuilderArray * @return int|bool */ public static function buildRoutes(array $routeBuilderArray) { //creia cabeçalho do arquivode rotas $routes = Strings::PHP_TAG . chr(13) . chr(13) . Strings::ROUTER_BUILDER_GEN_FILE_STRING_HEADER . chr(13) . chr(13); //Faz um loop ema todos os itens do arquivo array do raouteBuilder foreach ($routeBuilderArray as $module => $moduleRoute) { //Constroi rotas para o modulo $routes .= "//" . $module . $moduleRoute . chr(13) . chr(13) . chr(13) . chr(13); /*Adiciona as rotas do modulo*/ } //substitui o conteudo do arquivo de rotas pelo novo conteudo return file_put_contents(PathHelper::getLaravelRoutesPath(), str_replace(file_get_contents(PathHelper::getLaravelRoutesPath()), $routes, file_get_contents(PathHelper::getLaravelRoutesPath()))); }
/** * Read Directory Nested * * @param string $path Path directory to be scan * @param integer $directory_depth directory depth of nested to be scanned * @param boolean $hidden true if want to show hidden content * @return array path trees */ public static function readDirList($path, $directory_depth = 0, $hidden = false) { $file_data = false; if (static::isDir($path) && ($fp = opendir($path))) { $new_depth = $directory_depth - 1; $path = PathHelper::cleanPath($path) . '/'; while (false !== ($file = readdir($fp))) { // Remove '.', '..', and hidden files [optional] if ($file === '.' || $file === '..' || $hidden === false && $file[0] === '.') { continue; } static::isDir($path . $file) && ($path .= '/'); if (($directory_depth < 1 || $new_depth > 0) && static::isDir($path . $file)) { $file_data[$file] = static::readDirList($path . $file, $new_depth, $hidden); } else { $file_data[] = $file; } } // close resource closedir($fp); } return $file_data; }
require_once 'Bootstrap.php'; use Symfony\Component\Console\Application; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Input\ArrayInput; use Executables\FileCommands\FileCommandFactory; $commandName = 's3fileshifter'; $commandDefinition = array(new InputArgument('source', InputArgument::REQUIRED, 'The file or directory to shift.'), new InputArgument('destination', InputArgument::REQUIRED, 'Where the file or directory should be shifted to.')); $commandDescription = 'Shifts a file from S3 to the local or vice versa.'; $commandHelp = 'The <info>s3fileshifter</info> will shift a file or a whole directory from the local filesystem to S3 or vice versa.' . PHP_EOL . ' Note that one of the input arguments must use the S3 protocol and the other one a valid path to a file or directory in the local filesystem.' . PHP_EOL . '<comment>Samples:</comment>' . PHP_EOL . 'To copy a directory from S3 to local:<info>php S3FileShifter.php s3fileshifter s3://bucket/directory /tmp/destination_directory</info>' . PHP_EOL . 'To copy a file from local to S3<info>php S3FileShifter.php s3fileshifter /tmp/file.example s3://bucket/destination_directory</info>'; $commandLogic = function (InputInterface $input, OutputInterface $output) { $source = $input->getArgument('source'); $destination = $input->getArgument('destination'); $validator = new S3FileShifterArgumentsValidator($destination, $source); if ($validator->validate() === false) { $output->writeln('<error>One of the paths needs to have the "s3://" protocol</error>'); return; } $scan = FileCommandFactory::getCommand('DefaultScan', array('path' => $source)); $sourceFilePaths = $scan->execute(); foreach ($sourceFilePaths as $currentRelativePath) { $shift = FileCommandFactory::getCommand('DefaultShift', array('src' => PathHelper::buildPath($source, $currentRelativePath), 'dest' => PathHelper::buildPath($destination, $currentRelativePath))); $shift->execute(); } }; $console = new Application(); $console->register($commandName)->setDefinition($commandDefinition)->setDescription($commandDescription)->setHelp($commandHelp)->setCode($commandLogic); $input = new ArrayInput(array('command' => 's3fileshifter', 'source' => $argv[1], 'destination' => $argv[2])); $console->run($input);
public function toolsSetChmod() { $return = array(); $return['status'] = 'error'; $return['msg'] = ''; $return['perms'] = ''; $post = $this->input->post(); if (empty($post['folder']) || empty($post['type'])) { $return['msg'] = 'Data not specified'; $this->_json($return); } if (!is_numeric($post['type'])) { $return['msg'] = 'Chmod type is wrong!'; $this->_json($return); } $type = $post['type']; $folder = $post['folder']; $chmod = $type == 1 ? 755 : 777; $found = false; foreach ($this->chmod_folders as $cfolder) { if ($folder == $cfolder['path']) { $found = true; break; } } if (!$found) { $return['msg'] = 'Chmod folder ' . $folder . ' not allowed!'; $this->_json($return); } $stat = @chmod($folder, $chmod); if ($stat) { $status = 1; } else { @exec('sudo chmod ' . $chmod . ' ' . $folder, $output, $res); if (!$res) { $status = 1; } else { $return['msg'] = 'Chmod folder ' . $folder . ' not allowed!'; $this->_json($return); } } clearstatcache(); $perms = PathHelper::getPermissions($folder, true); $return['perms'] = $perms['int'] . ' (' . $perms['str'] . ')'; $return['msg'] = 'Successfully chmoded folder ' . $folder . ' to ' . $chmod; $return['status'] = $status ? 'ok' : 'error'; $this->_json($return); }
/** * Retorna a mensagem de sucesso ao rodar comando module:refresh * * @param string $moduleType * @param string $moduleName * @return string */ public static function successfullyRunModuleRefresh($moduleType, $moduleName) { return 'Comando executado com sucesso. ' . $moduleType . '.' . $moduleName . ' ' . Configs::getConfig(PathHelper::getModuleConfigPath($moduleType, $moduleName), "versao"); }