/** * Execute the command. * * @return void * * @since 1.0 */ public function execute() { $this->getApplication()->outputTitle('Clear Twig cache dir'); if (!$this->getApplication()->get('renderer.cache', false)) { $this->out('Twig caching is not enabled.'); return; } $cacheDir = JPATH_ROOT . '/' . $this->getApplication()->get('renderer.cache'); $this->logOut(sprintf('Cleaning the cache dir in "%s"', $cacheDir)); if (is_dir($cacheDir)) { Folder::delete($cacheDir); } $this->out()->out('The Twig cache directory has been cleared.'); }
/** * doExecute * * @return mixed|void */ public function doExecute() { // Flip replace array because we want to convert template. $replace = array_flip($this->replace); foreach ($replace as &$val) { $val = '{{' . $val . '}}'; } // Flip src and dest because we want to convert template. $src = $this->config['dir.src']; $dest = $this->config['dir.dest']; // Remove dir first Folder::delete($dest); $this->container->get('operator.convert')->copy($src, $dest, $replace); }
/** * doExecute * * @return mixed|void */ public function doExecute() { // Flip replace array because we want to convert template. $replace = array_flip($this->replace); foreach ($replace as &$val) { $val = '{{' . $val . '}}'; } // Flip src and dest because we want to convert template. $src = $this->config['dir.src']; $dest = $this->config['dir.dest']; if (!is_dir($src)) { throw new \RuntimeException(sprintf('Extension "%s" in %s not exists', $this->config['element'], $this->config['client'])); } // Remove dir first Folder::delete($dest); $this->container->get('operator.convert')->copy($src, $dest, $replace); }
/** * Method to get the list of files for the field options. * Specify the target directory with a directory attribute * Attributes allow an exclude mask and stripping of extensions from file name. * Default attribute may optionally be set to null (no file) or -1 (use a default). * * @return array The field option objects. * * @since 1.0 */ protected function getOptions() { $options = array(); // Initialize some field attributes. $filter = (string) $this->element['filter']; $exclude = (string) $this->element['exclude']; $stripExt = (string) $this->element['stripext']; $hideNone = (string) $this->element['hide_none']; $hideDefault = (string) $this->element['hide_default']; // Get the path in which to search for file options. $path = (string) $this->element['directory']; if (!is_dir($path)) { $path = JPATH_ROOT . '/' . $path; } // Prepend some default options based on field attributes. if (!$hideNone) { $options[] = HtmlSelect::option('-1', Text::alt('JOPTION_DO_NOT_USE', preg_replace('/[^a-zA-Z0-9_\\-]/', '_', $this->fieldname))); } if (!$hideDefault) { $options[] = HtmlSelect::option('', Text::alt('JOPTION_USE_DEFAULT', preg_replace('/[^a-zA-Z0-9_\\-]/', '_', $this->fieldname))); } // Get a list of files in the search path with the given filter. $files = Folder::files($path, $filter); // Build the options list from the list of files. if (is_array($files)) { foreach ($files as $file) { // Check to see if the file is in the exclude mask. if ($exclude) { if (preg_match(chr(1) . $exclude . chr(1), $file)) { continue; } } // If the extension is to be stripped, do it. if ($stripExt) { $file = File::stripExt($file); } $options[] = HtmlSelect::option($file, $file); } } // Merge any additional options in the XML definition. $options = array_merge(parent::getOptions(), $options); return $options; }
/** * Execute the command * * @return void * * @since 1.0 */ public function execute() { // Check if caching is enabled $twigCache = $this->app->get('template.cache', false); if ($twigCache === false) { $this->app->out('Twig caching is disabled.'); return; } // Display status $this->app->out('Resetting Twig Cache.'); // First remove the existing cache files if (is_dir(JPATH_ROOT . '/' . $twigCache)) { foreach (Folder::folders(JPATH_ROOT . '/' . $twigCache) as $folder) { Folder::delete(JPATH_ROOT . '/' . $twigCache . '/' . $folder); } } // Now get a list of all the templates $files = Folder::files(JPATH_TEMPLATES, '.twig', true, true); // Load each template now /** @var \Joomla\Renderer\TwigRenderer $twigRenderer */ $twigRenderer = $this->app->getContainer()->get('renderer'); $engine = $twigRenderer->getRenderer(); $errorFiles = []; foreach ($files as $file) { $template = str_replace(JPATH_TEMPLATES . '/', '', $file); try { $engine->loadTemplate($template); } catch (\Twig_Error $e) { $errorFiles[] = $file; } } if (count($errorFiles)) { $msg = 'The following Twig resources failed to cache: ' . implode(', ', $errorFiles); } else { $msg = 'The cached Twig resources were successfully created.'; } $this->app->out($msg); }
/** * Execute the application. * * @return void * * @since 1.0 */ protected function doExecute() { if ($this->input->get('h') || $this->input->get('help')) { $this->out(); $this->out('GetJoomlaCLI ' . self::VERSION); $this->out('--------------------------------------------------------'); $this->out('GetJoomlaCLI is a Joomla Framework simple Command Line Apllication.'); $this->out('With GetJoomlaCLI you can easily download the latest Joomla CMS into a folder.'); $this->out('called "testingsite".'); $this->out(); $this->out(' -h | --help Prints this usage information.'); $this->out(' -folder the folder name where to create the joomla site'); $this->out(' "testingsite" will be used if no name is provided'); $this->out('EXAMPLE USAGE:'); $this->out(' php -f getjoomlacli.php -h'); $this->out(' php -f getjoomlacli.php --folder=testingsite'); $this->out(); } else { $folder = JPATH_ROOT . '/' . $this->input->get('folder', 'testingsite'); if (is_dir($folder)) { $this->out('Removing old files in the folder...'); Folder::delete($folder); } Folder::create($folder); $this->out('Downloading Joomla...'); $repository = 'https://github.com/joomla/joomla-cms.git'; $branch = 'staging'; $command = "git clone -b {$branch} --single-branch --depth 1 {$repository} {$folder}"; $this->out($command); $output = array(); exec($command, $output, $returnValue); if ($returnValue) { $this->out('Sadly we were not able to download Joomla.'); } else { $this->out('Joomla Downloaded and ready for executing the tests.'); } } }
/** * Extract a ZIP compressed file to a given path * * @param string $archive Path to ZIP archive to extract * @param string $destination Path to extract archive into * @param array $options Extraction options [unused] * * @return boolean True if successful * * @throws RuntimeException * @since 11.1 */ public function extract($archive, $destination, array $options = array()) { $this->_data = null; $this->_metadata = null; $this->_data = file_get_contents($archive); if (!$this->_data) { if (class_exists('\\JError')) { return JError::raiseWarning(100, 'Unable to read archive'); } else { throw new RuntimeException('Unable to read archive'); } } $this->_getTarInfo($this->_data); for ($i = 0, $n = count($this->_metadata); $i < $n; $i++) { $type = strtolower($this->_metadata[$i]['type']); if ($type == 'file' || $type == 'unix file') { $buffer = $this->_metadata[$i]['data']; $path = Path::clean($destination . '/' . $this->_metadata[$i]['name']); // Make sure the destination folder exists if (!Folder::create(dirname($path))) { if (class_exists('\\JError')) { return JError::raiseWarning(100, 'Unable to create destination'); } else { throw new RuntimeException('Unable to create destination'); } } if (File::write($path, $buffer) === false) { if (class_exists('\\JError')) { return JError::raiseWarning(100, 'Unable to write entry'); } else { throw new RuntimeException('Unable to write entry'); } } } } return true; }
/** * Method to write the process id file out to disk. * * @return boolean * * @since 11.1 */ protected function writeProcessIdFile() { // Verify the process id is valid. if ($this->processId < 1) { Log::add('The process id is invalid.', Log::EMERGENCY); return false; } // Get the application process id file path. $file = $this->config->get('application_pid_file'); if (empty($file)) { Log::add('The process id file path is empty.', Log::ERROR); return false; } // Make sure that the folder where we are writing the process id file exists. $folder = dirname($file); if (!is_dir($folder) && !Folder::create($folder)) { Log::add('Unable to create directory: ' . $folder, Log::ERROR); return false; } // Write the process id file out to disk. if (!file_put_contents($file, $this->processId)) { Log::add('Unable to write proccess id file: ' . $file, Log::ERROR); return false; } // Make sure the permissions for the proccess id file are accurate. if (!chmod($file, 0644)) { Log::add('Unable to adjust permissions for the proccess id file: ' . $file, Log::ERROR); return false; } return true; }
/** * Moves an uploaded file to a destination folder * * @param string $src The name of the php (temporary) uploaded file * @param string $dest The path (including filename) to move the uploaded file to * @param boolean $use_streams True to use streams * * @return boolean True on success * * @since 1.0 * @throws FilesystemException */ public static function upload($src, $dest, $use_streams = false) { // Ensure that the path is valid and clean $dest = Path::clean($dest); // Create the destination directory if it does not exist $baseDir = dirname($dest); if (!file_exists($baseDir)) { Folder::create($baseDir); } if ($use_streams) { $stream = Stream::getStream(); if (!$stream->upload($src, $dest)) { throw new FilesystemException(__METHOD__ . ': ' . $stream->getError()); } return true; } else { if (is_writeable($baseDir) && move_uploaded_file($src, $dest)) { // Short circuit to prevent file permission errors if (Path::setPermissions($dest)) { return true; } else { throw new FilesystemException(__METHOD__ . ': Failed to change file permissions.'); } } else { throw new FilesystemException(__METHOD__ . ': Failed to move file.'); } return false; } }
/** * Tests the Folder::makeSafe method. * * @return void * * @since 1.0 * * @covers Joomla\Filesystem\Folder::makeSafe */ public function testMakeSafe() { $actual = Folder::makeSafe('test1/testdirectory'); $this->assertEquals('test1/testdirectory', $actual); }
/** * Extract an archive file to a directory. * * @param string $archivename The name of the archive file * @param string $extractdir Directory to unpack into * * @return boolean True for success * * @since 1.0 * @throws \InvalidArgumentException */ public function extract($archivename, $extractdir) { $ext = pathinfo($archivename, PATHINFO_EXTENSION); $path = pathinfo($archivename, PATHINFO_DIRNAME); $filename = pathinfo($archivename, PATHINFO_FILENAME); switch ($ext) { case 'zip': $result = $this->getAdapter('zip')->extract($archivename, $extractdir); break; case 'tar': $result = $this->getAdapter('tar')->extract($archivename, $extractdir); break; case 'tgz': case 'gz': case 'gzip': // This may just be an individual file (e.g. sql script) $tmpfname = $this->options['tmp_path'] . '/' . uniqid('gzip'); $gzresult = $this->getAdapter('gzip')->extract($archivename, $tmpfname); if ($gzresult instanceof \Exception) { @unlink($tmpfname); return false; } if ($ext === 'tgz' || stripos($filename, '.tar') !== false) { $result = $this->getAdapter('tar')->extract($tmpfname, $extractdir); } else { Folder::create($path); $result = File::copy($tmpfname, $extractdir, null, 0); } @unlink($tmpfname); break; case 'tbz2': case 'bz2': case 'bzip2': // This may just be an individual file (e.g. sql script) $tmpfname = $this->options['tmp_path'] . '/' . uniqid('bzip2'); $bzresult = $this->getAdapter('bzip2')->extract($archivename, $tmpfname); if ($bzresult instanceof \Exception) { @unlink($tmpfname); return false; } if ($ext === 'tbz2' || stripos($filename, '.tar') !== false) { $result = $this->getAdapter('tar')->extract($tmpfname, $extractdir); } else { Folder::create($path); $result = File::copy($tmpfname, $extractdir, null, 0); } @unlink($tmpfname); break; default: throw new \InvalidArgumentException(sprintf('Unknown archive type: %s', $ext)); } if (!$result || $result instanceof \Exception) { return false; } return true; }
public static function getLanguages() { jimport('joomla.filesystem.folder'); $dirs = Folder::folders(JPATH_SITE . "/language"); $ret = array(); if (count($dirs) > 0) { foreach ($dirs as $lang) { $ret[$lang] = $lang; } } return $ret; }
/** * Extract a ZIP compressed file to a given path using native php api calls for speed * * @param string $archive Path to ZIP archive to extract * @param string $destination Path to extract archive into * * @return boolean True on success * * @since 11.1 * @throws RuntimeException */ protected function extractNative($archive, $destination) { $zip = zip_open($archive); if (is_resource($zip)) { // Make sure the destination folder exists if (!Folder::create($destination)) { if (class_exists('\\JError')) { return JError::raiseWarning(100, 'Unable to create destination'); } else { throw new RuntimeException('Unable to create destination'); } } // Read files in the archive while ($file = @zip_read($zip)) { if (zip_entry_open($zip, $file, "r")) { if (substr(zip_entry_name($file), strlen(zip_entry_name($file)) - 1) != "/") { $buffer = zip_entry_read($file, zip_entry_filesize($file)); if (File::write($destination . '/' . zip_entry_name($file), $buffer) === false) { if (class_exists('\\JError')) { return JError::raiseWarning(100, 'Unable to write entry'); } else { throw new RuntimeException('Unable to write entry'); } } zip_entry_close($file); } } else { if (class_exists('\\JError')) { return JError::raiseWarning(100, 'Unable to read entry'); } else { throw new RuntimeException('Unable to read entry'); } } } @zip_close($zip); } else { if (class_exists('\\JError')) { return JError::raiseWarning(100, 'Unable to open archive'); } else { throw new RuntimeException('Unable to open archive'); } } return true; }
/** * Extract a ZIP compressed file to a given path * * @param string $archive Path to ZIP archive to extract * @param string $destination Path to extract archive into * * @return boolean True if successful * * @since 1.0 * @throws \RuntimeException */ public function extract($archive, $destination) { $this->data = null; $this->metadata = null; $this->data = file_get_contents($archive); if (!$this->data) { throw new \RuntimeException('Unable to read archive'); } $this->getTarInfo($this->data); for ($i = 0, $n = count($this->metadata); $i < $n; $i++) { $type = strtolower($this->metadata[$i]['type']); if ($type == 'file' || $type == 'unix file') { $buffer = $this->metadata[$i]['data']; $path = Path::clean($destination . '/' . $this->metadata[$i]['name']); // Make sure the destination folder exists if (!Folder::create(dirname($path))) { throw new \RuntimeException('Unable to create destination'); } if (File::write($path, $buffer) === false) { throw new \RuntimeException('Unable to write entry'); } } } return true; }
/** * Moves an uploaded file to a destination folder * * @param string $src The name of the php (temporary) uploaded file * @param string $dest The path (including filename) to move the uploaded file to * @param boolean $use_streams True to use streams * * @return boolean True on success * * @since 11.1 */ public static function upload($src, $dest, $use_streams = false) { // Ensure that the path is valid and clean $dest = Path::clean($dest); // Create the destination directory if it does not exist $baseDir = dirname($dest); if (!file_exists($baseDir)) { Folder::create($baseDir); } if ($use_streams) { $stream = Factory::getStream(); if (!$stream->upload($src, $dest)) { Log::add(Text::sprintf('JLIB_FILESYSTEM_ERROR_UPLOAD', $stream->getError()), Log::WARNING, 'jerror'); return false; } return true; } else { $FTPOptions = ClientHelper::getCredentials('ftp'); $ret = false; if ($FTPOptions['enabled'] == 1) { // Connect the FTP client $ftp = ClientFtp::getInstance($FTPOptions['host'], $FTPOptions['port'], array(), $FTPOptions['user'], $FTPOptions['pass']); // Translate path for the FTP account $dest = Path::clean(str_replace(JPATH_ROOT, $FTPOptions['root'], $dest), '/'); // Copy the file to the destination directory if (is_uploaded_file($src) && $ftp->store($src, $dest)) { unlink($src); $ret = true; } else { Log::add(Text::_('JLIB_FILESYSTEM_ERROR_WARNFS_ERR02'), Log::WARNING, 'jerror'); } } else { if (is_writeable($baseDir) && move_uploaded_file($src, $dest)) { // Short circuit to prevent file permission errors if (Path::setPermissions($dest)) { $ret = true; } else { Log::add(Text::_('JLIB_FILESYSTEM_ERROR_WARNFS_ERR01'), Log::WARNING, 'jerror'); } } else { Log::add(Text::_('JLIB_FILESYSTEM_ERROR_WARNFS_ERR02'), Log::WARNING, 'jerror'); } } return $ret; } }
/** * Extract an archive file to a directory. * * @param string $archivename The name of the archive file * @param string $extractdir Directory to unpack into * * @return boolean True for success * * @since 11.1 * @throws InvalidArgumentException */ public static function extract($archivename, $extractdir) { $untar = false; $result = false; $ext = File::getExt(strtolower($archivename)); // Check if a tar is embedded...gzip/bzip2 can just be plain files! if (File::getExt(File::stripExt(strtolower($archivename))) == 'tar') { $untar = true; } switch ($ext) { case 'zip': $adapter = self::getAdapter('zip'); if ($adapter) { $result = $adapter->extract($archivename, $extractdir); } break; case 'tar': $adapter = self::getAdapter('tar'); if ($adapter) { $result = $adapter->extract($archivename, $extractdir); } break; case 'tgz': // This format is a tarball gzip'd $untar = true; case 'gz': case 'gzip': // This may just be an individual file (e.g. sql script) $adapter = self::getAdapter('gzip'); if ($adapter) { $config = Factory::getConfig(); $tmpfname = $config->get('tmp_path') . '/' . uniqid('gzip'); $gzresult = $adapter->extract($archivename, $tmpfname); if ($gzresult instanceof Exception) { @unlink($tmpfname); return false; } if ($untar) { // Try to untar the file $tadapter = self::getAdapter('tar'); if ($tadapter) { $result = $tadapter->extract($tmpfname, $extractdir); } } else { $path = Path::clean($extractdir); Folder::create($path); $result = File::copy($tmpfname, $path . '/' . File::stripExt(basename(strtolower($archivename))), null, 1); } @unlink($tmpfname); } break; case 'tbz2': // This format is a tarball bzip2'd $untar = true; case 'bz2': case 'bzip2': // This may just be an individual file (e.g. sql script) $adapter = self::getAdapter('bzip2'); if ($adapter) { $config = Factory::getConfig(); $tmpfname = $config->get('tmp_path') . '/' . uniqid('bzip2'); $bzresult = $adapter->extract($archivename, $tmpfname); if ($bzresult instanceof Exception) { @unlink($tmpfname); return false; } if ($untar) { // Try to untar the file $tadapter = self::getAdapter('tar'); if ($tadapter) { $result = $tadapter->extract($tmpfname, $extractdir); } } else { $path = Path::clean($extractdir); Folder::create($path); $result = File::copy($tmpfname, $path . '/' . File::stripExt(basename(strtolower($archivename))), null, 1); } @unlink($tmpfname); } break; default: throw new InvalidArgumentException('Unknown Archive Type'); } if (!$result || $result instanceof Exception) { return false; } return true; }
/** * Test write method * * @return void * * @covers Joomla\Filesystem\File::write * @since 1.0 */ public function testWrite() { $name = 'tempFile'; $path = __DIR__; $data = 'Lorem ipsum dolor sit amet'; // Create a file on pre existing path. $this->assertThat(File::write($path . '/' . $name, $data), $this->isTrue(), 'Line:' . __LINE__ . ' File should be written successfully.'); // Create a file on pre existing path by using streams. $this->assertThat(File::write($path . '/' . $name, $data, true), $this->isTrue(), 'Line:' . __LINE__ . ' File should be written successfully.'); // Create a file on non-existing path. $this->assertThat(File::write($path . '/TempFolder/' . $name, $data), $this->isTrue(), 'Line:' . __LINE__ . ' File should be written successfully.'); // Removes file and folder. File::delete($path . '/' . $name); Folder::delete($path . '/TempFolder'); }
/** * Tears down the fixture, for example, closes a network connection. * This method is called after a test is executed. * * @return void */ protected function tearDown() { Folder::delete(JPATH_ROOT . '/language'); }
/** * Method to initialise the log file. This will create the folder path to the file if it doesn't already * exist and also get a new file header if the file doesn't already exist. If the file already exists it * will simply open it for writing. * * @return void * * @since 11.1 */ protected function initFile() { // If the file doesn't already exist we need to create it and generate the file header. if (!is_file($this->path)) { // Make sure the folder exists in which to create the log file. Folder::create(dirname($this->path)); // Build the log file header. $head = $this->generateFileHeader(); } else { $head = false; } // Open the file for writing (append mode). if (!($this->file = fopen($this->path, 'a'))) { throw new RuntimeException('Cannot open file for writing log'); } if ($head) { if (!fwrite($this->file, $head)) { throw new RuntimeException('Cannot fput file for log'); } } }
/** * Clean cache for a group given a mode. * * @param string $group The cache data group. * @param string $mode The mode for cleaning cache [group|notgroup]. * group mode : cleans all cache in the group * notgroup mode : cleans all cache not in the group * * @return boolean True on success, false otherwise. * * @since 11.1 */ public function clean($group, $mode = null) { if (trim($group) == '') { $clmode = 'notgroup'; } if ($mode == null) { $clmode = 'group'; } switch ($mode) { case 'notgroup': $clmode = 'notingroup'; $success = self::$CacheLiteInstance->clean($group, $clmode); break; case 'group': if (is_dir($this->_root . '/' . $group)) { $clmode = $group; self::$CacheLiteInstance->setOption('cacheDir', $this->_root . '/' . $group . '/'); $success = self::$CacheLiteInstance->clean($group, $clmode); Folder::delete($this->_root . '/' . $group); } else { $success = true; } break; default: if (is_dir($this->_root . '/' . $group)) { $clmode = $group; self::$CacheLiteInstance->setOption('cacheDir', $this->_root . '/' . $group . '/'); $success = self::$CacheLiteInstance->clean($group, $clmode); } else { $success = true; } break; } if ($success == true) { return $success; } else { return false; } }