/** * This function is used to uplodad file in /uploads/YEAR/MONTH directory * and to create Content record contextually. * * * @param type $inputfile * @param string $destfile * @return boolean */ public function upload($inputfile, $destfile = null) { if (strlen(trim($inputfile['name'])) === 0) { return FALSE; } $filename = strtolower($inputfile['name']); $sourcefile = $inputfile['tmp_name']; $file = new \Cake\Filesystem\File($sourcefile, true, 0775); $CONTENT_YEAR = date('Y'); $CONTENT_MONTH = date('m'); $UPLOAD_DIR = $this->path; $folder_dest = new Folder($UPLOAD_DIR); if (!$folder_dest->inCakePath($folder_dest->pwd() . DS . $CONTENT_YEAR)) { $folder_dest->create($folder_dest->pwd() . DS . $CONTENT_YEAR); } $folder_dest->cd($CONTENT_YEAR); if (!$folder_dest->inCakePath($folder_dest->pwd() . DS . $CONTENT_MONTH)) { $folder_dest->create($folder_dest->pwd() . DS . $CONTENT_MONTH); } $folder_dest->cd($CONTENT_MONTH); $path = DS . $CONTENT_YEAR . DS . $CONTENT_MONTH . DS; $permittedFilename = $this->getPermittedFilename($UPLOAD_DIR . $path, $filename); $destfile = $folder_dest->pwd() . DS . $permittedFilename; if ($file->copy($destfile, true)) { return $path . $permittedFilename; } else { return FALSE; } }
/** * Cria um plugin de teste e o carrega para conseguir rodar os testes. */ public function setUp() { parent::setUp(); $testData = ['full_path' => ROOT . DS . 'plugins' . DS . 'ThemeInstallerTest' . DS, 'config_folder' => ROOT . DS . 'plugins' . DS . 'ThemeInstallerTest' . DS . 'config' . DS, 'css_folder' => ROOT . DS . 'plugins' . DS . 'ThemeInstallerTest' . DS . 'webroot' . DS . '_assets' . DS . 'css' . DS, 'js_folder' => ROOT . DS . 'plugins' . DS . 'ThemeInstallerTest' . DS . 'webroot' . DS . '_assets' . DS . 'js' . DS, 'img_folder' => ROOT . DS . 'plugins' . DS . 'ThemeInstallerTest' . DS . 'webroot' . DS . '_assets' . DS . 'img' . DS, 'packages_folder' => ROOT . DS . 'plugins' . DS . 'ThemeInstallerTest' . DS . 'webroot' . DS . '_assets' . DS . 'packages' . DS]; $pluginFolder = new Folder($testData['full_path'], self::CREATE_FOLDER_IF_NOT_EXISTS, self::PLUGIN_FOLDER_PERMISSIONS); $pluginFolder->create($testData['config_folder']); $pluginFolder->create($testData['css_folder']); $pluginFolder->create($testData['js_folder']); $pluginFolder->create($testData['img_folder']); $pluginFolder->create($testData['packages_folder'] . 'sample_package'); $defaultSettingsFile = new File($testData['config_folder'] . 'default_settings.php', true); $defaultSettingsFile->write("<?php \n\t\t\treturn [\n\t\t\t\t'MyApplication.Modules.ThemeInstallerTest.Settings' => \n\t\t\t\t\t['Default' => true]\n\t\t\t\t]; \n\t\t?>"); $defaultSettingsFile->close(); $file = new File($testData['css_folder'] . 'sample.css', true); $file->write('#id { }'); $file->close(); $file = new File($testData['js_folder'] . 'sample.js', true); $file->write('#id { }'); $file->close(); $file = new File($testData['packages_folder'] . 'sample_package' . DS . 'sample.css', true); $file->write('#id { }'); $file->close(); $file = new File($testData['packages_folder'] . 'sample_package' . DS . 'sample.js', true); $file->write('#id { }'); $file->close(); $bootstrapFile = new File($testData['config_folder'] . 'bootstrap.php', true); $bootstrapFile->close(); }
/** * Test plugin load by list. * * @return void */ public function testLoadList() { $Folder = new Folder(); $pluginsDir = APP_ROOT . 'Plugins' . DS; $TestPlgPath = $pluginsDir . 'PluginTest'; $Folder->create($TestPlgPath, 0777); new File($TestPlgPath . '/config/bootstrap.php', true); new File($TestPlgPath . '/config/routes.php', true); $NoRoutesPlgPath = $pluginsDir . 'NoRoutes'; $Folder->create($NoRoutesPlgPath, 0777); new File($NoRoutesPlgPath . '/config/bootstrap.php', true); $NoBootstrapPlgPath = $pluginsDir . 'NoBootstrap'; $Folder->create($NoBootstrapPlgPath, 0777); new File($NoBootstrapPlgPath . '/config/routes.php', true); $NoConfigPlgPath = $pluginsDir . 'NoConfig'; $Folder->create($NoConfigPlgPath, 0777); Plugin::load('Migrations'); Plugin::loadList(['NoConfig', 'NoRoutes', 'PluginTest', 'Migrations', 'NoBootstrap']); $this->assertTrue(Plugin::loaded('NoBootstrap')); $this->assertTrue(Plugin::loaded('PluginTest')); $this->assertTrue(Plugin::loaded('NoRoutes')); $this->assertTrue(Plugin::loaded('NoConfig')); // Check virtual paths. $this->assertSame(1, count(vPath()->getPaths('NoBootstrap:'))); $this->assertSame(1, count(vPath()->getPaths('PluginTest:'))); $this->assertSame(1, count(vPath()->getPaths('NoRoutes:'))); $this->assertSame(1, count(vPath()->getPaths('NoConfig:'))); $Folder->delete($TestPlgPath); $Folder->delete($NoRoutesPlgPath); $Folder->delete($NoConfigPlgPath); $Folder->delete($NoBootstrapPlgPath); }
/** * Check if there is some files to upload and modify the entity before * it is saved. * * At the end, for each files to upload, unset their "virtual" property. * * @param Event $event The beforeSave event that was fired. * @param Entity $entity The entity that is going to be saved. * * @throws \LogicException When the path configuration is not set. * @throws \ErrorException When the function to get the upload path failed. * * @return void */ public function beforeSave(Event $event, Entity $entity) { $config = $this->_config; foreach ($config['fields'] as $field => $fieldOption) { $data = $entity->toArray(); $virtualField = $field . $config['suffix']; if (!isset($data[$virtualField]) || !is_array($data[$virtualField])) { continue; } $file = $entity->get($virtualField); if ((int) $file['error'] === UPLOAD_ERR_NO_FILE) { continue; } if (!isset($fieldOption['path'])) { throw new \LogicException(__('The path for the {0} field is required.', $field)); } if (isset($fieldOption['prefix']) && (is_bool($fieldOption['prefix']) || is_string($fieldOption['prefix']))) { $this->_prefix = $fieldOption['prefix']; } $extension = (new File($file['name'], false))->ext(); $uploadPath = $this->_getUploadPath($entity, $fieldOption['path'], $extension); if (!$uploadPath) { throw new \ErrorException(__('Error to get the uploadPath.')); } $folder = new Folder($this->_config['root']); $folder->create($this->_config['root'] . dirname($uploadPath)); if ($this->_moveFile($entity, $file['tmp_name'], $uploadPath, $field, $fieldOption)) { if (!$this->_prefix) { $this->_prefix = ''; } $entity->set($field, $this->_prefix . $uploadPath); } $entity->unsetProperty($virtualField); } }
public function beforeMarshal(Event $event, $data, $options) { $config = $this->_config; foreach ($config['fields'] as $fieldKey => $fieldValue) { $virtualField = $fieldKey; $file = $data[$fieldKey]; if ((int) $file['error'] === UPLOAD_ERR_NO_FILE) { continue; } if (!isset($fieldValue['path'])) { throw new \LogicException(__('The path for the {0} field is required.', $fieldKey)); } if (isset($fieldValue['prefix']) && (is_bool($fieldValue['prefix']) || is_string($fieldValue['prefix']))) { $this->_prefix = $fieldValue['prefix']; } $extension = (new File($file['name'], false))->ext(); $uploadPath = $this->_getUploadPath($data, $fieldValue['path'], $extension); if (!$uploadPath) { throw new \ErrorException(__('Error to get the uploadPath.')); } $folder = new Folder($this->_config['root']); $folder->create($this->_config['root'] . dirname($uploadPath)); if ($this->_moveFile($data, $file['tmp_name'], $uploadPath, $fieldKey, $fieldValue)) { if (!$this->_prefix) { $this->_prefix = ''; } $data[$fieldKey] = $uploadPath; } } }
/** * Scan folder by path. * * @param null $path * @return void|\Cake\Network\Response */ public function scanFolder($path = null) { if (!$path) { $path = WWW_ROOT; } $Folder = new Folder(); $_path = $this->request->query('path') ? $this->request->query('path') : $path; if (!is_dir($_path)) { $Folder->create($_path); } $_path = realpath($_path) . DS; $regex = '/^' . preg_quote(realpath($path), '/') . '/'; if (preg_match($regex, $_path) == false) { $this->_controller->Flash->error(__d('file_manager', 'Path {0} is restricted', $_path)); return $this->_controller->redirect(['action' => 'browse']); } $blacklist = ['.git', '.svn', '.CVS']; $regex = '/(' . preg_quote(implode('|', $blacklist), '.') . ')/'; if (in_array(basename($_path), $blacklist) || preg_match($regex, $_path)) { $this->_controller->Flash->error(__d('file_manager', 'Path %s is restricted', $_path)); return $this->_controller->redirect(['action' => 'browse']); } $Folder->path = $_path; $content = $Folder->read(); $this->_controller->set('path', $_path); $this->_controller->set('content', $content); }
private function removeAndCreateFolder($path) { $dir = new Folder($path); $dir->delete(); $dir->create($path); $file = new File($path . DS . 'empty'); $file->create(); }
/** * Test exist theme plugin. * * @return void */ public function testExistTheme() { $name = Configure::read('Theme.site'); $path = $this->_paths[1] . $name; $this->_folder->create($path); $this->assertSame($path, Theme::exist($name)); $this->_folder->delete($path); }
public function afterSave(Event $event, Entity $site, \ArrayObject $options) { $sitePath = WWW_ROOT . '..' . DS . self::SITES_DIR . DS . 'site' . $site->id; $folder = new Folder(); if (!$folder->create($sitePath, 0755)) { throw new InternalErrorException('Error create site files'); } $indexHtml = new File($sitePath . DS . 'index.html', true, 0644); $indexHtml->write($site->content); }
private function checkIfSubfolderExistsAndCreateIfFalseAndReturnPath($folder, $subfolder) { $folderObject = new Folder($folder); $folder = $folderObject->read(); if (!in_array($subfolder, $folder[0])) { $folderObject->create($subfolder); } $folderObject->cd($subfolder); return $folderObject->path; }
public function addDirImg() { if ($this->request->is('post')) { $dossier_nom = $this->request->data['dossier_nom']; $folder = new Folder(ROOT . '/plugins/Admin/webroot/img/projets/'); $folder->create($dossier_nom); $this->Flash->success(__('Le dossier a été créé avec succès !')); return $this->redirect(['action' => 'index']); } $this->set('data', ['title' => __("Ajouter un dossier d'images")]); $this->set(compact('data')); }
/** * Cria um plugin de teste e o carrega para conseguir rodar os testes. */ public function setUp() { parent::setUp(); $testPluginData = ['full_path' => ROOT . DS . 'plugins' . DS . 'PluginInstallerTest' . DS, 'config_folder' => ROOT . DS . 'plugins' . DS . 'PluginInstallerTest' . DS . 'config' . DS]; $pluginFolder = new Folder($testPluginData['full_path'], self::CREATE_FOLDER_IF_NOT_EXISTS, self::PLUGIN_FOLDER_PERMISSIONS); $pluginFolder->create('config'); $defaultSettingsFile = new File($testPluginData['config_folder'] . 'default_settings.php', true); $defaultSettingsFile->write("<?php \n\t\t\treturn [\n\t\t\t\t'MyApplication.Modules.PluginInstallerTest.Settings' => \n\t\t\t\t\t['Default' => true]\n\t\t\t\t]; \n\t\t?>"); $defaultSettingsFile->close(); $bootstrapFile = new File($testPluginData['config_folder'] . 'bootstrap.php', true); $bootstrapFile->close(); Plugin::load('PluginInstallerTest', ['routes' => false, 'bootstrap' => false]); }
public function create($path = null) { $root = WWW_ROOT; $fullPath = $root . $path; if ($this->request->is('post')) { $folderName = $this->request->data['name']; $folder = new Folder($fullPath); if ($folder->create($folderName)) { $this->Flash->success(__('The folder "{0}" has been created.', $folderName)); return $this->redirect(['action' => 'index', $path]); } $this->Flash->error(__('The folder "{0}" could not be created.', $folderName)); } }
/** * Faz uma instalação básica do plugin. * A instalação consiste em criar o arquivo de configurações do plugin no diretório apropriado. * Este método é chamado pelo método PluginStarter::load() quando necessário. * * @param string $pluginName O nome do plugin a ser instalado. * @return void */ public function install($pluginName) { $settingsFileFolder = $this->pluginInstallationFolder . $pluginName . DS; if (Plugin::loaded($pluginName)) { $defaultFile = Plugin::path($pluginName) . 'config' . DS . 'default_settings.php'; $folderHandler = new Folder(); if (!$folderHandler->cd($settingsFileFolder)) { $folderHandler->create($settingsFileFolder); } $fileHandler = new File($defaultFile); $fileHandler->copy($settingsFileFolder . 'settings.php'); $fileHandler->close(); } }
/** * Upload a file to the server * @param upload - file to upload * @param owner - contains model name and id associated with the file * @return array - uploaded file information or null for failure */ public function upload($upload, $owner = null) { // Filesize verification if ($upload['size'] == 0) { return null; } if ($upload['size'] > $this->maxFileSize) { return null; } $path = $this->storagePath; // Owner separated storage if ($this->storeOwner == true && $owner) { // Directory should be lower case $ownerTable = strtolower($owner->source()); // Owner specific directory must be unique (uuid) $ownerDirectory = Inflector::singularize($ownerTable) . $owner->id; $path .= DS . $ownerTable . DS . $ownerDirectory; } // If types do not match, default subdir is 'document' $subdir = 'document'; $types = ['image', 'audio', 'video']; // Check for filetype foreach ($types as $type) { if (strstr($upload['type'], $type)) { $subdir = $type; } } // Append the subdirectory (filtype directory) $path .= DS . $subdir; // Make directory if there is none $directory = new Folder(); if (!$directory->create(WWW_ROOT . DS . $path)) { return null; } // Find file in tmp $file = new File($upload['tmp_name']); // File's name must be unique, making the path unique as well $name = time() . '_' . Inflector::slug($upload['name']); $path .= DS . $name; // Copy from tmp to perm (create) if ($file->copy($path)) { return ['original_name' => $upload['name'], 'name' => $name, 'path' => $path, 'type' => $upload['type'], 'size' => $upload['size']]; } else { return null; } }
define('APP', ROOT . '/tests/App/'); define('CONFIG', ROOT . '/tests/config/'); define('WWW_ROOT', ROOT . DS . WEBROOT_DIR . DS); define('TESTS', ROOT . DS . 'tests' . DS); define('TMP', ROOT . DS . 'tmp' . DS); define('LOGS', TMP . 'logs' . DS); define('CACHE', TMP . 'cache' . DS); define('CAKE_CORE_INCLUDE_PATH', ROOT . '/vendor/cakephp/cakephp'); define('CORE_PATH', CAKE_CORE_INCLUDE_PATH . DS); define('CAKE', CORE_PATH . 'src' . DS); require ROOT . '/vendor/autoload.php'; require CORE_PATH . 'config/bootstrap.php'; Configure::write('App', ['namespace' => $pluginName . '\\Test\\App', 'paths' => ['templates' => [APP . 'Template' . DS]]]); Configure::write('debug', true); $TMP = new Folder(TMP); $TMP->create(TMP . 'cache/models', 0777); $TMP->create(TMP . 'cache/persistent', 0777); $TMP->create(TMP . 'cache/views', 0777); $cache = ['default' => ['engine' => 'File'], '_cake_core_' => ['className' => 'File', 'prefix' => strtolower($pluginName) . '_myapp_cake_core_', 'path' => CACHE . 'persistent/', 'serialize' => true, 'duration' => '+10 seconds'], '_cake_model_' => ['className' => 'File', 'prefix' => strtolower($pluginName) . '_my_app_cake_model_', 'path' => CACHE . 'models/', 'serialize' => 'File', 'duration' => '+10 seconds']]; Cake\Cache\Cache::config($cache); Cake\Core\Configure::write('Session', ['defaults' => 'php']); // Ensure default test connection is defined if (!getenv('db_dsn')) { putenv('db_dsn=sqlite:///:memory:'); } Cake\Datasource\ConnectionManager::config('default', ['url' => getenv('db_dsn'), 'quoteIdentifiers' => true, 'timezone' => 'UTC']); Cake\Datasource\ConnectionManager::config('test', ['url' => getenv('db_dsn'), 'quoteIdentifiers' => true, 'timezone' => 'UTC']); // Alias AppController to the test App class_alias($pluginName . '\\Test\\App\\Controller\\AppController', 'App\\Controller\\AppController'); // If plugin has routes.php/bootstrap.php then load them, otherwise don't. $loadPluginRoutes = file_exists(dirname(__FILE__) . DS . 'config' . DS . 'routes.php');
/** * Upload user profile image. * * @param User $user */ protected function _uploadAvatar(User $user) { if (isset($this->_tmpImage) && file_exists($this->_tmpImage['tmp_name'])) { $imageInfo = pathinfo($this->_tmpImage['name']); $imageName = 'orig_' . $user->get('id') . '.' . $imageInfo['extension']; $folderPath = $this->_path->entityFolderPath($user->get('id'), DS); $imagePath = $folderPath . $imageName; $Folder = new Folder(); // Delete user folder if upload new image. if (is_dir($folderPath)) { $Folder->delete($folderPath); } if (!is_dir($folderPath)) { $Folder->create($folderPath); } if (is_dir($folderPath) && move_uploaded_file($this->_tmpImage['tmp_name'], $imagePath)) { $user->set('image', $imageName); $thumbName = 'thumb_' . $user->get('id') . '.' . $imageInfo['extension']; // Resize original image. $Resize = new ImageThumbnail($imagePath); $Resize->sizeWidth(450); $Resize->save($imagePath); // Resize and crop thumb. $Thumbnail = new ImageThumbnail($imagePath); $Thumbnail->setResize(false); $Thumbnail->setSize($this->_config['thumbWidth'], $this->_config['thumbHeight']); $Thumbnail->save($folderPath . $thumbName); } } }
/** * afterSave Event. If an attachment entity has its tmpPath value set, it will be moved * to the defined filepath * * @param Event $event Event * @param Attachment $attachment Entity * @param ArrayObject $options Options * @return void * @throws \Exception If the file couldn't be moved */ public function afterSave(Event $event, Attachment $attachment, \ArrayObject $options) { if ($attachment->tmpPath) { // Make sure the folder is created $folder = new Folder(); $targetDir = Configure::read('Attachments.path') . dirname($attachment->filepath); if (!$folder->create($targetDir)) { throw new \Exception("Folder {$targetDir} could not be created."); } $targetPath = Configure::read('Attachments.path') . $attachment->filepath; if (!rename($attachment->tmpPath, $targetPath)) { throw new \Exception("Temporary file {$attachment->tmpPath} could not be moved to {$attachment->filepath}"); } $attachment->tmpPath = null; } }
public function changePhoto() { $directory = strtolower(str_replace(' ', '-', $this->userID)); $rootDir = WWW_ROOT . 'img/profiles'; $path = $rootDir . '/' . $directory; $folder = new Folder(); if (!is_dir($path)) { $folder->create($path); } $profileImg['profile']['profile_pic'] = ''; if (isset($this->request->data['photo']['name']) && $this->request->data['photo']['name']) { $profileImg['profile']['profile_pic'] = $this->userID . '/' . $this->Utilities->uploadProfilePhoto($path, $this->request->data['photo']); } $user = $this->Users->get($this->userID, ['contain' => ['Profiles']]); if ($this->request->is(['patch', 'post', 'put'])) { $user = $this->Users->patchEntity($user, $profileImg); if ($this->Users->save($user)) { $this->Flash->success(__('Your profile photo updated successfully')); } else { $this->Flash->error(__('Sorry, something went wrong')); } } return $this->redirect(['users' > 'users', 'action' => 'profile']); }
define('APP_ROOT', ROOT . 'tests' . DS . 'test_app' . DS); define('APP', APP_ROOT . APP_DIR . DS); define('CONFIG', APP_ROOT . 'config' . DS); define('ASSETS_CACHE', APP_ROOT . 'cache'); define('TMP', APP_ROOT); define('LOGS', TMP . 'logs' . DS); define('CACHE', TMP . 'cache' . DS); define('SESSIONS', TMP . 'sessions' . DS); define('UNION_CORE_PATH', ROOT . 'vendor/union-cms/core/'); // CakePHP constants. define('CAKE_CORE_INCLUDE_PATH', ROOT . '/vendor/cakephp/cakephp'); define('CORE_PATH', CAKE_CORE_INCLUDE_PATH . DS); define('CAKE', CORE_PATH . 'src' . DS); // Create test app folders. $folder = new Folder(); $folder->create(LOGS, 0777); $folder->create(SESSIONS, 0777); $folder->create(CACHE, 0777); $folder->create(CACHE . 'view', 0777); $folder->create(CACHE . 'models', 0777); date_default_timezone_set('UTC'); mb_internal_encoding('UTF-8'); // Include CakePHP framework. /** @noinspection PhpIncludeInspection */ require_once CAKE_CORE_INCLUDE_PATH . '/config/bootstrap.php'; $path = Path::getInstance(); // Load union core plugin. Plugin::load('Union/Core', ['routes' => true, 'bootstrap' => true]); $path->setRoot(APP_ROOT); $path->set('cache', ASSETS_CACHE); $path->set('Union/Core', ROOT);
private function crop($options, $filePath) { $config = $this->_config; $pathInfo = pathinfo($filePath); $point = new Point($options['x'], $options['y']); $box = new Box($options['width'], $options['height']); $folder = new Folder($config['root']); $folder->create($config['root'] . $options['path']); $savePath = $config['root'] . $options['path']; if (!empty($options['prefix'])) { $savePath .= $options['prefix']; } $savePath .= $pathInfo['filename']; if (!empty($options['suffix'])) { $savePath .= $options['suffix']; } $savePath .= '.' . $pathInfo['extension']; $imagine = new Imagine(); $image = $imagine->open($config['root'] . $filePath); $image->crop($point, $box)->save($savePath); }
public function upload($system, $path) { // UPLOAD THE FILE TO THE RIGHT SYSTEM if ($system == 'production') { $other = 'development'; } else { $other = 'production'; } $path = str_replace('___', '/', $path); $file = new File('../../' . $other . $path); $file2 = new File('../../' . $system . $path); if (!$file2->exists()) { $dirs = explode('/', $path); $prod = new Folder('../../' . $system); for ($i = 0; $i < sizeof($dirs) - 1; $i++) { if (!$prod->cd($dirs[$i])) { $prod->create($dirs[$i]); $prod->cd($dirs[$i]); } } } if ($file->copy('../../' . $system . $path)) { if (touch('../../' . $system . $path, $file->lastChange())) { $this->Flash->success(__('File copied successfully.')); } else { $this->Flash->success(__('File copied successfully, but time not updated.')); } } else { $this->Flash->error(__('Unable copy file. ')); } return $this->redirect($this->referer()); }
define('DS', DIRECTORY_SEPARATOR); define('ROOT', dirname(__DIR__) . DS); define('APP_DIR', 'test_app'); define('WEBROOT_DIR', 'webroot'); define('CONFIG', ROOT . DS . 'config' . DS); define('APP', ROOT . DS . 'tests' . DS . APP_DIR . DS); define('WWW_ROOT', ROOT . DS . WEBROOT_DIR . DS); define('TESTS', ROOT . DS . 'tests' . DS . 'Test' . DS); define('TMP', ROOT . DS . 'tmp' . DS); define('LOGS', TMP . 'logs' . DS); define('CACHE', TMP . 'cache' . DS); define('CAKE_CORE_INCLUDE_PATH', ROOT . '/vendor/cakephp/cakephp'); define('CORE_PATH', CAKE_CORE_INCLUDE_PATH . DS); define('CAKE', CORE_PATH . 'src' . DS); require ROOT . '/vendor/cakephp/cakephp/src/basics.php'; require ROOT . '/vendor/autoload.php'; Configure::write('debug', true); Configure::write('App', ['namespace' => '\\Macro\\Test\\App', 'encoding' => 'UTF-8', 'base' => false, 'baseUrl' => false, 'dir' => 'src', 'webroot' => 'webroot', 'www_root' => APP . 'webroot', 'fullBaseUrl' => 'http://localhost', 'imageBaseUrl' => 'img/', 'jsBaseUrl' => 'js/', 'cssBaseUrl' => 'css/', 'paths' => ['plugins' => [APP . 'Plugin' . DS], 'templates' => [APP . 'Template' . DS]]]); Configure::write('Session', ['defaults' => 'php']); $TMP = new Folder(TMP); $TMP->create(TMP . 'cache/persistent', 0777); $cache = ['default' => ['engine' => 'Null'], '_cake_core_' => ['className' => 'Null', 'prefix' => 'cakepdf_myapp_cake_core_', 'path' => CACHE . 'persistent/', 'serialize' => 'File', 'duration' => '+10 seconds']]; Cache::config($cache); // Ensure default test connection is defined if (!getenv('db_class')) { putenv('db_class=Cake\\Database\\Driver\\Sqlite'); putenv('db_dsn=sqlite::memory:'); } ConnectionManager::config('test', ['className' => 'Cake\\Database\\Connection', 'driver' => getenv('db_class'), 'dsn' => getenv('db_dsn'), 'database' => getenv('db_database'), 'login' => getenv('db_login'), 'password' => getenv('db_password'), 'timezone' => 'UTC']); Plugin::load('Macro', ['path' => ROOT, 'bootstrap' => true]); DispatcherFactory::add('ControllerFactory');
/** * Check if there is some files to upload and modify the entity before * it is saved. * * For each files to upload, unset their "virtual" property. * * @param Event $event The beforeSave event that was fired. * @param Entity $entity The entity that is going to be saved. * * @throws \ErrorException */ public function beforeSave(Event $event, Entity $entity) { $config = $this->_config; /** * Foreach file set in the configuration, do the upload. */ foreach ($config['fields'] as $field => $fieldOption) { $data = $entity->toArray(); $virtualField = $field . $config['suffix']; /** * Check if the "virtual" field is in the data array and if this * field have a name param. (This is only for check if its a file type.) */ if (isset($data[$virtualField]) && !empty($data[$virtualField]['name'])) { //Get the array (name, tmp_name etc) of the virtual field. $file = $entity->get($virtualField); /** * If the tmp_name is empty, that mean there was an error while uploading * the file in the temporary directory. */ if (empty($file['tmp_name'])) { continue; } if (!isset($fieldOption['path'])) { throw new \ErrorException(__('Error to get the path for the {0} field.', $field)); } /** * Check if the user has set an option for the prefix, else use the default prefix config. */ if (isset($fieldOption['prefix']) && (is_bool($fieldOption['prefix']) || is_string($fieldOption['prefix']))) { $this->_prefix = $fieldOption['prefix']; } /** * Get the upload path with identifiers replaced by their corresponding folders. */ $uploadPath = $this->getUploadPath($entity, $fieldOption['path'], (new File($file['name'], false))->ext()); if (!$uploadPath) { throw new \ErrorException(__('Error to get the uploadPath.')); } /** * Create the folders if it doesn't exist. */ $this->_folder->create(dirname($uploadPath), 0755); /** * Try to move the temporary file to the correct upload path. */ if ($this->moveFile($entity, $file['tmp_name'], $uploadPath, $fieldOption, $field)) { if (!$this->_prefix) { $this->_prefix = ''; } /** * Set the new value for the current field. */ $entity->set($field, $this->_prefix . $uploadPath); } } /** * Unset the virtual field from the Entity. */ $entity->unsetProperty($virtualField); } }
/** * beforeSave handle * @param \Cake\Event\Event $event The beforeSave event that was fired. * @param \Cake\ORM\Entity $entity The entity that is going to be saved. * @return void */ public function beforeSave(Event $event, Entity $entity) { // get config $config = $this->_config; // go through each field foreach ($config['fields'] as $field => $path) { // set virtual upload field $virtual = $field . $config['suffix']; // no field or field not array? skip if (!isset($entity[$virtual]) || !is_array($entity[$virtual])) { continue; } // get uploaded file information $file = $entity->get($virtual); // file not ok? skip if ((int) $file['error'] !== UPLOAD_ERR_OK) { continue; } // get the final name $final = $this->path($entity, $file, $path); // create the folder $folder = new Folder($config['root']); $folder->create($config['root'] . dirname($final)); // upload the file $file = new File($file['tmp_name'], false); if ($file->copy($config['root'] . $final)) { // get previous file and delete it $previous = $entity->get($field); if ($previous) { $old = new File($config['root'] . str_replace('/', DS, $previous), false); if ($old->exists()) { $old->delete(); } } // set new file $entity->set($field, str_replace(DS, '/', $final)); } // unset virtual $entity->unsetProperty($virtual); } }
function export() { // Step 4: export default.pot file to the relevant directory $wnk_translation = Configure::read('WnkTranslation'); $filename = 'f' . gmdate('YmdHis'); // iterate through all configured languages: foreach ($wnk_translation['trans_lang'] as $k) { if ($k == $wnk_translation['default_lang']) { continue; } $path = ROOT . DS . 'src' . DS . 'Locale' . DS . $k; $folder = new Folder(); if (!file_exists($path)) { $folder->create($path); } $file = $path . DS . $filename; $file = new File($file, true, 0644); $z = 0; $data = TableRegistry::get('WnkTranslation.Translations')->find('all')->where(["locale" => $k])->all(); foreach ($data as $rec) { if ($rec->status == 'Original' or $rec->status == 'TranslatedByUser' or $rec->status == 'TranslatedByMachine') { $file->write('msgid "' . $rec->msgid . '"' . "\n"); $file->write('msgstr "' . $rec->msgstr . '"' . "\n"); $z++; } } $file->close(); if (file_exists($path . DS . 'default.po')) { unlink($path . DS . 'default.po'); } rename($path . DS . $filename, $path . DS . 'default.po'); } return 'Export successful with ' . $z . ' Records'; }
/** * testFindRecursive method * * @return void */ public function testFindRecursive() { $Folder = new Folder(CORE_PATH); $result = $Folder->findRecursive('(config|paths)\\.php'); $expected = [CORE_PATH . 'config' . DS . 'config.php']; $this->assertSame([], array_diff($expected, $result)); $this->assertSame([], array_diff($expected, $result)); $result = $Folder->findRecursive('(config|woot)\\.php', true); $expected = [CORE_PATH . 'config' . DS . 'config.php']; $this->assertSame($expected, $result); $path = TMP . 'tests' . DS; $Folder = new Folder($path, true); $Folder->create($path . 'sessions'); $Folder->create($path . 'testme'); $Folder->cd($path . 'testme'); $File = new File($Folder->pwd() . DS . 'paths.php'); $File->create(); $Folder->cd($path . 'sessions'); $result = $Folder->findRecursive('paths\\.php'); $expected = []; $this->assertSame($expected, $result); $Folder->cd($path . 'testme'); $File = new File($Folder->pwd() . DS . 'my.php'); $File->create(); $Folder->cd($path); $result = $Folder->findRecursive('(paths|my)\\.php'); $expected = [$path . 'testme' . DS . 'my.php', $path . 'testme' . DS . 'paths.php']; $this->assertSame(sort($expected), sort($result)); $result = $Folder->findRecursive('(paths|my)\\.php', true); $expected = [$path . 'testme' . DS . 'my.php', $path . 'testme' . DS . 'paths.php']; $this->assertSame($expected, $result); }
/** * Bake the plugin, create directories and files * * @param string $plugin Name of the plugin in CamelCased format * @return bool */ public function bake($plugin) { $pathOptions = App::path('Plugin'); if (count($pathOptions) > 1) { $this->findPath($pathOptions); } $this->hr(); $this->out(sprintf("<info>Plugin Name:</info> %s", $plugin)); $this->out(sprintf("<info>Plugin Directory:</info> %s", $this->path . $plugin)); $this->hr(); $classBase = 'src'; $looksGood = $this->in('Look okay?', ['y', 'n', 'q'], 'y'); if (strtolower($looksGood) === 'y') { $Folder = new Folder($this->path . $plugin); $directories = ['config', $classBase . DS . 'Model' . DS . 'Behavior', $classBase . DS . 'Model' . DS . 'Table', $classBase . DS . 'Model' . DS . 'Entity', $classBase . DS . 'Shell' . DS . 'Task', $classBase . DS . 'Controller' . DS . 'Component', $classBase . DS . 'View' . DS . 'Helper', $classBase . DS . 'Template', 'tests' . DS . 'TestCase' . DS . 'Controller' . DS . 'Component', 'tests' . DS . 'TestCase' . DS . 'View' . DS . 'Helper', 'tests' . DS . 'TestCase' . DS . 'Model' . DS . 'Behavior', 'tests' . DS . 'Fixture', 'webroot']; foreach ($directories as $directory) { $dirPath = $this->path . $plugin . DS . $directory; $Folder->create($dirPath); new File($dirPath . DS . 'empty', true); } foreach ($Folder->messages() as $message) { $this->out($message, 1, Shell::VERBOSE); } $errors = $Folder->errors(); if (!empty($errors)) { foreach ($errors as $message) { $this->error($message); } return false; } $controllerFileName = 'AppController.php'; $out = "<?php\n\n"; $out .= "namespace {$plugin}\\Controller;\n\n"; $out .= "use App\\Controller\\AppController as BaseController;\n\n"; $out .= "class AppController extends BaseController {\n\n"; $out .= "}\n"; $this->createFile($this->path . $plugin . DS . $classBase . DS . 'Controller' . DS . $controllerFileName, $out); $emptyFile = $this->path . 'empty'; $this->_deleteEmptyFile($emptyFile); $hasAutoloader = $this->_modifyAutoloader($plugin, $this->path); $this->_generateRoutes($plugin, $this->path); $this->_modifyBootstrap($plugin, $hasAutoloader); $this->_generatePhpunitXml($plugin, $this->path); $this->_generateTestBootstrap($plugin, $this->path); $this->hr(); $this->out(sprintf('<success>Created:</success> %s in %s', $plugin, $this->path . $plugin), 2); } return true; }