/** * @param CM_Frontend_Render $render * @throws CM_Exception */ public function __construct(CM_Frontend_Render $render) { parent::__construct($render); $this->addVariables(); $file = new CM_File(DIR_PUBLIC . 'static/css/library/icon.less'); if ($file->exists()) { $this->add($file->read()); } foreach (array_reverse($render->getSite()->getModules()) as $moduleName) { foreach (array_reverse($render->getSite()->getThemes()) as $theme) { foreach (CM_Util::rglob('*.less', $render->getThemeDir(true, $theme, $moduleName) . 'css/') as $path) { $file = new CM_File($path); $this->add($file->read()); } } } $viewClasses = CM_View_Abstract::getClassChildren(true); foreach ($viewClasses as $viewClassName) { $validModule = in_array(CM_Util::getNamespace($viewClassName), $render->getSite()->getModules()); $validViewClass = $this->_isValidViewClass($viewClassName); if ($validModule && $validViewClass) { $asset = new CM_Asset_Css_View($this->_render, $viewClassName); $this->add($asset->_getContent()); } } }
public function iconRefresh() { /** @var CM_File[] $svgFileList */ $svgFileList = array(); foreach (CM_Bootloader::getInstance()->getModules() as $moduleName) { $iconPath = CM_Util::getModulePath($moduleName) . 'layout/default/resource/img/icon/'; foreach (glob($iconPath . '*.svg') as $svgPath) { $svgFile = new CM_File($svgPath); $svgFileList[strtolower($svgFile->getFileName())] = $svgFile; } } if (0 === count($svgFileList)) { throw new CM_Exception_Invalid('Cannot process `0` icons'); } $this->_getStreamOutput()->writeln('Processing ' . count($svgFileList) . ' unique icons...'); $dirWork = CM_File::createTmpDir(); $dirBuild = $dirWork->joinPath('/build'); foreach ($svgFileList as $fontFile) { $fontFile->copyToFile($dirWork->joinPath($fontFile->getFileName())); } CM_Util::exec('fontcustom', array('compile', $dirWork->getPathOnLocalFilesystem(), '--no-hash', '--autowidth', '--font-name=icon-webfont', '--output=' . $dirBuild->getPathOnLocalFilesystem())); $cssFile = $dirBuild->joinPath('/icon-webfont.css'); $less = preg_replace('/url\\("(?:.*?\\/)(.+?)(\\??#.+?)?"\\)/', 'url(urlFont("\\1") + "\\2")', $cssFile->read()); CM_File::create(DIR_PUBLIC . 'static/css/library/icon.less', $less); foreach (glob($dirBuild->joinPath('/icon-webfont.*')->getPathOnLocalFilesystem()) as $fontPath) { $fontFile = new CM_File($fontPath); $fontFile->rename(DIR_PUBLIC . 'static/font/' . $fontFile->getFileName()); } $dirWork->delete(true); $this->_getStreamOutput()->writeln('Created web-font and stylesheet.'); }
/** * @param CM_OutputStream_Interface $output * @param CM_File_Filesystem $backupFilesystem */ public function verifyExport(CM_OutputStream_Interface $output, CM_File_Filesystem $backupFilesystem) { $asserter = new S3Export_Asserter(); $sourceFilesystem = $this->_getFilesystemOriginal(); $filePaths = $this->_getRandomFiles($backupFilesystem, 100, 100000); foreach ($filePaths as $path) { $backupFile = new CM_File($path, $backupFilesystem); $sourceFile = new CM_File($path, $sourceFilesystem); $asserter->assertThat($sourceFile->exists(), function () use($output) { $output->write("."); }, function () use($output, $backupFile) { $output->writeln('E'); $output->writeln("Integrity mismatch: Corresponding backup file does not exist for {$backupFile->getPath()}"); }); if ($sourceFile->exists()) { $asserter->assertThat($sourceFile->getHash() === $backupFile->getHash(), function () use($output) { $output->write('.'); }, function () use($output, $backupFile) { $output->writeln('E'); $output->writeln("Integrity mismatch: Different hashes for {$backupFile->getPath()}"); }); } } $output->writeln(''); $output->writeln(join(', ', ["Assertions run: {$asserter->getAssertionCount()}", "succeeded: {$asserter->getAssertionSuccessCount()}", "failed: {$asserter->getAssertionFailCount()}"])); }
/** * @param int $streamChannelId * @param CM_File $archiveSource */ public function importVideoArchive($streamChannelId, CM_File $archiveSource) { $streamChannelArchive = new CM_Model_StreamChannelArchive_Video($streamChannelId); $archiveDestination = $streamChannelArchive->getVideo(); $archiveDestination->ensureParentDirectory(); $archiveSource->copyToFile($archiveDestination); }
public function testGetSetRuntime() { $defaultTimeZoneBackup = date_default_timezone_get(); $interval = '1 day'; $timezone = new DateTimeZone('Europe/Berlin'); $event1 = new CM_Clockwork_Event('foo', $interval); $event2 = new CM_Clockwork_Event('bar', $interval); $date1 = new DateTime('2014-10-31 08:00:00', $timezone); $date2 = new DateTime('2014-10-31 08:02:03', $timezone); $context = 'persistence-test'; $storage = new CM_Clockwork_Storage_FileSystem($context); $serviceManager = CM_Service_Manager::getInstance(); $storage->setServiceManager($serviceManager); $filepath = 'clockwork/' . md5($context) . '.json'; $file = new CM_File($filepath, $serviceManager->getFilesystems()->getData()); $this->assertFalse($file->exists()); $this->assertFalse($file->getParentDirectory()->exists()); $storage->setRuntime($event1, $date1); $this->assertTrue($file->getParentDirectory()->exists()); $this->assertTrue($file->exists()); $storage->setRuntime($event2, $date2); date_default_timezone_set('Antarctica/Vostok'); $storage = new CM_Clockwork_Storage_FileSystem($context); $storage->setServiceManager($serviceManager); $this->assertEquals($date1, $storage->getLastRuntime($event1)); $this->assertEquals($date2, $storage->getLastRuntime($event2)); date_default_timezone_set($defaultTimeZoneBackup); }
protected function _process() { $return = array(); try { $fileInfo = reset($_FILES); if (empty($fileInfo)) { throw new CM_Exception('Invalid file upload'); } if (isset($fileInfo['error']) && $fileInfo['error'] !== UPLOAD_ERR_OK) { throw new CM_Exception('File upload error: ' . self::$_uploadErrors[$fileInfo['error']]); } $fileTmp = new CM_File($fileInfo['tmp_name']); if ($fileTmp->getSize() > self::MAX_FILE_SIZE) { throw new CM_Exception_FormFieldValidation(new CM_I18n_Phrase('File too big')); } $file = CM_File_UserContent_Temp::create($fileInfo['name'], $fileTmp->read()); $fileTmp->delete(); $query = $this->_request->getQuery(); $preview = null; if (isset($query['field'])) { $field = CM_FormField_File::factory($query['field'], ['name' => 'file']); $field->validateFile($file); $preview = $this->getRender()->fetchViewTemplate($field, 'preview', array('file' => $file)); } $return['success'] = array('id' => $file->getUniqid(), 'preview' => $preview); } catch (CM_Exception_FormFieldValidation $ex) { $return['error'] = array('type' => get_class($ex), 'msg' => $ex->getMessagePublic($this->getRender())); } $this->_setContent(json_encode($return, JSON_HEX_TAG)); // JSON decoding in IE-iframe needs JSON_HEX_TAG }
/** * @param int|null $deployVersion */ public function setDeployVersion($deployVersion = null) { $deployVersion = null !== $deployVersion ? (int) $deployVersion : time(); $sourceCode = join(PHP_EOL, array('<?php', 'return function (CM_Config_Node $config) {', ' $config->deployVersion = ' . $deployVersion . ';', '};', '')); $targetPath = DIR_ROOT . 'resources/config/deploy.php'; $configFile = new CM_File($targetPath); $configFile->ensureParentDirectory(); $configFile->write($sourceCode); }
/** * @param CM_Site_Abstract $site * @return string * @throws CM_Exception_Invalid */ private function _getAppClassName(CM_Site_Abstract $site) { foreach ($site->getModules() as $moduleName) { $file = new CM_File(DIR_ROOT . CM_Bootloader::getInstance()->getModulePath($moduleName) . 'library/' . $moduleName . '/App.js'); if ($file->exists()) { return $moduleName . '_App'; } } throw new CM_Exception_Invalid('No App class found'); }
public function addVariables() { foreach (array_reverse($this->_render->getSite()->getModules()) as $moduleName) { foreach (array_reverse($this->_render->getSite()->getThemes()) as $theme) { $file = new CM_File($this->_render->getThemeDir(true, $theme, $moduleName) . 'variables.less'); if ($file->exists()) { $this->add($file->read()); } } } }
public function setUp() { CM_Db_Db::exec('ALTER TABLE cm_model_location_ip AUTO_INCREMENT = 1'); CM_Db_Db::exec('ALTER TABLE cm_model_location_zip AUTO_INCREMENT = 1'); CM_Db_Db::exec('ALTER TABLE cm_model_location_city AUTO_INCREMENT = 1'); CM_Db_Db::exec('ALTER TABLE cm_model_location_state AUTO_INCREMENT = 1'); CM_Db_Db::exec('ALTER TABLE cm_model_location_country AUTO_INCREMENT = 1'); $this->_errorStream = new CM_OutputStream_Null(); $file = new CM_File('/CM_OutputStream_File-' . uniqid(), CM_Service_Manager::getInstance()->getFilesystems()->getTmp()); $file->truncate(); $this->_outputStream = new CM_OutputStream_File($file); }
/** * @param string $path * @param string|null $formatMessage * @param string|null $formatDate * @param int|null $minLevel * @return CM_Log_Handler_Stream */ public function createFileHandler($path, $formatMessage = null, $formatDate = null, $minLevel = null) { $path = (string) $path; $formatMessage = null !== $formatMessage ? (string) $formatMessage : $formatMessage; $formatDate = null !== $formatDate ? (string) $formatDate : $formatDate; $filesystem = $this->getServiceManager()->getFilesystems()->getData(); $file = new CM_File($path, $filesystem); $file->ensureParentDirectory(); $stream = new CM_OutputStream_File($file); $formatter = new CM_Log_Formatter_Text($formatMessage, $formatDate); return $this->_createStreamHandler($stream, $formatter, $minLevel); }
/** * @param CM_File_Filesystem $filesystem */ protected function _fillFilesystemWithRandomFiles(CM_File_Filesystem $filesystem) { $faker = Faker\Factory::create(); for ($i = 0; $i < 20; $i++) { $directory = $faker->lexify('????????' . $i); for ($j = 0; $j < 10; $j++) { $path = $faker->lexify('????????' . $j); $content = $faker->paragraph(10); $file = new CM_File($directory . '/' . $path, $filesystem); $file->ensureParentDirectory(); $file->write($content); } } }
public function __construct(CM_Frontend_Render $render) { parent::__construct($render); $extensions = array('css', 'less'); foreach (array_reverse($render->getSite()->getModules()) as $moduleName) { $libraryPath = DIR_ROOT . CM_Bootloader::getInstance()->getModulePath($moduleName) . 'client-vendor/'; foreach ($extensions as $extension) { foreach (CM_Util::rglob('*.' . $extension, $libraryPath) as $path) { $file = new CM_File($path); $this->add($file->read()); } } } }
public function testImportVideoThumbnail() { $testFile1 = CM_File::create('test1.png', 'foo1', CM_Service_Manager::getInstance()->getFilesystems()->getTmp()); $testFile2 = CM_File::create('test2.png', 'foo2', CM_Service_Manager::getInstance()->getFilesystems()->getTmp()); $cli = new CM_MediaStreams_Cli(); // streamchannel exists /** @var CM_Model_StreamChannel_Media $streamChannel */ $streamChannel = CMTest_TH::createStreamChannel(null, null, 'foobar'); $this->assertCount(0, $streamChannel->getThumbnails()); $cli->importVideoThumbnail('foobar', $testFile1, 1234); $this->assertCount(1, $streamChannel->getThumbnails()); /** @var CM_StreamChannel_Thumbnail $thumbnail */ $thumbnail = $streamChannel->getThumbnails()->getItem(0); $this->assertSame(1234, $thumbnail->getCreateStamp()); $this->assertSame('foo1', $thumbnail->getFile()->read()); // archive exists $archive = CM_Model_StreamChannelArchive_Media::createStatic(['streamChannel' => $streamChannel]); $streamChannel->delete(); $cli->importVideoThumbnail('foobar', $testFile2, 1235); $this->assertCount(2, $streamChannel->getThumbnails()); /** @var CM_StreamChannel_Thumbnail $thumbnail */ $thumbnail = $archive->getThumbnails()->getItem(1); $this->assertSame(1235, $thumbnail->getCreateStamp()); $this->assertSame('foo2', $thumbnail->getFile()->read()); }
function smarty_function_load(array $params, Smarty_Internal_Template $template) { /** @var CM_Frontend_Render $render */ $render = $template->smarty->getTemplateVars('render'); $namespace = isset($params['namespace']) ? $params['namespace'] : null; $parse = isset($params['parse']) ? (bool) $params['parse'] : true; if ($parse) { $tplPath = $render->getLayoutPath($params['file'], $namespace); $params = array_merge($template->getTemplateVars(), $params); return $render->fetchTemplate($tplPath, $params); } else { $tplPath = $render->getLayoutPath($params['file'], $namespace, null, true); $file = new CM_File($tplPath); return $file->read(); } }
/** * @param string $namespace */ private function _dbToFileSql($namespace) { $namespace = (string) $namespace; $tables = CM_Db_Db::exec("SHOW TABLES LIKE ?", array(strtolower($namespace) . '_%'))->fetchAllColumn(); sort($tables); $dump = CM_Db_Db::getDump($tables, true); CM_File::create(CM_Util::getModulePath($namespace) . '/resources/db/structure.sql', $dump); }
public function testFetchDescriptionKeywordsConsiderNamespaceWideLocation() { $dirTmp = CM_Bootloader::getInstance()->getDirTmp(); $render = $this->getMockBuilder('CM_Frontend_Render')->setMethods(array('getTemplatePath', 'getLayoutPath'))->getMock(); $render->expects($this->any())->method('getTemplatePath')->will($this->returnValue(null)); $render->expects($this->exactly(2))->method('getLayoutPath')->will($this->returnCallback(function ($templateName) use($dirTmp) { $templateFile = new CM_File($dirTmp . $templateName); $templateFile->ensureParentDirectory(); $templateFile->write('test-' . $templateName); return $templateFile->getPath(); })); /** @var CM_Frontend_Render $render */ $page = $this->getMockBuilder('CM_Page_Abstract')->getMockForAbstractClass(); /** @var CM_Page_Abstract $page */ $renderAdapter = new CM_RenderAdapter_Page($render, $page); $this->assertSame('test-Page/Abstract/meta-description.tpl', $renderAdapter->fetchDescription()); $this->assertSame('test-Page/Abstract/meta-keywords.tpl', $renderAdapter->fetchKeywords()); }
/** * @throws CM_Exception */ public function mount() { if ($this->isMounted()) { return; } $tmpDir = CM_File::createTmpDir(); $mountpointPath = (string) $tmpDir->getPathOnLocalFilesystem(); CM_Util::exec('sudo mount', [$this->_path, $mountpointPath]); $this->_waitForMountStatus(true); }
/** * @param string $filename * @param string $configJson * @param bool|null $merge */ public function setConfig($filename, $configJson, $merge = null) { $merge = (bool) $merge; $configJson = (object) CM_Util::jsonDecode($configJson); $configFile = new CM_File(DIR_ROOT . 'resources/config/' . $filename . '.php'); $config = new CM_Config_Node(); if ($merge && $configFile->exists()) { $config->extendWithFile($configFile); } $config->extendWithConfig($configJson); $configStr = $config->exportAsString('$config'); $indentation = ' '; $indent = function ($content) use($indentation) { return preg_replace('/(:?^|[\\n])/', '$1' . $indentation, $content); }; $configFile->ensureParentDirectory(); $configFile->write(join(PHP_EOL, ['<?php', '// This is autogenerated config file. You should not change it manually.', '', 'return function (CM_Config_Node $config) {', $indent($configStr), '};', ''])); $this->_getStreamOutput()->writeln('Created `' . $configFile->getPath() . '`'); }
/** * @return array */ private function _getColorStyles() { $site = $this->getParams()->getSite('site'); $style = ''; foreach (array_reverse($site->getModules()) as $moduleName) { $file = new CM_File(CM_Util::getModulePath($moduleName) . 'layout/default/variables.less'); if ($file->exists()) { $style .= $file->read() . PHP_EOL; } } preg_match_all('#@(color\\w+)#', $style, $matches); $colors = array_unique($matches[1]); foreach ($colors as $variableName) { $style .= '.' . $variableName . ' { background-color: @' . $variableName . '; }' . PHP_EOL; } $lessCompiler = new lessc(); $style = $lessCompiler->compile($style); preg_match_all('#.(color\\w+)\\s+\\{([^}]+)\\}#', $style, $matches); return array_combine($matches[1], $matches[2]); }
protected function _process() { $path = $this->getRequest()->getPath(); $content = null; $mimeType = null; if ($pathRaw = $this->getRender()->getLayoutPath('resource/' . $path, null, null, true, false)) { $file = new CM_File($pathRaw); if (in_array($file->getExtension(), $this->_getFiletypesForbidden())) { throw new CM_Exception_Nonexistent('Forbidden filetype', CM_Exception::WARN, ['path' => $path]); } $content = $file->read(); $mimeType = $file->getMimeType(); } elseif ($pathTpl = $this->getRender()->getLayoutPath('resource/' . $path . '.smarty', null, null, true, false)) { $content = $this->getRender()->fetchTemplate($pathTpl); $mimeType = CM_File::getMimeTypeByContent($content); } else { throw new CM_Exception_Nonexistent('Invalid filename', CM_Exception::WARN, ['path' => $path]); } $this->setHeader('Content-Type', $mimeType); $this->_setContent($content); }
public function testValidateFileNoImage() { $image = CM_File::createTmp(); $formField = new CM_FormField_FileImage(); $exception = $this->catchException(function () use($formField, $image) { $formField->validateFile($image); }); $this->assertInstanceOf(CM_Exception_FormFieldValidation::class, $exception); $this->assertSame('FormField Validation failed', $exception->getMessage()); /** @var CM_Exception $exception */ $this->assertSame('Invalid image', $exception->getMessagePublic(new CM_Frontend_Render())); }
/** * @param string $streamChannelMediaId * @param CM_File $archiveSource * @throws CM_Exception_Invalid */ public function importArchive($streamChannelMediaId, CM_File $archiveSource) { $streamChannelMediaId = (string) $streamChannelMediaId; $streamChannelArchive = CM_Model_StreamChannelArchive_Media::findByMediaId($streamChannelMediaId); if (!$streamChannelArchive) { $streamChannel = CM_Model_StreamChannel_Media::findByMediaId($streamChannelMediaId); if ($streamChannel) { throw new CM_Exception_Invalid('Archive not created, please try again later', null, ['streamChannelMediaId' => $streamChannelMediaId]); } $exception = new CM_Exception_Invalid('Archive not found, stream channel not found, skipping', CM_Exception::WARN, ['streamChannelMediaId' => $streamChannelMediaId]); $context = new CM_Log_Context(); $context->setException($exception); $this->getServiceManager()->getLogger()->warning('Archive creating error', $context); return; } $filename = $streamChannelArchive->getId() . '-' . $streamChannelArchive->getHash() . '-original.' . $archiveSource->getExtension(); $archiveDestination = new CM_File_UserContent('streamChannels', $filename, $streamChannelArchive->getId()); $archiveDestination->ensureParentDirectory(); $archiveSource->copyToFile($archiveDestination); $streamChannelArchive->setFile($archiveDestination); }
/** * @param $manifestPath * @param string $devicePath * @param bool|null $skipFormat * @param bool|null $dryRun */ public function createJob($manifestPath, $devicePath, $skipFormat = null, $dryRun = null) { $manifestPath = (string) $manifestPath; if (!preg_match('/^\\//', $manifestPath)) { $manifestPath = getcwd() . '/' . $manifestPath; } $devicePath = (string) $devicePath; $skipFormat = (bool) $skipFormat; $dryRun = (bool) $dryRun; $awsBackupManager = $this->_getBackupManager(); $this->_getStreamOutput()->writeln('Preparing backup device'); $device = new S3Export_Device($devicePath); if (!$skipFormat) { $device->format(); } $device->mount(); $this->_getStreamOutput()->writeln('Creating AWS backup job'); $manifestFile = new CM_File($manifestPath); $job = $awsBackupManager->createJob($manifestFile->read(), $dryRun); $this->_getStreamOutput()->writeln("Job created, id: `{$job->getId()}`"); $this->_getStreamOutput()->writeln('Storing AWS Signature on backup device'); $awsBackupManager->storeJobSignatureOnDevice($job, $device); $device->unmount(); }
/** * @param string $namespace * @param string $filename * @param int|null $sequence * @param CM_Service_Manager|null $serviceManager */ public function __construct($namespace, $filename, $sequence = null, CM_Service_Manager $serviceManager = null) { $namespace = (string) $namespace; $filename = (string) $filename; if (null !== $sequence) { $sequence = (int) $sequence; } if (null === $serviceManager) { $serviceManager = CM_Service_Manager::getInstance(); } $this->_pathRelative = $this->_calculateRelativeDir($namespace, $filename, $sequence); $this->_namespace = $namespace; $this->setServiceManager($serviceManager); $filesystem = $serviceManager->getUserContent()->getFilesystem($this->getNamespace()); parent::__construct($this->getPathRelative(), $filesystem); }
/** * @param CM_File $file * @param string|null $content * @param bool|null $overwrite */ public function createFile(CM_File $file, $content = null, $overwrite = null) { $parentDirectory = $file->getParentDirectory(); if (!$parentDirectory->exists()) { $this->createDirectory($parentDirectory); } if ($file->exists()) { if (!$overwrite) { $this->notify('skip', $file->getPath()); } else { $this->notify('modify', $file->getPath()); $file->write($content); } } else { $this->notify('create', $file->getPath()); $file->write($content); } }
/** * @runInSeparateProcess * @preserveGlobalState disabled */ public function testForkAndWaitForChildren() { $file = CM_File::createTmp(); $process = CM_Process::getInstance(); $parentOutput = []; for ($i = 1; $i <= 4; $i++) { $parentOutput[] = "Child {$i} forked."; $process->fork(function () use($i, $file) { $ms = 100 * $i; usleep($ms * 1000); $file->appendLine("Child {$i} terminated after {$ms} ms."); }); } $parentOutput[] = 'Parent waiting for 250 ms...'; usleep(250000); $parentOutput[] = 'Parent listening to children...'; $process->waitForChildren(); $parentOutput[] = 'Parent terminated.'; $childrenOutput = explode(PHP_EOL, $file->read()); $this->assertSame(['Child 1 forked.', 'Child 2 forked.', 'Child 3 forked.', 'Child 4 forked.', 'Parent waiting for 250 ms...', 'Parent listening to children...', 'Parent terminated.'], $parentOutput); $this->assertContainsAll(['Child 2 terminated after 200 ms.', 'Child 1 terminated after 100 ms.', 'Child 3 terminated after 300 ms.', 'Child 4 terminated after 400 ms.'], $childrenOutput); }
public function testDeleteByPrefix() { $filesystem = new CM_File_Filesystem(new CM_File_Filesystem_Adapter_Local()); $dirTmp = CM_Bootloader::getInstance()->getDirTmp(); $pathList = array('foo/foobar/bar', 'foo/bar2', 'foo/bar'); /** @var CM_File[] $fileList */ $fileList = array(); foreach ($pathList as $path) { $file = new CM_File($dirTmp . $path, $filesystem); $file->ensureParentDirectory(); $file->write('hello'); $fileList[] = $file; $fileList[] = $file->getParentDirectory(); } foreach ($fileList as $file) { $this->assertTrue($file->exists()); } $filesystem->deleteByPrefix($dirTmp); foreach ($fileList as $file) { $this->assertFalse($file->exists()); } $this->assertTrue((new CM_File($dirTmp))->exists()); }
public function testGetFileNonexistent() { $fileNonexistent = new CM_File('foo/bar'); $params = new CM_Params(array('nonexistent' => $fileNonexistent->getPath())); $this->assertEquals($fileNonexistent, $params->getFile('nonexistent')); }
/** * @expectedException CM_Exception_FormFieldValidation */ public function testValidateFileNoImage() { $image = CM_File::createTmp(); $formField = new CM_FormField_FileImage(); $formField->validateFile($image); }