function generatePDF() { // tempfolder $tmpBaseFolder = TEMP_FOLDER . '/shopsystem'; $tmpFolder = project() ? "{$tmpBaseFolder}/" . project() : "{$tmpBaseFolder}/site"; if (is_dir($tmpFolder)) { Filesystem::removeFolder($tmpFolder); } if (!file_exists($tmpFolder)) { Filesystem::makeFolder($tmpFolder); } $baseFolderName = basename($tmpFolder); //Get site Requirements::clear(); $link = Director::absoluteURL($this->pdfLink() . "/?view=1"); $response = Director::test($link); $content = $response->getBody(); $content = utf8_decode($content); $contentfile = "{$tmpFolder}/" . $this->PublicURL . ".html"; if (!file_exists($contentfile)) { // Write to file if ($fh = fopen($contentfile, 'w')) { fwrite($fh, $content); fclose($fh); } } return $contentfile; }
public function processThumb($imgsrc, $_id, $isUrl = true) { $_id = empty($_id) ? $this->_id : $_id; $storage = Yii::app()->params['feed_path']; $temp = Yii::app()->params['temp']; $fileInfo = explode('.', $imgsrc); $fileType = $fileInfo[count($fileInfo) - 1]; $fileName = 'tmp_' . $_id . "." . $fileType; $tmpFile = $temp . DS . $fileName; if ($isUrl) { $res_get_file = FileRemote::getFromUrl($imgsrc, $tmpFile); } else { $fileSystem = new Filesystem(); $res_get_file = $fileSystem->copy($imgsrc, $tmpFile); } if (file_exists($tmpFile)) { $fileDest = StorageHelper::generalStoragePath($_id, $fileType, $storage); /*$fileSystem = new Filesystem(); $copy = $fileSystem->copy($tmpFile,$fileDest);*/ $width = Yii::app()->params['profile_image']['thumb']['width']; $height = Yii::app()->params['profile_image']['thumb']['height']; $resizeObj = new ResizeImage($tmpFile); $rs = $resizeObj->resizeImage($width, $height, 0); $res = $resizeObj->saveImage($fileDest, 100); if ($resizeObj) { $feed = self::model()->findByPk(new MongoId($_id)); $fileDest = str_replace($storage, '', $fileDest); $feed->thumb = $fileDest; $res = $feed->save(); return $res; } } else { throw new Exception("create file temp error!", 7); } }
protected function beforeGetContentBody() { $sn = time(); $i = 0; $tmpFile = $temp = Yii::app()->params['temp']; $storage = Yii::app()->params['feed_path']; $cdn = Yii::app()->params['cdn_url']; $contentParttern = $this->config['content_pattern']; foreach ($this->html->find("{$contentParttern} img") as $e) { $imgSrc = $e->src; if (!empty($imgSrc)) { $fileInfo = explode('.', $imgSrc); $fileType = $fileInfo[count($fileInfo) - 1]; $fileName = 'tmp_' . $sn . $i . "." . $fileType; $sfile = $tmpFile . DS . $fileName; $res_get_file = FileRemote::getFromUrl($imgSrc, $sfile); if ($res_get_file && file_exists($sfile)) { $fileDest = StorageHelper::generalStoragePath($sn . $i, $fileType, $storage); $fileSystem = new Filesystem(); $copy = $fileSystem->copy($sfile, $fileDest); if ($copy) { echo $fileDest . "\n"; $fileDestUrl = str_replace($storage, $cdn, $fileDest); $fileDestUrl = str_replace(DS, "/", $fileDestUrl); echo $fileDestUrl . "\n"; $e->src = $fileDestUrl; echo 'replace file content success' . "\n"; } else { echo 'replace file content error' . "\n"; } } $i++; } } }
protected function deleteTmpDir($testCase) { if (!file_exists($dir = sys_get_temp_dir() . '/' . Kernel::VERSION . '/' . $testCase)) { return; } $fs = new Filesystem(); $fs->remove($dir); }
public function render() { if (!empty($this->sPath)) { $oFilesystem = new Filesystem(); $sFileContents = $oFilesystem->getFileContents($this->sPath); return $this->processMarkdown($sFileContents); } return null; }
public function testShouldMoveFilesThatNeedEspecialPermissions() { $filesystem = new Filesystem(); $file = '/app/tmp/file'; $target = '/system/root/'; $return = $filesystem->sysMove($file, $target); $this->assertRegExp('/sudo mv -v/', $return); $this->assertRegExp('/\\/app\\/tmp\\/file/', $return); $this->assertRegExp('/\\/system\\/root\\//', $return); }
public static function processAvatar($model, $source, $type = "artist") { try { $fileSystem = new Filesystem(); $alowSize = Yii::app()->params['imageSize']; $maxSize = max($alowSize); $folderMax = "s0"; foreach ($alowSize as $folder => $size) { // Create folder by ID $fileSystem->mkdirs($model->getAvatarPath($model->id, $folder, true)); @chmod($model->getAvatarPath($model->id, $folder, true), 0755); // Get link file by ID $savePath[$folder] = $model->getAvatarPath($model->id, $folder); if ($size == $maxSize) { $folderMax = $folder; } } // Delete file if exists if (file_exists($savePath[$folder])) { $fileSystem->remove($savePath); } if (file_exists($source)) { list($width, $height) = getimagesize($source); $imgCrop = new ImageCrop($source, 0, 0, $width, $height); // aspect ratio for image size $aspectRatioW = $aspectRatioH = 1; if ($type == "video") { $videoAspectRatio = Yii::app()->params['videoResolutionRate']; list($aspectRatioW, $aspectRatioH) = explode(":", $videoAspectRatio); } $res = array(); foreach ($savePath as $k => $v) { $desWidth = $alowSize[$k]; $desHeight = round($alowSize[$k] * intval($aspectRatioH) / intval($aspectRatioW)); if (file_exists($v) && is_file($v)) { @unlink($v); } if ($width > 4000) { self::ImageCropPro($v, $source, $desWidth, $desHeight, 70); } else { if ($k == $folderMax) { $imgCrop->resizeRatio($v, $desWidth, $desHeight, 70); } else { $imgCrop->resizeCrop($v, $desWidth, $desHeight, 70); } } } if ($type != "video") { $fileSystem->remove($source); } } } catch (Exception $e) { $error = $e->getMessage(); } }
public function testIfRetrievingTheFilesWorks() { $config = \Mockery::mock('eXistenZNL\\PermCheck\\Config\\Config'); $filesystem = new Filesystem($config, dirname(__FILE__)); $files = array(__FILE__); $result = array(); foreach ($filesystem->getFiles() as $file) { $result[] = $file->getPathname(); } $this->assertEquals($files, $result); }
public function manageConfigs() { $fileSystem = new Filesystem(); $files = $fileSystem->files(__DIR__ . '/config'); if (!empty($files)) { foreach ($files as $file) { $name = explode('/', $file); $this->mergeConfigFrom($file, str_replace('.php', '', $name[count($name) - 1])); } } }
private function moveDefaultTemplate() { $this->log('Moving default template...'); $fileDir = $this->container->getParameter('claroline.param.files_directory'); $defaultTemplate = $this->container->getParameter('claroline.param.default_template'); $newTemplateDir = $fileDir . '/templates'; $newTemplate = $newTemplateDir . '/default.zip'; $fs = new Filesystem(); $fs->mkdir($newTemplateDir); $fs->copy($defaultTemplate, $newTemplate); }
public static function generalStoragePath($objId, $fileType = 'jpg', $storage, $isUrl = false) { $year = date('Y'); $month = date('m'); $day = date('d'); $sep = $isUrl ? '/' : DS; $exPath = $year . $sep . $month . $sep . $day; $filePath = $storage . $sep . $exPath; $fileSystem = new Filesystem(); $res = $fileSystem->mkdirs($filePath, '0755'); return $filePath . $sep . $objId . '.' . $fileType; }
/** * Process a php target file to append PHP syntax-sensitive content * from multiple template sources. * * @param string $file, a php file to modify * @param array $templates list of key (property name), value (template file) * @param string $data used to replace placeholders inside all template files * @param Boolean $front, set location to the front of the array */ protected function processFile($file, $templates, $data, $front = false) { $content = $this->files->get($file); $phpParser = new GenericPhpParser($content, $data, $this->parser); foreach ($templates as $property => $template) { $phpParser->parse($property, $template, $front); } $content = $phpParser->prettyPrint(); if (!is_null($content)) { $this->files->put($file, $content); } }
public function testIfRetrievingTheFilesWorks() { /** @var Config|MockInterface $config */ $config = \Mockery::mock(new Config()); $filesystem = new Filesystem($config, __DIR__); $files = array(__FILE__); $result = array(); foreach ($filesystem->getFiles() as $file) { $result[] = $file->getPathname(); } $this->assertEquals($files, $result); }
public function __construct($sConfigFile = 'config.json') { $oFilesystem = new Filesystem(); $sContents = $oFilesystem->getFileContents($sConfigFile); if (!empty($sContents)) { $this->_aConfig = json_decode($sContents, true); if (empty($this->_aConfig)) { throw new BadConfigException(sprintf($this->sError, $sConfigFile, $this->getJSONError(json_last_error()))); } } else { throw new BadConfigException("Config file is empty: " . $sConfigFile); } }
public function test_symlink_removal() { $test_dir = 'tests/test-data/symlinks'; $test_link = $test_dir . '/points_nowhere'; if (is_dir($test_dir)) { $this->rmdir_recursive($test_dir); } mkdir($test_dir); symlink("does_not_exist", $test_link); $fs = new Filesystem(); $fs->remove($test_dir); $this->assertFalse(is_link($test_link) || is_file($test_link)); }
public function create(array $data) { try { $this->validator->with($data)->passesOrFail(ValidatorInterface::RULE_CREATE); $projectFile = $this->repository->skipPresenter()->create($data); $this->storage->put($projectFile->getFileName(), $this->filesystem->get($data['file'])); return ['success' => true]; } catch (ValidatorException $e) { return ['error' => true, 'message' => $e->getMessageBag(), "messageDev" => 'ValidatorException']; } catch (\Exception $e) { return ["error" => true, "message" => 'Falha ao gravar registro.', "messageDev" => $e->getMessage()]; } }
/** * Replaces the `~` symbol with the user home path. * * @param string $path * @return string The path with the `~` replaced with the user home path if any. */ public static function homeify($path, Filesystem $filesystem = null) { if (!is_string($path)) { throw new \InvalidArgumentException('Paht must be a string'); } if (empty($filesystem)) { $filesystem = new Filesystem(); } $userHome = $filesystem->getUserHome(); if (!(empty($userHome) && false !== strpos($path, '~'))) { $path = str_replace('~', $userHome, $path); } return $path; }
/** * Completes the job by zipping up the generated export and creating an * export record for it. */ protected function complete() { $siteTitle = SiteConfig::current_site_config()->Title; $filename = preg_replace('/[^a-zA-Z0-9-.+]/', '-', sprintf('%s-%s.zip', $siteTitle, date('c'))); $dir = Folder::findOrMake(SiteExportExtension::EXPORTS_DIR); $dirname = ASSETS_PATH . '/' . SiteExportExtension::EXPORTS_DIR; $pathname = "{$dirname}/{$filename}"; SiteExportUtils::zip_directory($this->tempDir, "{$dirname}/{$filename}"); Filesystem::removeFolder($this->tempDir); $file = new File(); $file->ParentID = $dir->ID; $file->Title = $siteTitle . ' ' . date('c'); $file->Filename = $dir->Filename . $filename; $file->write(); $export = new SiteExport(); $export->ParentClass = $this->rootClass; $export->ParentID = $this->rootId; $export->Theme = $this->theme; $export->BaseUrlType = ucfirst($this->baseUrlType); $export->BaseUrl = $this->baseUrl; $export->ArchiveID = $file->ID; $export->write(); if ($this->email) { $email = new Email(); $email->setTo($this->email); $email->setTemplate('SiteExportCompleteEmail'); $email->setSubject(sprintf('Site Export For "%s" Complete', $siteTitle)); $email->populateTemplate(array('SiteTitle' => $siteTitle, 'Link' => $file->getAbsoluteURL())); $email->send(); } }
public function save() { if (!$this->getMailKey()) { $this->setMailKey(Filesystem::readRandomCharacters(20)); } return parent::save(); }
public static function get() { $rmFile = preg_replace("/\\/\\*([^x00]*)\\*?\\/?\\*\\//U", "", Filesystem::getFileContent(Config::ROADMAP)); $roadMap = JSON::decode($rmFile, true); $tmpl = self::$_attr; $cnt = 0; $good = is_array($roadMap); //print_r( $roadMap ); die; for ($i = 0; $good && is_array($roadMap) && $i < count($roadMap); $i++) { $el = $roadMap[$i]; foreach ($el as $k => $v) { if (($pos = array_search($k, $tmpl)) !== FALSE) { $tmpl[$pos] = "asnfcjrwpht984fh9prewgf84fds"; $cnt++; } } $good = $cnt == count(self::$_attr); } if ($good) { return $roadMap; } else { self::raiseException(ERR_ROADMAP); return NULL; } }
private static function loadSkinSpecification($path) { $config_path = $path . DIRECTORY_SEPARATOR . 'skin.json'; $config = array(); if (Filesystem::pathExists($config_path)) { $config = Filesystem::readFile($config_path); try { $config = phutil_json_decode($config); } catch (PhutilJSONParserException $ex) { throw new PhutilProxyException(pht("Skin configuration file '%s' is not a valid JSON file.", $config_path), $ex); } $type = idx($config, 'type', self::TYPE_BASIC); } else { $type = self::TYPE_BASIC; } $spec = new PhameSkinSpecification(); $spec->setRootDirectory($path); $spec->setConfig($config); switch ($type) { case self::TYPE_BASIC: $spec->setSkinClass('PhameBasicTemplateBlogSkin'); break; case self::TYPE_ADVANCED: $spec->setSkinClass($config['class']); $spec->addPhutilLibrary($path . DIRECTORY_SEPARATOR . 'src'); break; default: throw new Exception(pht('Unknown skin type!')); } $spec->setType($type); return $spec; }
public function setUp() { parent::setUp(); $this->logInWithPermission('ADMIN'); Versioned::reading_stage('Stage'); // Set backend root to /AssetFieldTest AssetStoreTest_SpyStore::activate('AssetFieldTest'); $create = function ($path) { Filesystem::makeFolder(dirname($path)); $fh = fopen($path, "w+"); fwrite($fh, str_repeat('x', 1000000)); fclose($fh); }; // Write all DBFile references foreach (AssetFieldTest_Object::get() as $object) { $path = AssetStoreTest_SpyStore::getLocalPath($object->File); $create($path); } // Create a test files for each of the fixture references $files = File::get()->exclude('ClassName', 'Folder'); foreach ($files as $file) { $path = AssetStoreTest_SpyStore::getLocalPath($file); $create($path); } }
public function save() { if (!$this->mailKey) { $this->mailKey = Filesystem::readRandomCharacters(20); } return parent::save(); }
protected function getProxyCommand() { $uri = new PhutilURI($this->proxyURI); $username = AlmanacKeys::getClusterSSHUser(); if ($username === null) { throw new Exception(pht('Unable to determine the username to connect with when trying ' . 'to proxy an SSH request within the Phabricator cluster.')); } $port = $uri->getPort(); $host = $uri->getDomain(); $key_path = AlmanacKeys::getKeyPath('device.key'); if (!Filesystem::pathExists($key_path)) { throw new Exception(pht('Unable to proxy this SSH request within the cluster: this device ' . 'is not registered and has a missing device key (expected to ' . 'find key at "%s").', $key_path)); } $options = array(); $options[] = '-o'; $options[] = 'StrictHostKeyChecking=no'; $options[] = '-o'; $options[] = 'UserKnownHostsFile=/dev/null'; // This is suppressing "added <address> to the list of known hosts" // messages, which are confusing and irrelevant when they arise from // proxied requests. It might also be suppressing lots of useful errors, // of course. Ideally, we would enforce host keys eventually. $options[] = '-o'; $options[] = 'LogLevel=quiet'; // NOTE: We prefix the command with "@username", which the far end of the // connection will parse in order to act as the specified user. This // behavior is only available to cluster requests signed by a trusted // device key. return csprintf('ssh %Ls -l %s -i %s -p %s %s -- %s %Ls', $options, $username, $key_path, $port, $host, '@' . $this->getUser()->getUsername(), $this->getOriginalArguments()); }
function phabricator_read_config_file($original_config) { $root = dirname(dirname(__FILE__)); // Accept either "myconfig" (preferred) or "myconfig.conf.php". $config = preg_replace('/\\.conf\\.php$/', '', $original_config); $full_config_path = $root . '/conf/' . $config . '.conf.php'; // Make sure config file errors are reported. $old_error_level = error_reporting(E_ALL | E_STRICT); $old_display_errors = ini_get('display_errors'); ini_set('display_errors', 1); ob_start(); $conf = (include $full_config_path); $errors = ob_get_clean(); error_reporting($old_error_level); ini_set('display_errors', $old_display_errors); if ($conf === false) { if (!Filesystem::pathExists($full_config_path)) { $files = id(new FileFinder($root . '/conf/'))->withType('f')->withSuffix('conf.php')->withFollowSymlinks(true)->find(); foreach ($files as $key => $file) { $file = trim($file, './'); $files[$key] = preg_replace('/\\.conf\\.php$/', '', $file); } $files = " " . implode("\n ", $files); throw new Exception("CONFIGURATION ERROR\n" . "Config file '{$original_config}' does not exist. Valid config files " . "are:\n\n" . $files); } throw new Exception("Failed to read config file '{$config}': {$errors}"); } return $conf; }
/** * writeTo * * @param string $path * @return void */ public function writeTo($path) { Filesystem::makeFolder(dirname($path)); if (is_dir(dirname($path))) { self::writeImage($path); } }
public function run() { $conduit = $this->getConduit(); $results = array(); foreach ($this->paths as $path) { $name = basename($path); $this->writeStatusMessage("Uploading '{$name}'...\n"); try { $data = Filesystem::readFile($path); } catch (FilesystemException $ex) { $this->writeStatusMessage("Unable to upload file: " . $ex->getMessage() . "\n"); $results[$path] = null; continue; } $phid = $conduit->callMethodSynchronous('file.upload', array('data_base64' => base64_encode($data), 'name' => $name)); $info = $conduit->callMethodSynchronous('file.info', array('phid' => $phid)); $results[$path] = $info; if (!$this->getJSON()) { echo " {$name}: " . $info['uri'] . "\n\n"; } } if ($this->getJSON()) { echo json_encode($results) . "\n"; } else { $this->writeStatusMessage("Done.\n"); } return 0; }
public function save() { if (!$this->getAccountSecret()) { $this->setAccountSecret(Filesystem::readRandomCharacters(32)); } return parent::save(); }
function buildThemes() { global $Site; $themes = array(); $themesPaths = Filesystem::listDirectories(PATH_THEMES); foreach ($themesPaths as $themePath) { // Check if the theme is translated. $languageFilename = $themePath . DS . 'languages' . DS . $Site->locale() . '.json'; if (!Sanitize::pathFile($languageFilename)) { $languageFilename = $themePath . DS . 'languages' . DS . 'en_US.json'; } if (Sanitize::pathFile($languageFilename)) { $database = file_get_contents($languageFilename); $database = json_decode($database, true); $database = $database['theme-data']; $database['dirname'] = basename($themePath); // --- Metadata --- $filenameMetadata = $themePath . DS . 'metadata.json'; if (Sanitize::pathFile($filenameMetadata)) { $metadataString = file_get_contents($filenameMetadata); $metadata = json_decode($metadataString, true); $database = $database + $metadata; // Theme data array_push($themes, $database); } } } return $themes; }
private function markupText($markup_file) { $contents = Filesystem::readFile($markup_file); $file = basename($markup_file); $parts = explode("\n~~~~~~~~~~\n", $contents); $this->assertEqual(3, count($parts), $markup_file); list($input_remarkup, $expected_output, $expected_text) = $parts; $engine = $this->buildNewTestEngine(); switch ($file) { case 'raw-escape.txt': // NOTE: Here, we want to test PhutilRemarkupRuleEscapeRemarkup and // PhutilRemarkupBlockStorage, which are triggered by "\1". In the // test, "~" is used as a placeholder for "\1" since it's hard to type // "\1". $input_remarkup = str_replace("~", "", $input_remarkup); $expected_output = str_replace("~", "", $expected_output); $expected_text = str_replace("~", "", $expected_text); break; case 'toc.txt': $engine->setConfig('header.generate-toc', true); break; } $actual_output = (string) $engine->markupText($input_remarkup); switch ($file) { case 'toc.txt': $table_of_contents = PhutilRemarkupEngineRemarkupHeaderBlockRule::renderTableOfContents($engine); $actual_output = $table_of_contents . "\n\n" . $actual_output; break; } $this->assertEqual($expected_output, $actual_output, "Failed to markup HTML in file '{$file}'."); $engine->setMode(PhutilRemarkupEngine::MODE_TEXT); $actual_output = (string) $engine->markupText($input_remarkup); $this->assertEqual($expected_text, $actual_output, "Failed to markup text in file '{$file}'."); }