/** * Class constructor. * * @param \BackBee\BBApplication $application * @param array $config */ public function __construct(BBApplication $application, array $config) { $this->_application = $application; $this->_config = $config; if (true === array_key_exists('basedir', $config)) { $this->_basedir = $config['basedir']; File::resolveFilepath($this->_basedir, null, array('include_path' => $this->_application->getRepository())); } else { $this->_basedir = $this->_application->getRepository(); } }
/** * Handles a media file request. * * @param string $filename The media file to provide * * @throws FrontControllerException * * @return Response */ public function mediaAction($type, $filename, $includePath = array()) { $includePath = array_merge($includePath, array($this->application->getStorageDir(), $this->application->getMediaDir())); if (null !== $this->application->getBBUserToken()) { $includePath[] = $this->application->getTemporaryDir(); } $matches = array(); if (preg_match('/([a-f0-9]{3})\\/([a-f0-9]{29})\\/(.*)\\.([^\\.]+)/', $filename, $matches)) { $filename = $matches[1] . '/' . $matches[2] . '.' . $matches[4]; } elseif (preg_match('/([a-f0-9]{4})([a-f0-9]{4})([a-f0-9]{4})([a-f0-9]{4})([a-f0-9]{4})([a-f0-9]{4})([a-f0-9]{4})([a-f0-9]{4})\\/.*\\.([^\\.]+)/', $filename, $matches)) { $filename = $matches[1] . $matches[2] . $matches[3] . $matches[4] . $matches[5] . $matches[6] . $matches[7] . $matches[8] . '.' . $matches[9]; File::resolveMediapath($filename, null, array('include_path' => $includePath)); } File::resolveFilepath($filename, null, array('include_path' => $includePath)); $this->application->info(sprintf('Handling image URL `%s`.', $filename)); if (false === file_exists($filename) || false === is_readable($filename)) { $request = $this->application->getRequest(); throw new FrontControllerException(sprintf('The file `%s` can not be found (referer: %s).', $request->getHost() . '/' . $request->getPathInfo(), $request->server->get('HTTP_REFERER')), FrontControllerException::NOT_FOUND); } return $this->createMediaResponse($filename); }
public function removeThumbnail(Layout $layout, BBApplication $app) { $thumbnailfile = $layout->getPicPath(); if (empty($thumbnail)) { return true; } File::resolveFilepath($thumbnailfile, null, array('include_path' => $app->getResourceDir())); while (true === is_file($thumbnailfile) && true === is_writable($thumbnailfile)) { @unlink($thumbnailfile); $thumbnailfile = $layout->getPicPath(); File::resolveFilepath($thumbnailfile, null, array('include_path' => $app->getResourceDir())); } return true; }
/** * Prepend one directory at the begining of resources dirs. * * @param type $dir * * @return ApplicationInterface */ public function unshiftResourceDir($dir) { File::resolveFilepath($dir); $resourcedir = $this->getResourceDir(); array_unshift($resourcedir, $dir); $this->resourceDir = $resourcedir; return $this; }
/** * Parse classcontent directories and hydrate categories attribute. * * @param array $directories classcontent directories */ private function loadCategoriesFromClassContentDirectories($directories) { $classcontents = []; foreach ($directories as $directory) { $classcontents = array_merge($classcontents, array_map(function ($path) use($directory) { return str_replace([DIRECTORY_SEPARATOR, '\\\\'], [NAMESPACE_SEPARATOR, NAMESPACE_SEPARATOR], AbstractContent::CLASSCONTENT_BASE_NAMESPACE . str_replace([$directory, '.yml'], ['', ''], $path)); }, File::getFilesRecursivelyByExtension($directory, 'yml'))); } foreach ($classcontents as $class) { try { if (class_exists($class)) { $this->buildCategoryFromClassContent(new $class()); } } catch (ClassNotFoundException $e) { // nothing to do } } }
/** * Returns the default classcontent thumbnail filepath. * * @param array $base_directories list of every resources directories of current application * * @return string */ private function getDefaultClassContentThumbnailFilepath(array $base_directories) { $filename = 'default_thumbnail.png'; File::resolveFilepath($filename, null, array('include_path' => $base_directories)); return $filename; }
/** * Return the real yaml file path of the loading class. * * @param string $path * * @return string The real path if found */ private function resolveFilePath($path) { $path = str_replace(array($this->_protocol . '://', '/'), array('', DIRECTORY_SEPARATOR), $path); foreach ($this->_includeExtensions as $ext) { $filename = $path . $ext; File::resolveFilepath($filename, null, array('include_path' => $this->_classcontentdir)); if (true === is_file($filename)) { return $filename; } } return $path; }
public static function onFlushElementFile(Event $event) { $revision = $event->getTarget(); $content = $revision->getContent(); if (!$content instanceof ElementFile || !is_file($content->path)) { return; } $application = $event->getApplication(); $em = $application->getEntityManager(); $uow = $em->getUnitOfWork(); if ($uow->isScheduledForDelete($content)) { return; } $fileRepository = $em->getRepository('BackBee\\ClassContent\\Element\\File'); $fileRepository->setDirectories($application); $fileRepository->commitFile($content); $moveFrom = $content->path; File::resolveFilepath($moveFrom, null, array('base_dir' => $application->getMediaDir())); $content->setParam('stat', json_encode(stat($moveFrom))); if ($content instanceof ElementImage) { list($width, $height) = getimagesize($moveFrom); $content->setParam('width', $width); $content->setParam('height', $height); } $uow->recomputeSingleEntityChangeSet($em->getClassMetadata('BackBee\\ClassContent\\Revision'), $revision); }
/** * Move an uploaded file to the temporary directory and update file content. * * @param \BackBee\CoreDomain\ClassContent\AbstractClassContent $file * @param string $newfilename * @param string $originalname * * @return boolean|string * @throws \BackBee\ClassContent\Exception\ClassContentException Occures on invalid content type provided */ public function updateFile(AbstractClassContent $file, $newfilename, $originalname = null, $src = null) { if (false === $file instanceof ElementFile) { throw new ClassContentException('Invalid content type'); } if (null === $originalname) { $originalname = $file->originalname; } $base_dir = $this->_temporarydir; $file->originalname = $originalname; $file->path = Media::getPathFromContent($file); if (null === $file->getDraft()) { $base_dir = $this->isInMediaLibrary($file) ? $this->_mediadir : $this->_storagedir; } $moveto = $file->path; File::resolveFilepath($moveto, null, array('base_dir' => $base_dir)); try { if ($src === null) { File::resolveFilepath($newfilename, null, array('base_dir' => $this->_temporarydir)); File::move($newfilename, $moveto); } else { $dir = dirname($moveto); if (!is_dir($dir)) { File::mkdir($dir); } file_put_contents($moveto, base64_decode($src)); } $this->dispatchPostUploadEvent($moveto, $file->path); } catch (\BackBee\Exception\BBException $e) { return false; } return $moveto; }
/** * Returns complete url which match with routeName and routeParams; you can also customize * the base url; by default it use current site base url. * * @param string $name The name of the route to look for. * @param array|null $params Optional, parameters to apply to the route. * @param string|null $baseUrl Optional, base URL to use rather than the computed one. * @param boolean $addExt If true adds the default extension to result. * @param Site|null $site Optional, the site for which the uri will be built. * @param boolean $buildQuery If true, adds unused parameters in querystring * * @return string The computed URL. */ public function getUrlByRouteName($name, array $params = null, $baseUrl = null, $addExt = true, Site $site = null, $buildQuery = false) { $paramsToAdd = []; $uri = $this->applyRouteParameters($this->getRoutePath($name), (array) $params, $paramsToAdd); $path = $this->getUri($baseUrl . $uri, null, $site); if (true !== $addExt) { $path = File::removeExtension($path); } if (!empty($paramsToAdd) && true === $buildQuery) { $path = $path . '?' . http_build_query($paramsToAdd); } return $path; }
public function renderTemplate($filename, array $templateDir, array $params = [], array $vars = []) { foreach ($params as $key => $v) { $this->setParam($key, $v); } foreach ($vars as $k => $v) { $this->assign($k, $v); } try { File::resolveFilepath($filename, null, array('include_path' => $templateDir)); ob_start(); include $filename; return ob_get_clean(); } catch (FrontControllerException $fe) { ob_end_clean(); throw $fe; } catch (Exception $e) { ob_end_clean(); throw new RendererException($e->getMessage() . ' in ' . $filename, RendererException::RENDERING_ERROR, $e); } }
/** * Tries to match a URL with a set of routes. * * @param string $pathinfo The path info to be parsed (raw format, i.e. not urldecoded) * * @return array An array of parameters * * @throws ResourceNotFoundException If the resource could not be found * @throws MethodNotAllowedException If the resource was found but the request method is not allowed */ public function match($pathinfo) { $pathinfo = File::normalizePath($pathinfo, '/', false); return parent::match($pathinfo); }
/** * Updates a file script of a layout. * * @param Layout $layout The layout to update * * @return string The filename of the updated script */ public function updateLayout(Layout $layout) { if (null === $layout->getSite()) { return false; } $layoutfile = $this->getLayoutFile($layout); File::resolveFilepath($layoutfile, null, array('include_path' => $this->_layoutdir)); if (false === file_exists($layoutfile)) { File::resolveFilepath($layoutfile, null, array('base_dir' => $this->_layoutdir[1])); } if (false === file_exists($layoutfile) && false === touch($layoutfile)) { throw new RendererException(sprintf('Unable to create file %s.', $layoutfile), RendererException::LAYOUT_ERROR); } if (!is_writable($layoutfile)) { throw new RendererException(sprintf('Unable to open file %s in writing mode.', $layoutfile), RendererException::LAYOUT_ERROR); } return $layoutfile; }
/** * @see BackBee\Renderer\RendererInterface::partial() */ public function partial($template = null, $params = null) { $this->templateFile = $template; File::resolveFilepath($this->templateFile, null, array('include_path' => $this->_scriptdir)); if (!is_file($this->templateFile) || !is_readable($this->templateFile)) { throw new RendererException(sprintf('Unable to find file \'%s\' in path (%s)', $template, implode(', ', $this->_scriptdir)), RendererException::SCRIPTFILE_ERROR); } // Assign parameters if (null !== $params) { $params = (array) $params; foreach ($params as $param => $value) { $this->setParam($param, $value); } } return $this->renderTemplate(true); }
public static function onRemoveElementFile(Event $event) { $dispatcher = $event->getDispatcher(); $application = $dispatcher->getApplication(); try { $content = $event->getEventArgs()->getEntity(); if (!$content instanceof ElementFile) { return; } $includePath = array($application->getStorageDir(), $application->getMediaDir()); if (null !== $application->getBBUserToken()) { $includePath[] = $application->getTemporaryDir(); } $filename = $content->path; File::resolveFilepath($filename, null, array('include_path' => $includePath)); @unlink($filename); } catch (\Exception $e) { $application->warning('Unable to delete file: ' . $e->getMessage()); } }
/** * Upload file from a base64 * * @param String $src base64 * @param String $originalName * @return Array $data */ private function doUpload($src, $originalName) { $data = $this->buildData($originalName, File::getExtension($originalName, false)); file_put_contents($data['path'], base64_decode($src)); return $data; }
/** * */ private function _init() { if ($this->isInitialised) { return; } if (false === file_exists($this->getConfig('extractedDir'))) { $res = mkdir($this->getConfig('extractedDir'), 0777, true); if (false === $res) { throw new \Exception('Could not create tmp dir: ' . $this->getConfig('extractedDir')); } } $archiveFile = $this->getConfig('archive'); // if remote file, copy to tmp dir if (0 === strpos($archiveFile, 'https://') || 0 === strpos($archiveFile, 'http://') || 0 === strpos($archiveFile, 'ftp://')) { $tempFile = tempnam(sys_get_temp_dir(), basename($archiveFile)); copy($archiveFile, $tempFile); $archiveFile = $tempFile; } File::extractZipArchive($archiveFile, $this->getConfig('extractedDir'), true); // delegate to FileSystem connector $this->fileSystemConnector = new FileSystem($this->_application, array('basedir' => $this->getConfig('extractedDir'))); $this->isInitialised = true; }
/** * Returns an array of YAML files in the directory. * * @param string $basedir The base directory * * @return array * * @throws \BackBee\Config\Exception\InvalidBaseDirException Occurs if the base directory cannont be read */ private function getYmlFiles($basedir) { $ymlFiles = File::getFilesByExtension($basedir, self::EXTENSION); $defaultFile = $basedir . DIRECTORY_SEPARATOR . self::CONFIG_FILE . '.' . self::EXTENSION; if (is_file($defaultFile) && 1 < count($ymlFiles)) { // Ensure that config.yml is the first one $ymlFiles = array_diff($ymlFiles, array($defaultFile)); array_unshift($ymlFiles, $defaultFile); } foreach ($ymlFiles as &$file) { $name = basename($file); if (in_array(substr($name, 0, strrpos($name, '.')), $this->yml_names_to_ignore)) { $file = null; } } return array_filter($ymlFiles); }
/** * If folder is not present create it and then copy the file * * @param string $oldImagePath The source file path * @param string $newImagePath The target file path * * @return void * * @throws \InvalidArgumentException * @throws ApplicationException */ protected function createDirAndCopyFile($oldImagePath, $newImagePath) { try { if (!is_dir(dirname($newImagePath))) { File::mkdir(dirname($newImagePath)); } File::copy($oldImagePath, $newImagePath); } catch (InvalidArgumentException $e) { throw new \InvalidArgumentException($e->getMessage()); } catch (ApplicationException $e) { throw $e; } }
/** * Returns classnames of all classcontents element * * @return array Contains every BackBee's element classcontent classnames */ public function getAllElementClassContentClassnames() { $directory = $this->application->getBBDir() . DIRECTORY_SEPARATOR . 'ClassContent'; $classnames = array_map(function ($path) use($directory) { return str_replace([DIRECTORY_SEPARATOR, '\\\\'], [NAMESPACE_SEPARATOR, NAMESPACE_SEPARATOR], AbstractClassContent::CLASSCONTENT_BASE_NAMESPACE . str_replace([$directory, '.yml'], ['', ''], $path)); }, File::getFilesRecursivelyByExtension($directory, 'yml')); $classnames[] = AbstractClassContent::CLASSCONTENT_BASE_NAMESPACE . 'ContentSet'; return $classnames; }
public function testResolveFilepath() { $twigFilePath = $this->getFixturesFolder() . 'file.twig'; File::resolveFilepath($twigFilePath); $this->assertEquals($this->getFixturesFolder() . 'file.twig', $twigFilePath); }
/** * Returns all content classnames found in $directory. * * @param string $directory The directory to look at. * * @return string[] An array of content classnames found in directory. */ public static function getClassContentClassnamesFromDir($directory) { if (!is_dir($directory)) { return []; } return array_map(function ($path) use($directory) { return str_replace([DIRECTORY_SEPARATOR, '\\\\'], [NAMESPACE_SEPARATOR, NAMESPACE_SEPARATOR], AbstractClassContent::CLASSCONTENT_BASE_NAMESPACE . str_replace([$directory, '.yml'], ['', ''], $path)); }, File::getFilesRecursivelyByExtension($directory, 'yml')); }
/** * Returns the computed storage filename base on an uid. * * @param string $uid * @param string $originalname * @param int $folder_size * @param boolean $include_originalname * * @return string * * @throws \BackBee\Exception\InvalidArgumentException Occurs if the provided $uid is invalid */ public static function getPathFromUid($uid, $originalname, $folder_size = 3, $include_originalname = false) { if (false === is_string($uid) || true === empty($uid)) { throw new InvalidArgumentException('Enable to compute path, the provided uid is not a valid string'); } $folder = ''; $filename = $uid; if (0 < $folder_size && strlen($uid) > $folder_size) { $folder = substr($uid, 0, $folder_size) . DIRECTORY_SEPARATOR; $filename = substr($uid, $folder_size); } if (true === $include_originalname) { $filename .= DIRECTORY_SEPARATOR . $include_originalname; } else { $extension = File::getExtension($originalname, true); $filename .= $extension; } return $folder . $filename; }