public function createFileNode(Element $parentElement, $desiredFilename, $workingFilePath, StorageFacilityFile $preconfiguredFile = null) { if (empty($desiredFilename)) { $desiredFilename = $this->filenameFromBasename(basename($workingFilePath)); } $path = pathinfo($workingFilePath); $ext = !empty($path['extension']) ? strtolower($path['extension']) : ''; if (in_array(strtolower($ext), array_map("strtolower", $this->mediaRestrictedExtensions))) { throw new Exception('Cannot add file with restricted extension [' . $ext . ']'); } list($storageFacility, $sfParams) = $this->deriveStorageFacility($parentElement); $element = $this->NodeRefService->oneFromAspect('@files')->getElement(); $file = $preconfiguredFile !== null ? $preconfiguredFile : new StorageFacilityFile(); $file->setId($storageFacility->findUniqueFileID($sfParams, $desiredFilename)); $file->setLocalPath($workingFilePath); $file = $storageFacility->putFile($sfParams, $file); list($width, $height) = ImageUtils::getImageDimensions($file->getLocalPath()); $mimetype = FileSystemUtils::getMimetype($file->getExtension()); //CREATE FILE NODE & SAVE $nodeRef = new NodeRef($element, SlugUtils::createSlug($file->getId())); $nodeRef = $this->NodeService->generateUniqueNodeRef($nodeRef, null, true); $node = $nodeRef->generateNode(); $this->NodeMapper->defaultsOnNode($node); $node->Title = $file->getId(); $node->setMeta('#url', $file->getURL()); // $node->setMeta('#path',$file->getLocalPath()); $node->setMeta('#mimetype', $mimetype); $node->setMeta('#size', filesize($file->getLocalPath())); $node->setMeta('#width', $width); $node->setMeta('#height', $height); $node->setMeta('#parent-element', $parentElement->Slug); $this->NodeService->add($node); return $node; }
public static function getInstance() { if (!self::$fileSystemUtils) { self::$fileSystemUtils = new FileSystemUtils(); return self::$fileSystemUtils; } return self::$fileSystemUtils; }
public function testFixtures() { $this->createFixtures(); $directories = FileSystemUtils::listDirectories($this->workDir . '/.composer/global'); $this->assertEquals('testorg', implode(',', $directories)); $directories = FileSystemUtils::listDirectories($this->workDir . '/.composer/global/testorg'); $this->assertEquals('testproject', implode(',', $directories)); $projects = FileSystemUtils::allInstalledProjectsInBaseDir($this->workDir . '/.composer/global'); $this->assertEquals('testorg/testproject', implode(',', $projects)); }
/** * Run our command. Set up the environment, as needed, ensuring that * it is restored at the end of the run. */ public function run($stdoutFile = '') { $commandString = $this->getCommandString(); // print ">> $commandString\n"; $origEnv = $this->env->apply($this->env); $origDir = FileSystemUtils::applyDir($this->dir); $exitCode = static::runCommand($commandString, $stdoutFile); $origEnv->apply(); FileSystemUtils::applyDir($origDir); return $exitCode; }
public function transferTo($filename) { if (!$this->isEmpty() && is_uploaded_file($this->tempName)) { if (@FileSystemUtils::safeCopy($this->tempName, $filename)) { return true; } if (@move_uploaded_file($this->tempName, $filename)) { return true; } } return FALSE; }
/** * This function copies the file from the local path (specified in the {@link $file}) to the generated storage * path; creating any directories as needed. The public URL will be set on the {@link $file} upon successful * persistence to the filesystem. * * @param Site $site Site used to determine storage location * @param StorageFacilityFile &$file File to store * * @return StorageFacilityFile Fully-resolved and stored file, has URL and id * set appropriately to reference the stored file later * @throws StorageFacilityException upon failure */ public function putFile(StorageFacilityParams $params, StorageFacilityFile &$file) { $storagePath = $this->generateStoragePath($params, $file->getId()); // $this->createDirectory($storagePath); if (is_file($file->getLocalPath())) { try { FileSystemUtils::safeCopy($file->getLocalPath(), $storagePath); } catch (Exception $e) { throw new StorageFacilityException($e->getMessage()); } } else { throw new StorageFacilityException("Local file not found '" . $file->getLocalPath() . "'"); } $file->setLocalPath($storagePath); $file->setUrl($this->generateUrl($params, $file->getId())); return $file; }
/** * * Construct a Storage instance placed inside the specified folder with the specified name, * of the specified type. * * @param string $folder the folder name, as a string. * @param string $name the storage file name, as a string. * @param string $storage_t the storage file, actually the file extension. * @throws \Mbcraft\Piol\IOException if the parameters does not point to a valid storage location. * * @internal */ protected function __construct($folder, $name, $storage_t) { /* if (!preg_match(self::VALID_FOLDER_AND_STORAGE_NAME_PATTERN,$folder)) throw new IOException("Nome del folder non valido!"); if (!preg_match(self::VALID_FOLDER_AND_STORAGE_NAME_PATTERN,$name)) throw new IOException("Nome del file non valido!"); */ $this->folder = $folder; $this->name = $name; $storage_dir = StorageFactory::getProtectedStorage(); $this->storage_type = $storage_t; $p = $storage_dir->getPath() . $folder . DS; $this->storage_dir = new Dir($p); if (!FileSystemUtils::isValidFilename($name . "." . $storage_t)) { throw new IOException("The specified string is not a valid filename."); } $p = $storage_dir->getPath() . $folder . DS . $name . DOT . $storage_t; $this->storage_file = new File($p); }
function execute() { $file_or_folder = $this->file_or_folder; $force = $this->force; if (self::$dummy_mode) { echo "Removing : " . $file_or_folder . "<br />"; return; } $root_dir_path = self::$root_dir->getPath(); //se è una cartella elimino solo i file che sono anche nel modulo if (FileSystemUtils::isDir($this->module_dir->getPath() . $file_or_folder)) { $source_dir = new Dir($this->module_dir->getPath() . $file_or_folder); $target_dir = new Dir($root_dir_path . $file_or_folder); if (!$target_dir->exists()) { return; } $toremove_files = $source_dir->listFiles(); foreach ($toremove_files as $elem) { if ($elem->isDir()) { $this->remove($file_or_folder . $elem->getName() . DS); } else { $this->remove($file_or_folder . $elem->getFilename()); } } if ($target_dir->isEmpty()) { $target_dir->delete(false); } } else { $source_file = new File($this->module_dir->getPath() . $file_or_folder); $target_file = new File($root_dir_path . $file_or_folder); if (!$force && !$source_file->exists()) { return; } //se non esiste nel modulo non lo rimuovo $target_file->delete(); } }
/** * * Copies this file to the target folder. * * @param \Mbcraft\Piol\Dir|string $target_dir The target dir or string path to copy this file into. * @param string $new_name An optional new name for the copied file. * @return boolean true if this operation was successfull, false otherwise. * * @api */ public function copy($target_dir, $new_name = null) { $t_dir = Dir::asDir($target_dir); if ($new_name == null) { $n_name = $this->getFullName(); } else { FileSystemUtils::checkValidFilename($new_name); $n_name = $new_name; } return copy($this->__full_path, $t_dir->__full_path . $n_name); }
protected function deriveMetaDatatype(ValidationExpression $ve) { $v = $ve->getValidationArray(); $datatype = $v['datatype']; switch ($datatype) { case 'flag': return 'flag'; case 'boolean': return 'tiny'; case 'date': if (isset($v['unix']) && !StringUtils::strToBool($v['unix'])) { return 'datetime'; } // If unix attribute is not specified, assume they want date (timestamp) for backward-compatibility return 'date'; case 'int': $min = isset($v['min']) ? (int) $v['min'] : 0; $max = isset($v['max']) ? (int) $v['max'] : PHP_INT_MAX; if ($min < 0) { if ($min >= -128 && $max <= 127) { return 'tiny-signed'; } else { if ($min >= -2147483648 && $max <= 2147483647) { return 'int-signed'; } } return 'long-signed'; } if ($max < 255) { return 'tiny'; } else { if ($max <= 4294967295) { return 'int'; } } return 'long'; case 'float': return 'float'; case 'slug': case 'slugwithslash': case 'email': $ve->setMax(255); // set max return 'varchar'; case 'json': $ve->setMax(262144); //set max to 256K return 'mediumtext'; case 'string': case 'html': case 'url': // NOTE: MySQL columns are bytes, string lengths are characters $max = 255; // default is 255 if (isset($v['max'])) { $max = (int) FileSystemUtils::iniValueInBytes($v['max']); } if ($max == 65536) { $max = 65535; } if ($max > 262144) { // max is 256K $max = 262144; } $ve->setMax($max); // set max if ($max <= 255) { // 255 or less is VARCHAR return 'varchar'; } if ($max <= 65535) { // 64K or less is TEXT return 'text'; } if ($max <= 262144) { // 256K or less is MEDIUMTEXT return 'mediumtext'; } case 'binary': $max = 262144; // default is 256K if (isset($v['max'])) { $max = (int) FileSystemUtils::iniValueInBytes($v['max']); } if ($max == 65536) { $max = 65535; } if ($max > 262144) { // max is 256K $max = 262144; } $ve->setMax($max); // set max if ($max <= 65535) { // 64K or less, store as BLOB return 'blob'; } if ($max <= 262144) { // 256K or less, store as MEDIUMBLOB return 'mediumblob'; } } }
/** * Constructs a file cache store object. * * @param Logger $Logger our Logger * @param DateFactory $DateFactory IoC Datefactory * @param string $fileCacheDirectory The absolute path where our files will be stored without trailing '/' * @param string $fileCachePrefixKey A prefix for the cache keys * @param boolean $fileCacheEnabled Flag to determine if caching is enabled * @param string $fileCacheExtension The file extension to use for cache files. */ public function __construct(LoggerInterface $Logger, DateFactory $DateFactory, $fileCacheDirectory, $fileCacheCachePrefixKey = '', $fileCacheEnabled = false, $fileCacheExtension = 'cfcache') { if ($fileCacheEnabled) { // Verify the directory exists and is writable if (!is_writable($fileCacheDirectory) && !@FileSystemUtils::recursiveMkdir($fileCacheDirectory)) { throw new CacheException("Directory '{$fileCacheDirectory}' does not exist or is not writable."); } // Remove any trailing DIRECTORY_SEPARATOR passed in // For example '/home/crowdfusion/filestore/' becomes '/home/crowdfusion/filestore' $fileCacheDirectory = rtrim($fileCacheDirectory, DIRECTORY_SEPARATOR); // Set our vars $this->cachePrefixKey = str_replace(' ', '', $fileCacheCachePrefixKey); $this->Logger = $Logger; $this->DateFactory = $DateFactory; $this->dir = $fileCacheDirectory; $this->enabled = $fileCacheEnabled; $this->fileExtension = $fileCacheExtension; $this->Logger->debug("Set FileStore options:\n" . "\tCachePrefix: {$fileCacheCachePrefixKey}\n" . "\tEnabled: TRUE"); } else { $this->enabled = false; } }
/** * Moves the file from the themes to the public app directory * * NOTE: the following code will overwrite files * * @param string $relpath The relative path where the file lives * @param string $filename The file to move * * @return string the full path and filename of the moved file */ public function putFile($relpath, $filename, $ts) { $basedir = $this->getBaseDeployDirectory() . $this->subject . '/'; //move files from themes to public app directory $newfile = $basedir . $relpath; // @FileSystemUtils::safeCopy($filename, $newfile); // $ts = filemtime($filename); if (!file_exists($newfile) || $ts != filemtime($newfile)) { @FileSystemUtils::safeCopy($filename, $newfile); //@touch($newfile,$ts); //preserve original modified time } return new StorageFacilityFile('/' . ltrim($relpath, '/'), $newfile); }
/** * Combines all the listed files into a single file at {@link $aggregatePath} * * @param string $md5 The md5 (stored in the aggregate) * @param array $files A list of files to store * @param string $aggregatePath The name of the file to write our aggregate to * * @return array An array with urls as the keys and data as values */ protected function aggregateFiles($md5, array $files, $aggregatePath) { $this->Logger->debug('Rebuilding...'); $file = array("md5" => $md5, $this->subject => array(), "files" => $files); $aggregateContents = "<?php\n\n\$contents = \n" . var_export($file, true) . "\n\n?><?php\n \$" . $this->subject . " = array(\n "; foreach ($files as $filename) { if (!file_exists($filename)) { continue; } $fileContents = file_get_contents($filename); $fileContents = preg_replace('/\\$' . $this->subject . '\\s*\\=\\s*array\\s*\\(/i', '', $fileContents); $fileContents = preg_replace('/\\<\\?php/i', '', $fileContents); $fileContents = preg_replace('/\\)\\;\\s*(\\?\\>)?/', '', $fileContents); $aggregateContents .= $fileContents; // include $filename; //$subject = $this->subject; // if (isset($$subject)) { // foreach ($$subject as $url => $params) // $file[$this->subject][$url] = $params; // } } $aggregateContents .= " ); ?>"; // if (empty(${$this->subject})) // return array(); FileSystemUtils::safeFilePutContents($aggregatePath, $aggregateContents); include $aggregatePath; return ${$this->subject}; }
/** * * Saves the uploaded file into the specified folder optionally overriding the filename used during upload. * The temporary upload file is deleted. * * @param \Mbcraft\Piol\Dir|string $dir The Dir instance or string path of the folder in which save the uploaded file. * @param string $new_name the optional name to use for the file (overrides upload filename). * @return \Mbcraft\Piol\File a File instance pointing to the saved file, or null if an error occurred. * * @throws \Mbcraft\Piol\IOException if something goes wrong (eg. the provided filename is not valid). * * @api */ public function moveTo($dir, $new_name = null) { $final_dir = Dir::asDir($dir); FileSystemUtils::checkValidFilename($new_name); if ($new_name == null) { $real_filename = $this->getFullName(); } else { $real_filename = $new_name; } $final_file = $final_dir->newFile($real_filename); return $this->saveAs($final_file); }
protected function _importPhotosFromJson($file) { try { $contents = file_get_contents($file); $json = JSONUtils::decode($contents); foreach ($json as $v) { echo "importing {$v->title}..."; $url = $v->src; $parts = parse_url($url); $slug = SlugUtils::createSlug(basename($parts['path'])); preg_match('/(\\.\\w*)$/', $parts['path'], $ext); $nodeRef = $this->NodeRefService->oneFromAspect('@images'); $nodeRef = $this->NodeRefService->generateNodeRef($nodeRef, $slug); $node = $nodeRef->generateNode(); if (!$this->NodeService->refExists($node->getNodeRef())) { // go fetch file from url $data = $this->HttpRequest->fetchURL($url); // create a unique output file name $sourceFile = FileSystemUtils::secureTmpname($this->workDir, 'urlfetch', !empty($ext[1]) ? strtolower($ext[1]) : null); file_put_contents($sourceFile, $data); $node->Title = rtrim($v->title); $node->Status = "published"; $node->ActiveDate = $this->DateFactory->newStorageDate(); $node = $this->ImageService->storeMedia($sourceFile, $node, basename($parts['path'])); $this->NodeService->add($node); echo "done\n"; } else { echo "exists\n"; } unset($nodeRef); unset($node); } } catch (Exception $e) { echo "Exception: " . $e->getMessage() . "\n"; } }
/** * Marks up a string with paragraphs and automatically links any urls. * * This function marks up the output with paragraph tags and auto-links any URLs that are found. * The resulting output is suitable for display in any web-browser, but must have * paragraph and extra html tags removed before it's ready for editing. * * Content is XSS cleaned and stripped of all but a few tags (specified by implementation.) * * @param string $string The HTML string to format * @param string $allowedTags (optional) A comma-separated list of allowed tags. * * @return string A nicely-formatted version of the input text, with automatic paragraphs and urls in place * * @see unAutoParagraph() */ public function autoParagraph($string, $allowedTags = null, $linkUrls = true) { if (is_null($allowedTags)) { $allowedTags = $this->defaultAllowedTags; } if (is_null($this->purifier)) { require_once PATH_SYSTEM . '/vendors/HTMLPurifier.php'; $this->purifier = HTMLPurifier::instance(); FileSystemUtils::recursiveMkdir($this->vendorCacheDirectory . '/purifier/'); } if ($this->injectors == null && $linkUrls) { $this->injectors = array(new CF_HTMLPurifier_Injector_Linkify()); } $purifierConfig = array('Core.Encoding' => $this->charset, 'AutoFormat.AutoParagraph' => true, 'HTML.TidyLevel' => 'none', 'HTML.Allowed' => $allowedTags, 'Cache.SerializerPath' => $this->vendorCacheDirectory); if (!is_null($this->injectors)) { $purifierConfig['AutoFormat.Custom'] = $this->injectors; } $string = $this->purifier->purify($string, $purifierConfig); $string = str_replace("\n\n", '[DBLBR]', $string); $string = str_replace("\n", '<br/>', $string); $string = str_replace('[DBLBR]', "\n\n", $string); // trim links $string = preg_replace_callback("/\\<a\\s+href\\=\"(" . URLUtils::URL_MATCH . ")\"\\>\\1<\\/a\\>/Uix", array($this, 'trimCallback'), $string); // trim all words longer than 60 chars that aren't URLs, ignoring tags if (preg_match_all("/\\S60/", strip_tags(preg_replace('/(\\<(\\/?[^\\>]+)\\>)/', ' $1', $string)), $m)) { foreach ($m[0] as $n) { if (!preg_match("/" . URLUtils::URL_MATCH . "/", $n)) { $string = str_replace($n, trim(substr($n, 0, 60 - 3), '.') . '...', $string); } } } return $string; }
protected function executeExecImagick() { // get the width of the original image $retval = 1; $output = array(); exec("{$this->imageIdentifyExecPath} -format %w " . escapeshellarg($this->sourceFile) . " 2>&1", $output, $retval); if ($retval > 0) { throw new ImageFilterException("Unable to read source file."); } $width = $output[0] - $this->padding * 2; // Step 1. Generate the photo credit $op = ''; // store original values $targetFile = $this->targetFile; $this->targetFile = FileSystemUtils::secureTmpname($this->workDir, 'credit', '.' . $this->outputType); $op .= " -background '{$this->backgroundColor}'"; if ($this->fontColor != null) { $op .= " -fill '{$this->fontColor}'"; } if ($this->fontFamily != null) { $op .= " -font '{$this->fontFamily}'"; } if ($this->fontStyle != null) { $op .= " -style '{$this->fontStyle}'"; } if ($this->fontWeight != null) { $op .= " -weight '{$this->fontWeight}'"; } $op .= " -pointsize {$this->fontSize}"; // Force height to fontSize because IM < version 6.5.2-4 will ignore -pointsize to make the text fill the maximum width specified // I think this will limit all credit to 1 line of text $op .= " -size {$width}x{$this->fontSize}"; $op .= " -gravity {$this->anchor}"; $op .= " label:\"" . preg_replace('/"/', '\\"', $this->text) . "\""; $op .= " -bordercolor '{$this->backgroundColor}'"; $op .= " -border {$this->padding}x{$this->padding}"; $credit = ImagickExecFilterHelper::executeFilter($this, $op, true); // Step 2. Apply the photo credit // restore original values $this->targetFile = $targetFile; $op = ''; if ($this->type == 'overlay') { $op .= " -gravity {$this->anchor}"; $op .= " -draw 'image over 0,0 0,0 \"{$credit}\"'"; } else { if ($this->type == 'add') { $op .= " -background '{$this->backgroundColor}'"; $op .= " {$credit}"; if (preg_match('/^North/i', $this->anchor)) { $op .= " +swap"; } if (preg_match('/^(North|South)$/i', $this->anchor)) { $op .= " -gravity Center"; } else { if (preg_match('/East$/i', $this->anchor)) { $op .= " -gravity East"; } } $op .= " -append"; } } return ImagickExecFilterHelper::executeFilter($this, $op); }
<?php require_once 'IConstants.inc'; require_once $ConstantsArray['dbServerUrl'] . "FormValidator//validator.php"; require $ConstantsArray['dbServerUrl'] . "DataStoreMgr//FolderDataStore.php"; require $ConstantsArray['dbServerUrl'] . "DataStoreMgr//LocationDataStore.php"; require $ConstantsArray['dbServerUrl'] . "Utils//FileSystemUtils.php"; require $ConstantsArray['dbServerUrl'] . "Utils//StringUtils.php"; $LDS = LocationDataStore::getInstance(); $msg = ""; if ($_POST["formAction"] == "delete") { $pathL = $_POST['locationPath']; $isLocationEmpty = FileSystemUtils::isDirEmpty($pathL); if ($isLocationEmpty) { $LDS->deleteBySeq($_POST['editSeq']); FileSystemUtils::delete_NestedDirectory($pathL); $msg = StringUtils::getMessage("Location", "Location deleted successfully", false); } else { $msg = StringUtils::getMessage("Delete Location", "-The Location that you are trying to delete is related to folders.", true); } //Delte folder from location } $locations = $LDS->FindAll(); ?> <!DOCTYPE html> <html> <head> <?php include "_jsAdminInclude.php"; ?>
public function save() { if ($this->lockSystemChanges) { return; } if (!$this->changed) { return; } $xml = new SimpleXMLExtended('<system/>'); $test = $xml->addChild('plugins'); foreach ($this->plugins as $plugin) { $test->addXMLElement($this->SystemXMLConverter->pluginToXML($plugin)); } $test = $xml->addChild('elements'); foreach ($this->elements as $element) { $test->addXMLElement($this->SystemXMLConverter->elementToXML($element)); } $test = $xml->addChild('aspects'); foreach ($this->aspects as $aspect) { $test->addXMLElement($this->SystemXMLConverter->aspectToXML($aspect)); } $test = $xml->addChild('cmsnavitems'); foreach ($this->cmsNavItems as $navItem) { $test->addXMLElement($this->SystemXMLConverter->cmsNavItemToXML($navItem)); } $newContents = $xml->asPrettyXML(); $backup = $this->backupPath . '/system.' . $this->DateFactory->newStorageDate()->format('Y_m_d_His') . '.' . microtime(true) . '.xml'; FileSystemUtils::safeCopy($this->systemXMLFile, $backup); FileSystemUtils::safeFilePutContents($this->systemXMLFile, $newContents); $this->ApplicationContext->clearContextFiles(); $this->changed = false; $this->resetParsed(); }
/** * @dataProvider getBadExtensions * * @param string $extension */ public function testGetMimetypeBadExtensions($extension) { $this->assertEquals('application/octet-stream', \FileSystemUtils::getMimetype($extension)); }
/** * * Copies this directory and all its content to a new path. * * @param \Mbcraft\Piol\Dir|string $path the path where to copy this folder and all its content. * @param string $new_name An aoptional new name for the copied folder. * * @api */ public function copy($path, $new_name = null) { $target_dir = Dir::asDir($path); if ($new_name == null) { $new_name = $this->getName(); } else { FileSystemUtils::checkValidFilename($new_name); } $copy_dir = $target_dir->newSubdir($new_name); $results = $this->listElements(Dir::MODE_FILES_AND_FOLDERS); $all_elements = array_merge($results[0], $results[1]); foreach ($all_elements as $elem) { $elem->copy($copy_dir); } }
/** * Processes an array (or single) of assets. * * @param array $assets Array of asset file names, or a single asset file name * @param string $optionsKey String representation of the options; used to create aggregated file name * @param string $extension File extension, 'js' or 'css' * @param callback $compressCallback Callback to execute to compress the contents of the asset. If null, the * contents won't be compressed. * * @return StorageFacilityFile Aggregated file stored in the aggregate storage facility (with url populated) */ protected function processAsset($asset, $optionsKey, $extension) { $ts = $this->AssetService->getOriginTimestamp($asset); $prefix = ''; $p = basename($asset); $prefix = rtrim($p, '.' . $extension) . '.'; $cacheFileId = '/' . $this->cacheBasePath . '/' . $prefix . md5(serialize(array($asset, $optionsKey, $ts))) . ".v" . $this->DateFactory->newStorageDate($ts)->format(AssetAggregator::DATE_FORMAT) . "." . $extension; if (!$this->AssetService->fileExists($cacheFileId)) { $deployedfile = $this->AssetService->getOriginPath($asset); $contents = @file_get_contents($deployedfile); if ($contents === false) { throw new Exception("Reading contents of file '{$deployedfile}' for asset '{$asset}' failed (empty file contents will cause failure)."); } // strip non-ASCII characters $contents = preg_replace('/[^(\\x20-\\x7F)\\x0A]*/', '', $contents); $tmpFile = $this->vendorCacheDirectory . '/assetCache' . $cacheFileId; if (!is_writable($this->vendorCacheDirectory)) { throw new Exception('Vendor cache directory is not writable: ' . $this->vendorCacheDirectory); } FileSystemUtils::safeFilePutContents($tmpFile, $contents); $this->AssetService->putFile($cacheFileId, $tmpFile, $ts); } $aggregateFile = $this->AssetService->resolveFile($cacheFileId); return $aggregateFile->getURL(); }
public function testAllInstalledProjectsInBaseDir() { $projects = FileSystemUtils::allInstalledProjectsInBaseDir(__DIR__ . '/fixtures/global'); $this->assertEquals('org/example', implode(',', $projects)); }
public function maxUploadSize() { return FileSystemUtils::humanFileSize(FileSystemUtils::iniValueInBytes(ini_get('upload_max_filesize'))); }
public function processQuickAdd(NodeRef $nodeRef, Node &$newNode) { try { $workdir = $this->vendorCacheDirectory; $fileURL = (string) $this->Request->getParameter('FileURL'); if (empty($fileURL)) { $fileURL = (string) $this->Request->getParameter('Url'); } $dataURL = (string) $this->Request->getParameter('DataURL'); if ($fileURL != null && trim($fileURL) !== '') { //process file from URL // $data = $this->HttpRequest->fetchURL($fileURL); // // if($data === FALSE) // throw new Exception("Could not get contents of image file at the specified URL. Please try uploading the image from a local file."); // // $basename = basename($fileURL); // // if(($qpos = strpos($basename,'?')) !== false) // $basename = substr($basename,0,$qpos); // // $uploadTempPath = rtrim($workdir, '/').'/uploads/'.$basename; // // FileSystemUtils::safeFilePutContents($uploadTempPath, $data); $this->getMediaService()->storeMediaFromURL($fileURL, $newNode); } else { if ($dataURL != null && trim($dataURL) !== '') { if (preg_match("/^data:(.*?);base64,(.*)\$/", $dataURL, $m)) { $mimeType = $m[1]; $data = $m[2]; if (empty($data)) { throw new Exception("Could not parse data from base64 encoded DataURL"); } $mimeParts = explode('/', $mimeType); $fname = mt_rand() . '.' . $mimeParts[1]; $newPath = rtrim($workdir, '/') . '/uploads/' . $fname; FileSystemUtils::safeFilePutContents($newPath, base64_decode($data)); $this->getMediaService()->storeMedia($newPath, $newNode); } else { throw new Exception("Invalid base64 encoded DataURL format"); } } else { foreach ($this->Request->getUploadedFiles() as $name => $upload) { if (!$upload->isEmpty()) { $dotPos = strrpos($upload->getName(), '.'); if ($dotPos === FALSE) { throw new Exception("Uploaded file name missing extension!"); } //$uploadBaseName = SlugUtils::createSlug($newNode->Title); //$uploadExtension = strtolower(substr($upload->getName(), $dotPos+1)); //$uploadName = $uploadBaseName.'.'.$uploadExtension; $uploadTempPath = $upload->getTemporaryName(); $newPath = rtrim($workdir, '/') . '/uploads/' . preg_replace('/[\\x80-\\xFF]/', '', $upload->getName()); //MOVE OR COPY UPLOADED FILE TO WORKING PATH if (!$upload->transferTo($newPath)) { throw new Exception('Unable to transfer upload to: ' . $newPath); } $this->getMediaService()->storeMedia($newPath, $newNode); break; //only process 1 uploaded file (for now) } else { throw new Exception("Unsuccessful upload: " . $upload->getHumanError()); } } } } } catch (StorageFacilityException $sfe) { throw new Exception("An error occurred storing the file(s): " . $sfe->getMessage()); } catch (ThumbnailsException $te) { throw new Exception("An error occurred generating the thumbnail(s): " . $te->getMessage()); } catch (Exception $e) { throw new Exception("An error occurred while processing the file(s): " . $e->getMessage()); } }
/** * Checks and prepares the image for use. * * @param $data base64 encoded data string * @return string file path on disk * @throws ImageFilterException */ protected function prepareImageData($data) { if (is_array($data)) { $uploadedFiles = $this->Request->getUploadedFiles(); $sourceFileName = $data['filename']; $filename = null; foreach ($uploadedFiles as $uploadFile) { if ($uploadFile->getName() == $sourceFileName) { $filename = $uploadFile->getTemporaryName(); break; } } if (empty($filename)) { throw new ImageFilterException("File '{$filename}' was not uploaded"); } $file = file_get_contents($filename); unlink($filename); } else { if (preg_match('/^data:/', $data)) { $data = substr($data, strpos($data, ",") + 1); if (!($file = base64_decode($data, true))) { throw new ImageFilterException('Data string is not a valid base64 encoded file.'); } } else { throw new ImageFilterException('No file was provided.'); } } // create a unique output file name $sourceFile = FileSystemUtils::secureTmpname($this->workDir, 'base64fetch'); file_put_contents($sourceFile, $file); return $sourceFile; }
protected function logLine($message) { FileSystemUtils::safeFilePutContents($this->logFile, '[' . date('Y-m-d H:i:s') . '] ' . $message . "\n", FILE_APPEND); }
<?php /** * This file contains all the requires that loads all the library classes. You can require * this class and forget all other require and dependency stuff. * */ namespace Mbcraft\Piol; require_once "PiolObject.php"; require_once "FileSystemUtils.php"; FileSystemUtils::checkPiolRootPath(); require_once "IOException.php"; require_once "__FileSystemElement.php"; require_once "Utils/IniPropertiesUtils.php"; require_once "Utils/JavaXmlPropertiesUtils.php"; require_once "FileReader.php"; require_once "FileWriter.php"; require_once "File.php"; require_once "Dir.php"; require_once "Storage.php"; require_once "StorageDrivers/DataStorage.php"; require_once "StorageDrivers/PropertiesStorage.php"; require_once "StorageDrivers/XMLStorage.php"; require_once "Upload.php"; require_once "UploadUtils.php"; require_once "Cache/ICache.php"; require_once "Cache/FlatDirCache.php"; if (defined("ZipArchive")) { require_once "ZipUtils.php"; }
protected function executeExecImagick() { // Step 1. Generate the watermark $op = ''; // store original values $fileType = $this->outputType; $targetFile = $this->targetFile; $this->outputAlpha = true; if ($this->type == 'text') { $this->outputType = 'png'; $this->targetFile = FileSystemUtils::secureTmpname($this->workDir, 'watermark', '.' . $this->outputType); $op .= " -background transparent"; $op .= " -fill '{$this->fontColor}'"; if (!empty($this->fontFamily)) { $op .= " -font '{$this->fontFamily}'"; } if (!empty($this->fontStyle)) { $op .= " -style '{$this->fontStyle}'"; } if (!empty($this->fontWeight)) { $op .= " -weight '{$this->fontWeight}'"; } $op .= " -size {$this->width}x{$this->height}"; if (!empty($this->fontSize)) { $op .= " -pointsize {$this->fontSize}"; } $op .= " caption:\"" . preg_replace('/"/', '\\"', $this->text) . "\""; $watermark = ImagickExecFilterHelper::executeFilter($this, $op, true); } else { if ($this->type == 'image') { $watermark = $this->image; } } // Step 2. Apply the watermark // restore original values $this->outputType = $fileType; $this->targetFile = $targetFile; /** This only works with IM > 6.5.3-4 **/ /*$op = "\"{$watermark}\""; $op .= " -compose dissolve"; $op .= " -define compose:args={$this->opacity}"; $op .= " -gravity {$this->anchor}"; $op .= " -geometry {$this->offsetX}{$this->offsetY}"; $op .= " -composite"; $image = ImagickExecFilterHelper::executeFilter($this, $op);*/ $inFile = escapeshellarg($this->sourceFile); $outFile = escapeshellarg($this->targetFile); $op = " -dissolve {$this->opacity}"; $op .= " -gravity {$this->anchor}"; $op .= " -geometry {$this->offsetX}{$this->offsetY}"; $op .= " \"{$watermark}\""; $op .= " {$inFile}"; if ($this->outputAlpha != null) { if ($this->outputAlpha == true) { $op .= " -alpha On"; } else { $op .= " -alpha Off"; } } $op .= " -quality {$this->outputQuality}"; $cmdParams = "{$op} {$outFile}"; $cmd = "{$this->imageCompositeExecPath} {$cmdParams} 2>&1"; $retval = 1; $output = array(); exec($cmd, $output, $retval); if ($retval > 0) { throw new ImageFilterException("Image filter process failed", $output); } @unlink($watermark); return $this->targetFile; }
public function quickAdd() { try { $this->checkNonce(); try { $mediaElementStr = (string) $this->Request->getRequiredParameter('ParentElement'); $mediaElement = $this->ElementService->getBySlug($mediaElementStr); $workdir = $this->vendorCacheDirectory; $fileURL = (string) $this->Request->getParameter('FileURL'); if ($fileURL != null && trim($fileURL) !== '') { //process file from URL $data = $this->HttpRequest->fetchURL($fileURL); if ($data === FALSE) { throw new Exception("Could not get contents of file at the specified URL. Please try uploading the file from a local file."); } $basename = basename($fileURL); if (($qpos = strpos($basename, '?')) !== false) { $basename = substr($basename, 0, $qpos); } $uploadTempPath = rtrim($workdir, '/') . '/uploads/' . $basename; FileSystemUtils::safeFilePutContents($uploadTempPath, $data); $node = $this->FileService->createFileNode($mediaElement, null, $uploadTempPath); } else { foreach ($this->Request->getUploadedFiles() as $name => $upload) { if (!$upload->isEmpty()) { $dotPos = strrpos($upload->getName(), '.'); if ($dotPos === FALSE) { throw new Exception("Uploaded file name missing extension!"); } //$uploadBaseName = SlugUtils::createSlug($newNode->Title); //$uploadExtension = strtolower(substr($upload->getName(), $dotPos+1)); //$uploadName = $uploadBaseName.'.'.$uploadExtension; $uploadTempPath = $upload->getTemporaryName(); $newPath = rtrim($workdir, '/') . '/uploads/' . $upload->getName(); //MOVE OR COPY UPLOADED FILE TO WORKING PATH if (!$upload->transferTo($newPath)) { throw new Exception('Unable to transfer upload to: ' . $newPath); } $node = $this->FileService->createFileNode($mediaElement, null, $newPath); break; //only process 1 uploaded file (for now) } else { throw new Exception("Unsuccessful upload: " . $upload->getHumanError()); } } } } catch (StorageFacilityException $sfe) { throw new Exception("An error occurred storing the media file(s): " . $sfe->getMessage()); } catch (ThumbnailsException $te) { throw new Exception("An error occurred generating the thumbnail(s): " . $te->getMessage()); } catch (HttpRequestServerException $hrse) { throw new Exception("An error occurred while fetching the media file(s): " . $hrse->getCode()); } catch (Exception $e) { throw new Exception("An error occurred while processing the media file(s): " . $e->getMessage()); } // create node $this->getErrors()->throwOnError(); $node = $this->RegulatedNodeService->getByNodeRef($node->getNodeRef(), new NodePartials()); $this->bindToActionDatasource(array($node)); return new View($this->successView()); } catch (ValidationException $e) { $this->bindToActionDatasource(array()); throw $e; } catch (Exception $e) { $this->bindToActionDatasource(array()); $this->errors->addGlobalError($e->getCode(), $e->getMessage())->throwOnError(); } }