/** * @ORM\PreFlush() */ public function preUpload() { if ($this->file) { if ($this->file instanceof FileUpload) { $basename = $this->file->getSanitizedName(); $basename = $this->suggestName($this->getFilePath(), $basename); $this->setName($basename); } else { $basename = trim(Strings::webalize($this->file->getBasename(), '.', FALSE), '.-'); $basename = $this->suggestName(dirname($this->file->getPathname()), $basename); $this->setName($basename); } if ($this->_oldPath && $this->_oldPath !== $this->path) { @unlink($this->getFilePathBy($this->_oldProtected, $this->_oldPath)); } if ($this->file instanceof FileUpload) { $this->file->move($this->getFilePath()); } else { copy($this->file->getPathname(), $this->getFilePath()); } return $this->file = NULL; } if (($this->_oldPath || $this->_oldProtected !== NULL) && ($this->_oldPath != $this->path || $this->_oldProtected != $this->protected)) { $oldFilePath = $this->getFilePathBy($this->_oldProtected !== NULL ? $this->_oldProtected : $this->protected, $this->_oldPath ?: $this->path); if (file_exists($oldFilePath)) { rename($oldFilePath, $this->getFilePath()); } } }
/** * UnsortedEpisodesFilter::accept() * * @return */ public function accept() { $file = new SplFileInfo( $this->getInnerIterator()->current() ); if ( !$file->isFile() ) { echo "Not a file<br />"; return false; } if ( !preg_match( '/\.(mkv|avi)$/ ', $file->getBasename() ) ) { echo "Not a video<br />"; return false; } if ( $file->getSize() < ( 25 * 1024 * 1024 ) ) { echo "Too small<br />"; return false; } $subtitleFileNames = array( $file->getBasename() . '.srt', $file->getBasename() . '.ass' ); foreach ( $subtitleFileNames as $subtitleFileName ) if ( file_exists( $subtitleFileName ) ) return false; }
/** * Upload an image to local server then return new image path after upload success * * @param array $file [tmp_name, name, error, type, size] * @param string image path for saving (this may constain filename) * @param string image filename for saving * @return string Image path after uploaded * @throws Exception If upload failed */ public function upload($file, $newImagePath = '.', $newImageName = NULL) { if (!empty($file['error'])) { $this->_throwException(':method: Upload error. Number: :number', array(':method' => __METHOD__, ':number' => $file['error'])); } if (getimagesize($file['tmp_name']) === FALSE) { $this->_throwException(':method: The file is not an image file.', array(':method' => __METHOD__)); } $fileInfo = new \SplFileInfo($newImagePath); if (!$fileInfo->getRealPath() or !$fileInfo->isDir()) { $this->_throwException(':method: The ":dir" must be a directory.', array(':method' => __METHOD__, ':dir' => $newImagePath)); } $defaultExtension = '.jpg'; if (empty($newImageName)) { if (!in_array($fileInfo->getBasename(), array('.', '..')) and $fileInfo->getExtension()) { $newImageName = $fileInfo->getBasename(); } else { $newImageName = uniqid() . $defaultExtension; } } if (!$fileInfo->isWritable()) { $this->_throwException(':method: Directory ":dir" is not writeable.', array(':method' => __METHOD__, ':dir' => $fileInfo->getRealPath())); } $destination = $fileInfo->getRealPath() . DIRECTORY_SEPARATOR . $newImageName; if (move_uploaded_file($file['tmp_name'], $destination)) { return $destination; } else { $this->_throwException(':method: Cannot move uploaded file to :path', array(':method' => __METHOD__, ':path' => $fileInfo->getRealPath())); } }
/** * Class init. * * @param string $path * @param string $root */ public function __construct($path, $root) { $this->root = $root; $this->path = ltrim(str_replace(realpath($root), '', realpath($path)), '/\\'); $this->fileInfo = new \SplFileInfo($root . '/' . $path); $this->name = File::stripExtension($this->fileInfo->getBasename()); $this->type = $this->fileInfo->getExtension(); }
/** * Load all extension classes */ public function load() { $counter = 0; foreach (glob(__DIR__ . '/Extension/*.php') as $filename) { $file = new \SplFileInfo($filename); $classname = $file->getBasename('.php'); $classpath = sprintf('%s\\Extension\\%s', __NAMESPACE__, $classname); require_once $filename; $extension = new \ReflectionClass($classpath); $instance = $extension->newInstance($this->getParent()); foreach ($extension->getMethods() as $method) { if (mb_substr($method->name, 0, 3) == 'FN_') { $map = new \StdClass(); $map->class = $extension->getShortName(); $map->method = $method->name; $map->instance = $instance; $tag = sprintf('%s.%s', mb_strtolower($classname), mb_substr($method->name, 3)); $this->mapping[$tag] = $map; } } $this->debug(__METHOD__, __LINE__, sprintf('Loaded extension: %s', $extension->getShortName())); // save the instance $this->instances[] = $instance; $counter++; } return $counter; }
/** * Returns base name of file without extension (or base name of directory). * * @param string $suffix * * @return string */ public function getBasename($suffix = null) { if (null === $suffix) { $suffix = static::SEPARATOR_EXTENSION . $this->getExtension(); } return parent::getBasename((string) $suffix); }
/** * Load config data. Support php|ini|yml config formats. * * @param string|\SplFileInfo $configFile * @throws ConfigException */ public function loadConfig($configFile) { if (!$configFile instanceof \SplFileInfo) { if (!is_string($configFile)) { throw new ConfigException('Mismatch type of variable.'); } $path = realpath($this->basePath . $configFile); // check basePath at mutation if (strpos($configFile, '..') || !strpos($path, realpath($this->basePath))) { throw new ConfigException('Config file name: ' . $configFile . ' isn\'t correct.'); } if (!is_file($path) || !is_readable($path)) { throw new ConfigException('Config file: ' . $path . ' not found of file isn\'t readable.'); } $configFile = new \SplFileInfo($path); } $path = $configFile->getRealPath(); $ext = $configFile->getExtension(); $key = $configFile->getBasename('.' . $ext); if ('php' === $ext) { $this->data[$key] = (include $path); } elseif ('ini' === $ext) { $this->data[$key] = parse_ini_file($path, true); } elseif ('yml' === $ext) { if (!function_exists('yaml_parse_file')) { throw new ConfigException("Function `yaml_parse_file` isn't supported.\n" . 'http://php.net/manual/en/yaml.requirements.php'); } $this->data[$key] = yaml_parse_file($path); } }
function __construct(\SplFileInfo $file, $contentType, $filename = null, $fileExtension = null) { $this->file = $file; $this->filename = $filename ?: $file->getBasename(); $this->contentType = $contentType; $this->fileExtension = $fileExtension ?: $file->getExtension(); }
/** * Extract the zip archive to be imported * * @throws \RuntimeException When archive cannot be opened or extracted or does not contain exactly one file file */ protected function extractZipArchive() { $archive = new \ZipArchive(); $status = $archive->open($this->filePath); if (true !== $status) { throw new \RuntimeException(sprintf('Error "%d" occurred while opening the zip archive.', $status)); } $path = $this->fileInfo->getPath(); $filename = $this->fileInfo->getBasename('.' . $this->fileInfo->getExtension()); $targetDir = sprintf('%s/%s', $path, $filename); if (!$archive->extractTo($targetDir)) { throw new \RuntimeException('Error occurred while extracting the zip archive.'); } $archive->close(); $this->archivePath = $targetDir; $finder = new Finder(); $files = $finder->in($targetDir)->name('/\\.' . $this->type . '$/i'); $count = $files->count(); if (1 !== $count) { throw new \RuntimeException(sprintf('Expecting the root directory of the archive to contain exactly 1 file file, found %d', $count)); } $filesIterator = $files->getIterator(); $filesIterator->rewind(); $this->filePath = $filesIterator->current()->getPathname(); }
/** * @param \SplFileInfo $fileInfo * @param string $downloadDirUrl */ public function __construct(\SplFileInfo $fileInfo, $downloadDirUrl) { $this->size = $fileInfo->getSize(); $this->fileName = $fileInfo->getBasename(); $this->lastModified = \DateTime::createFromFormat("U", $fileInfo->getMTime()); $this->url = "{$downloadDirUrl}/" . rawurlencode($this->fileName); }
/** * Returns the details about Communicator (current) file * w/o any kind of verification of file existance * * @param string $fileGiven * @return array */ protected function getFileDetailsRaw($fileGiven) { $info = new \SplFileInfo($fileGiven); $aFileBasicDetails = ['File Extension' => $info->getExtension(), 'File Group' => $info->getGroup(), 'File Inode' => $info->getInode(), 'File Link Target' => $info->isLink() ? $info->getLinkTarget() : '-', 'File Name' => $info->getBasename('.' . $info->getExtension()), 'File Name w. Extension' => $info->getFilename(), 'File Owner' => $info->getOwner(), 'File Path' => $info->getPath(), 'Name' => $info->getRealPath(), 'Type' => $info->getType()]; $aDetails = array_merge($aFileBasicDetails, $this->getFileDetailsRawStatistic($info, $fileGiven)); ksort($aDetails); return $aDetails; }
/** * @param string $filename * @return FileUpload */ public static function fileUploadFromFile($filename) { if (!file_exists($filename)) { throw new FileNotExistsException("File '{$filename}' does not exists"); } $file = new \SplFileInfo($filename); return new FileUpload(['name' => $file->getBasename(), 'type' => $file->getType(), 'size' => $file->getSize(), 'tmp_name' => $filename, 'error' => 0]); }
public function buildElephantFile($file) { $file = new \SplFileInfo($file); $resultFile = $file->getPath() . DIRECTORY_SEPARATOR . $file->getBasename('.elph') . '.php'; $rewriter = new Rewriter($resultFile); $rewriter->save(); return $resultFile; }
/** * Class constructor * * @param string $file_name File name */ public function __construct($file_name) { // Construct a new SplFileInfo object $spl = new SplFileInfo($file_name); $this->_name = $spl->getBasename(); $this->_path = $spl->getPath(); self::$instance = $this; }
function let(\SplFileInfo $file, Suite $suite) { $file->getFilename()->willReturn(__FILE__); $file->getPath()->willReturn(__DIR__); $file->getBasename('.php')->willReturn('SpecSpec'); $this->beConstructedWith($file, $suite, realpath(__DIR__ . '/../../../../..')); $this->shouldHaveType('Funk\\Specification\\Locator\\Iterator\\Spec'); }
private function readJsonFile(\SplFileInfo $splFile) { $result = []; $name = $splFile->getBasename('.json'); $json = json_decode($this->getContentFile($splFile), true); $result[$name] = $json; return $result; }
/** * Interpolates a string by substituting tokens in a string * * Default interpolations: * - `:webroot` Path to the webroot folder * - `:model` The current model e.g images * - `:field` The database field * - `:filename` The filename * - `:extension` The extension of the file e.g png * - `:id` The record id * - `:style` The current style e.g thumb * - `:hash` Generates a hash based on the filename * * @param string $string The string to be interpolated with data. * @param string $name The name of the model e.g. Image * @param int $id The id of the record e.g 1 * @param string $field The name of the database field e.g file * @param string $style The style to use. Should be specified in the behavior settings. * @param array $options You can override the default interpolations by passing an array of key/value * pairs or add extra interpolations. For example, if you wanted to change the hash method * you could pass `array('hash' => sha1($id . Configure::read('Security.salt')))` * @return array Settings array containing interpolated strings along with the other settings for the field. */ public static function run($string, $name, $id, $field, $filename, $style = 'original', $data = array()) { $info = new SplFileInfo($filename); $data += array('webroot' => preg_replace('/\\/$/', '', WWW_ROOT), 'model' => Inflector::tableize($name), 'field' => strtolower($field), 'filename' => $info->getBasename($info->getExtension()), 'extension' => $info->getExtension(), 'id' => $id, 'style' => $style, 'hash' => md5($info->getFilename() . Configure::read('Security.salt'))); foreach (static::$_interpolations as $name => $closure) { $data[$name] = $closure($info); } return String::insert($string, $data); }
/** * @param \SplFileInfo $fileInfo * @return PHPPropertyFile * @throws InvalidArgumentException */ public static function fromFileInfo(\SplFileInfo $fileInfo) { if (preg_match(self::FILE_NAME_REGEX, $fileInfo->getBasename(), $matches) !== 1) { throw new InvalidArgumentException(); } $file = new PHPFile($fileInfo); $property = Property::ofType($matches['type']); return new self($file, $property); }
public function getContent() { $info = new \SplFileInfo($this->file); $renderer = new PhpRenderer(); $stack = new TemplatePathStack(); $stack->addPath($info->getPath()); $stack->setDefaultSuffix(pathinfo($this->file, PATHINFO_EXTENSION)); $renderer->setResolver($stack); return $renderer->render($info->getBasename()); }
/** * Builds a UnitOfWork instance from the given \SplFileInfo * * @param \SplFileInfo $fileInfo The fileInfo to build from * * @throws \InvalidArgumentException * * @return UnitOfWork The instantiated migration */ public static function buildFromSplFileInfo(\SplFileInfo $fileInfo) { $uniqueId = $fileInfo->getBasename(); $file = $fileInfo->openFile(); $query = ''; while (!$file->eof()) { $query .= $file->fgets(); } return new UnitOfWork(new Uid($uniqueId), new Workload($query), new \DateTime()); }
/** * @param \SplFileInfo $fileInfo * @return PHPRangeFile * @throws InvalidArgumentException */ public static function fromFileInfo(\SplFileInfo $fileInfo) { if (preg_match(self::FILE_NAME_REGEX, $fileInfo->getBasename(), $matches) !== 1) { throw new InvalidArgumentException(); } $range = new Range((int) $matches['start'], (int) $matches['end']); $file = new PHPFile($fileInfo); $total = (int) $matches['total']; return new self($file, $range, $total); }
/** * @param null $rootPath * @param null $virtualRootPath path used as a virtual root path for served files * By default the directory name */ public function __construct($rootPath = null, $virtualRootPath = null) { $this->rootPath = $rootPath; $this->fs = new Filesystem(); if ($virtualRootPath) { $this->virtualRootPath = $virtualRootPath; } else { $file = new \SplFileInfo($rootPath); $this->virtualRootPath = '/' . $file->getBasename(); } }
/** * @param FileUpload $fileUpload * @return string */ public static function sanitizeFileName(FileUpload $fileUpload) { $filename = $fileUpload->getSanitizedName(); $filename = Strings::lower($filename); $fileInfo = new \SplFileInfo($filename); $suffix = $fileInfo->getExtension(); $basename = $fileInfo->getBasename(".{$suffix}"); $hash = md5($fileUpload->getContents()); $hash = Strings::substring($hash, 0, 9); return Strings::substring($basename, 0, 50) . "_{$hash}.{$suffix}"; }
public function hasFile($file) { if (!$file instanceof \SplFileInfo) { $file = new \SplFileInfo($file); } if (0 !== strpos($file->getRealPath(), realpath($this->getResource()))) { return false; } if ($this->getPattern()) { return (bool) preg_match($this->getPattern(), $file->getBasename()); } return true; }
private function registerResources() { $namespace = __NAMESPACE__ . '\\Resource'; foreach (glob(__DIR__ . '/Resource/*.php') as $filename) { $file = new \SplFileInfo($filename); $className = $file->getBasename('.php'); $reflectionClass = new \ReflectionClass($namespace . '\\' . $className); if ($reflectionClass->isSubclassOf(Resource::class) && !$reflectionClass->isAbstract()) { $resource = $reflectionClass->newInstanceArgs([$this->httpMethodsClient]); $resourceName = lcfirst($className); $this->resources[$resourceName] = $resource; } } }
function convert($fn) { $info = new SplFileInfo($fn); $cwd = getcwd(); $dir = $cwd."/html_files"; $outputFile = $dir ."/". $info->getBasename("docx") ."html"; $infile = $info->getPathname(); if( ! is_dir($dir) ) system("mkdir -p $dir"); /*! ** Should test to see if on OSX or Webfaction and use the approriate binary */ $cmd = "/Applications/LibreOffice.app/Contents/MacOS/soffice --headless --convert-to \"html:XHTML Writer File:UTF8\" --outdir $dir $infile"; system($cmd); print "cwd : $cwd\n"; print "infile basename: ".$info->getBasename("docx")."\n"; print "infile: $infile\n"; print "outputFile: $outputFile\n"; return $outputFile; // file_get_contents("$dir/"); }
/** * Retrieve directory content, directories and files * * @param Application $app Silex Application * @param Request $request Request parameters * * @return JsonResponse Array of objects */ function get_content(Application $app, Request $request) { $dirpath = Utils\check_path($app['cakebox.root'], $request->get('path')); if (!isset($dirpath)) { $app->abort(400, "Missing parameters"); } $finder = new Finder(); $finder->followLinks()->depth('< 1')->in("{$app['cakebox.root']}/{$dirpath}")->ignoreVCS(true)->ignoreDotFiles($app['directory.ignoreDotFiles'])->notName($app["directory.ignore"])->sortByType(); $dirContent = []; foreach ($finder as $file) { if ($file->isLink()) { $linkTo = readlink("{$app['cakebox.root']}/{$dirpath}/{$file->getBasename()}"); if (file_exists($linkTo) == false) { continue; } $file = new \SplFileInfo($linkTo); } $pathInfo = []; $pathInfo["name"] = $file->getBasename(); $pathInfo["type"] = $file->getType(); $pathInfo["mtime"] = $file->getMTime(); $pathInfo["size"] = Utils\get_size($file); $pathInfo["access"] = str_replace('%2F', '/', rawurlencode("{$app['cakebox.access']}/{$dirpath}/{$file->getBasename()}")); $pathInfo["extraType"] = ""; $ext = strtolower($file->getExtension()); if (in_array($ext, $app["extension.video"])) { $pathInfo["extraType"] = "video"; } else { if (in_array($ext, $app["extension.audio"])) { $pathInfo["extraType"] = "audio"; } else { if (in_array($ext, $app["extension.image"])) { $pathInfo["extraType"] = "image"; } else { if (in_array($ext, $app["extension.archive"])) { $pathInfo["extraType"] = "archive"; } else { if (in_array($ext, $app["extension.subtitle"])) { $pathInfo["extraType"] = "subtitle"; } } } } } array_push($dirContent, $pathInfo); } return $app->json($dirContent); }
public function filter(\Nette\Latte\MacroNode $node, \Nette\Latte\PhpWriter $writer) { $path = $node->tokenizer->fetchWord(); $params = $writer->formatArray(); $path = $this->moduleHelpers->expandPath($path, 'Resources/public'); if (!$this->debugMode) { $sass = new \SassParser(); $file = new \SplFileInfo($path); $targetFile = $file->getBasename() . '-' . md5($path . filemtime($path)) . '.css'; $targetDir = $this->wwwCacheDir . '/sass'; $target = $targetDir . '/' . $targetFile; $targetUrl = substr($target, strlen($this->wwwDir)); if (!file_exists($targetDir)) { umask(00); mkdir($targetDir, 0777, true); } $css = $sass->toCss($path); file_put_contents($target, $css); return '$control->getPresenter()->getContext()->getService("assets.assetManager")->addStylesheet("' . $targetUrl . '", ' . $params . '); '; } else { return ' $_sass_file = new \\SplFileInfo("' . $path . '"); $_sass_targetFile = $_sass_file->getBasename() . \'-\' . md5(\'' . $path . '\') . \'-\' . md5(\'' . $path . '\' . filemtime("' . $path . '")) . \'.css\'; $_sass_targetDir = \'' . $this->wwwCacheDir . '/sass\'; $_sass_target = $_sass_targetDir . \'/\' . $_sass_targetFile; $_sass_targetUrl = substr($_sass_target, strlen(\'' . $this->wwwDir . '\')); if (!file_exists($_sass_target)) { $_sass = new \\SassParser(); if (!file_exists($_sass_targetDir)) { umask(0000); mkdir($_sass_targetDir, 0777, true); } // Remove old files foreach (\\Nette\\Utils\\Finder::findFiles($_sass_file->getBasename() . \'-\' . md5(\'' . $path . '\') . \'-*\')->from($_sass_targetDir) as $_sass_old) { unlink($_sass_old->getPathname()); } $_sass_css = $_sass->toCss(\'' . $path . '\', $_sass_target); file_put_contents($_sass_target, $_sass_css); } $control->getPresenter()->getContext()->getService("assets.assetManager")->addStylesheet($_sass_targetUrl, ' . $params . '); '; } }
private function getComposerInformation(\SplFileInfo $file) { $zip = new \ZipArchive(); $zip->open($file->getPathname()); if (0 == $zip->numFiles) { return false; } $foundFileIndex = $zip->locateName('composer.json', \ZipArchive::FL_NODIR); if (false === $foundFileIndex) { return false; } $configurationFileName = $zip->getNameIndex($foundFileIndex); $composerFile = "zip://{$file->getPathname()}#{$configurationFileName}"; $json = file_get_contents($composerFile); $package = JsonFile::parseJson($json, $composerFile); $package['dist'] = array('type' => 'zip', 'url' => $file->getRealPath(), 'reference' => $file->getBasename(), 'shasum' => sha1_file($file->getRealPath())); $package = $this->loader->load($package); return $package; }
/** * Load class from specified file. * * @param \SplFileInfo $file * * @return TestCase * * @throws FilterException If cannot open file * @throws FilterException If TestCase class does not exists in this file */ public static function load(\SplFileInfo $file) { if (!$file->isReadable()) { throw new FilterException(sprintf('Cannot open file "%s"', $file->getRealPath())); } $loadedClasses = get_declared_classes(); include_once $file; $loadedClasses = array_reverse(array_values(array_diff(get_declared_classes(), $loadedClasses))); $name = $file->getBasename('.php'); /** @var TestCase $class */ foreach ($loadedClasses as $class) { if (preg_match('{^([\\w\\\\]+\\\\)?' . $name . '$}', $class)) { if (is_subclass_of($class, '\\Unteist\\TestCase')) { return new $class(); } } } throw new FilterException(sprintf('TestCase class does not found in file "%s"', $file->getRealPath())); }