/** * Constructor. * * @param Horde_Vcs_Base $rep A repository object. * @param string $dn Path to the directory. * @param array $opts Any additional options: * * @throws Horde_Vcs_Exception */ public function __construct(Horde_Vcs_Base $rep, $dn, $opts = array()) { parent::__construct($rep, $dn, $opts); $cmd = $rep->getCommand() . ' ls ' . escapeshellarg($rep->sourceroot . $this->_dirName); $dir = proc_open($cmd, array(1 => array('pipe', 'w'), 2 => array('pipe', 'w')), $pipes); if (!$dir) { throw new Horde_Vcs_Exception('Failed to execute svn ls: ' . $cmd); } if ($error = stream_get_contents($pipes[2])) { proc_close($dir); throw new Horde_Vcs_Exception($error); } /* Create two arrays - one of all the files, and the other of all the * dirs. */ $errors = array(); while (!feof($pipes[1])) { $line = chop(fgets($pipes[1], 1024)); if (!strlen($line)) { continue; } if (substr($line, 0, 4) == 'svn:') { $errors[] = $line; } elseif (substr($line, -1) == '/') { $this->_dirs[] = substr($line, 0, -1); } else { $this->_files[] = $rep->getFile($this->_dirName . '/' . $line); } } proc_close($dir); }
/** * Escapes a string to be used as a shell argument. * * @param string $argument The argument that will be escaped * * @return string The escaped argument */ public static function escapeArgument($argument) { //Fix for PHP bug #43784 escapeshellarg removes % from given string //Fix for PHP bug #49446 escapeshellarg doesn't work on Windows //@see https://bugs.php.net/bug.php?id=43784 //@see https://bugs.php.net/bug.php?id=49446 if ('\\' === DIRECTORY_SEPARATOR) { if ('' === $argument) { return escapeshellarg($argument); } $escapedArgument = ''; $quote = false; foreach (preg_split('/(")/', $argument, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE) as $part) { if ('"' === $part) { $escapedArgument .= '\\"'; } elseif (self::isSurroundedBy($part, '%')) { // Avoid environment variable expansion $escapedArgument .= '^%"' . substr($part, 1, -1) . '"^%'; } else { // escape trailing backslash if ('\\' === substr($part, -1)) { $part .= '\\'; } $quote = true; $escapedArgument .= $part; } } if ($quote) { $escapedArgument = '"' . $escapedArgument . '"'; } return $escapedArgument; } return escapeshellarg($argument); }
public function db($command = '', $args = '') { if (count($command) == 1 && reset($command) == 'help') { return $this->db_help(); } $defaults = array('host' => defined('IMPORT_DB_HOST') ? IMPORT_DB_HOST : DB_HOST, 'user' => defined('IMPORT_DB_USER') ? IMPORT_DB_USER : DB_USER, 'password' => defined('IMPORT_DB_PASSWORD') ? IMPORT_DB_PASSWORD : '', 'name' => defined('IMPORT_DB_NAME') ? IMPORT_DB_NAME : '', 'port' => '3306', 'ssh_host' => defined('IMPORT_DB_SSH_HOST') ? IMPORT_DB_SSH_HOST : '', 'ssh_user' => defined('IMPORT_DB_SSH_USER') ? IMPORT_DB_SSH_USER : '', 'table' => ''); $args = wp_parse_args($args, $defaults); $start_time = time(); if ($args['ssh_host']) { shell_exec(sprintf("ssh -f -L 3308:%s:%s %s@%s sleep 600 >> logfile", $args['host'], $args['port'], $args['ssh_user'], $args['ssh_host'])); $args['host'] = '127.0.0.1'; $args['port'] = '3308'; } WP_CLI::line('Importing database from ' . $args['host'] . '...' . ($args['ssh_host'] ? ' via ssh tunnel: ' . $args['ssh_host'] : '')); $password = $args['password'] ? '--password='******'password']) : ''; // TODO pipe through sed or interconnectIT's search replace script if (defined('IMPORT_DB_REMOTE_ABSPATH')) { $sed = " | sed s," . trailingslashit(IMPORT_DB_REMOTE_ABSPATH) . "," . ABSPATH . ",g"; } else { $sed = ''; } if ($args['site']) { $args['table'] = "wp_{$args['site']}_commentmeta wp_{$args['site']}_comments wp_{$args['site']}_links wp_{$args['site']}_options wp_{$args['site']}_postmeta wp_{$args['site']}_posts wp_{$args['site']}_term_relationships wp_{$args['site']}_term_taxonomy wp_{$args['site']}_terms"; } $exec = sprintf('mysqldump --verbose --host=%s --user=%s %s -P %s %s %s %s | mysql --host=%s --user=%s --password=%s %s', $args['host'], $args['user'], $password, $args['port'], $args['name'], $args['table'], $sed, DB_HOST, DB_USER, escapeshellarg(DB_PASSWORD), DB_NAME); WP_CLI::line('Running: ' . $exec); WP_CLI::launch($exec); WP_CLI::success(sprintf('Finished. Took %d seconds', time() - $start_time)); wp_cache_flush(); }
function do_update_plugin($dir, $domain) { $old = getcwd(); chdir($dir); if (!file_exists('locale')) { mkdir('locale'); } $files = get_plugin_sources("."); $cmd = <<<END xgettext \\ --from-code=UTF-8 \\ --default-domain={$domain} \\ --output=locale/{$domain}.pot \\ --language=PHP \\ --add-comments=TRANS \\ --keyword='' \\ --keyword="_m:1,1t" \\ --keyword="_m:1c,2,2t" \\ --keyword="_m:1,2,3t" \\ --keyword="_m:1c,2,3,4t" \\ END; foreach ($files as $file) { $cmd .= ' ' . escapeshellarg($file); } passthru($cmd); chdir($old); }
public static function escapeArgument($argument) { if ('\\' === DIRECTORY_SEPARATOR) { if ('' === $argument) { return escapeshellarg($argument); } $escapedArgument = ''; $quote = false; foreach (preg_split('/(")/i', $argument, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE) as $part) { if ('"' === $part) { $escapedArgument .= '\\"'; } elseif (self::isSurroundedBy($part, '%')) { $escapedArgument .= '^%"' . substr($part, 1, -1) . '"^%'; } else { if ('\\' === substr($part, -1)) { $part .= '\\'; } $quote = true; $escapedArgument .= $part; } } if ($quote) { $escapedArgument = '"' . $escapedArgument . '"'; } return $escapedArgument; } return escapeshellarg($argument); }
/** * * @param string $message SMS message * @return string Parsed command * @throws ConfigurationException */ private function prepareCommand($message) { $tokens = []; $params = array_merge($this->params, ['message' => escapeshellarg($message)]); foreach ($params as $name => $value) { $token = '#' . strtoupper($name) . '#'; if (is_scalar($value)) { $tokens[$token] = $value; } } $command = str_replace(array_keys($tokens), array_values($tokens), $this->command); try { $useSsh = (bool) $this->getParam('use_ssh'); } catch (ConfigurationException $exp) { $useSsh = false; } if ($useSsh) { $sshHost = (string) $this->getParam('ssh_host'); $sshLogin = (string) $this->getParam('ssh_login'); if (empty($sshHost) || empty($sshLogin)) { throw new ConfigurationException(__CLASS__ . ' is not configured properly. If SSH is enabled then parameters "ssh_host" and "ssh_login" must be set.'); } $tokens['#COMMAND#'] = $command; $command = str_replace(array_keys($tokens), array_values($tokens), $this->sshCommand); } return $command; }
public function testAcceptsValidStringInput() { $msg = escapeshellarg(file_get_contents("{$this->filesDir}valid.txt")); $cmd = "{$this->validateScript} {$msg}"; $result = $this->runCmd($cmd, $output); $this->assertTrue($result, $output); }
public function compress($source, $type) { $cmd = sprintf('java -jar %s --type %s --charset UTF-8 --line-break 1000', escapeshellarg($this->yuiPath), $type); $process = proc_open($cmd, array(0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("pipe", "w")), $pipes); fwrite($pipes[0], $source); fclose($pipes[0]); $output = array("stdout" => "", "stderr" => ""); $readSockets = array("stdout" => $pipes[1], "stderr" => $pipes[2]); $empty = array(); while (false !== stream_select($readSockets, $empty, $empty, 1)) { foreach ($readSockets as $stream) { $output[$stream == $pipes[1] ? "stdout" : "stderr"] .= stream_get_contents($stream); } $readSockets = array("stdout" => $pipes[1], "stderr" => $pipes[2]); $eof = true; foreach ($readSockets as $stream) { $eof &= feof($stream); } if ($eof) { break; } } $compressed = $output['stdout']; $errors = $output['stderr']; $this->errors = "" !== $errors; if ($this->errors) { $compressed = ""; $this->errors = sprintf("alert('compression errors, check your source and console for details'); console.error(%s); ", json_encode($errors)); } proc_close($process); return $compressed; }
/** * Call a drush command. */ public function call($command, $options = array(), $args = array()) { // Reset previous command. $this->result = null; $cmd = array(); $cmd[] = 'drush'; $cmd[] = $this->alias; $cmd[] = $command; $cmd[] = '--backend --quiet'; foreach ($options as $option) { $cmd[] = escapeshellarg($option); } foreach ($args as $arg) { $cmd[] = escapeshellarg($arg); } $cmd = implode(' ', $cmd); $output = ''; $retval = $this->exec($cmd, $output); if ($retval > 0) { throw new DrushException('Error running ' . $cmd); } else { $this->result = $this->parseDrushOutput($output); } return $this; }
/** * @see sfTask */ protected function execute($arguments = array(), $options = array()) { if (!class_exists($arguments['class'])) { throw new InvalidArgumentException(sprintf('The class "%s" does not exist.', $arguments['class'])); } // base lib and test directories $r = new ReflectionClass($arguments['class']); list($libDir, $testDir) = $this->getDirectories($r->getFilename()); $path = str_replace($libDir, '', dirname($r->getFilename())); $test = $testDir . '/unit' . $path . '/' . $r->getName() . 'Test.php'; // use either the test directory or project's bootstrap if (!file_exists($bootstrap = $testDir . '/bootstrap/unit.php')) { $bootstrap = sfConfig::get('sf_test_dir') . '/bootstrap/unit.php'; } if (file_exists($test) && $options['force']) { $this->getFilesystem()->remove($test); } if (file_exists($test)) { $this->logSection('task', sprintf('A test script for the class "%s" already exists.', $r->getName()), null, 'ERROR'); } else { $this->getFilesystem()->copy(dirname(__FILE__) . '/skeleton/test/UnitTest.php', $test); $this->getFilesystem()->replaceTokens($test, '##', '##', array('CLASS' => $r->getName(), 'BOOTSTRAP' => $this->getBootstrapPathPhp($bootstrap, $test), 'DATABASE' => $this->isDatabaseClass($r) ? "\n\$databaseManager = new sfDatabaseManager(\$configuration);\n" : '')); } if (isset($options['editor-cmd'])) { $this->getFilesystem()->execute($options['editor-cmd'] . ' ' . escapeshellarg($test)); } }
/** * Check if the password is correct without logging in the user * * @param string $uid The username * @param string $password The password * * @return true/false */ public function checkPassword($uid, $password) { $uidEscaped = escapeshellarg($uid); $password = escapeshellarg($password); $result = array(); $command = self::SMBCLIENT . ' //' . $this->host . '/dummy -U' . $uidEscaped . '%' . $password; $lastline = exec($command, $output, $retval); if ($retval === 127) { OCP\Util::writeLog('user_external', 'ERROR: smbclient executable missing', OCP\Util::ERROR); return false; } else { if (strpos($lastline, self::LOGINERROR) !== false) { //normal login error return false; } else { if (strpos($lastline, 'NT_STATUS_BAD_NETWORK_NAME') !== false) { //login on minor error goto login; } else { if ($retval != 0) { //some other error OCP\Util::writeLog('user_external', 'ERROR: smbclient error: ' . trim($lastline), OCP\Util::ERROR); return false; } else { login: $this->storeUser($uid); return $uid; } } } } }
public function createOwnVhostStarter() { if (Settings::Get('phpfpm.enabled') == '1' && Settings::Get('phpfpm.enabled_ownvhost') == '1') { $mypath = makeCorrectDir(dirname(dirname(dirname(__FILE__)))); // /var/www/froxlor, needed for chown $user = Settings::Get('phpfpm.vhost_httpuser'); $group = Settings::Get('phpfpm.vhost_httpgroup'); $domain = array('id' => 'none', 'domain' => Settings::Get('system.hostname'), 'adminid' => 1, 'mod_fcgid_starter' => -1, 'mod_fcgid_maxrequests' => -1, 'guid' => $user, 'openbasedir' => 0, 'email' => Settings::Get('panel.adminmail'), 'loginname' => 'froxlor.panel', 'documentroot' => $mypath); // all the files and folders have to belong to the local user // now because we also use fcgid for our own vhost safe_exec('chown -R ' . $user . ':' . $group . ' ' . escapeshellarg($mypath)); // get php.ini for our own vhost $php = new phpinterface($domain); // get php-config if (Settings::Get('phpfpm.enabled') == '1') { // fpm $phpconfig = $php->getPhpConfig(Settings::Get('phpfpm.vhost_defaultini')); } else { // fcgid $phpconfig = $php->getPhpConfig(Settings::Get('system.mod_fcgid_defaultini_ownvhost')); } // create starter-file | config-file $php->getInterface()->createConfig($phpconfig); // create php.ini (fpm does nothing here, as it // defines ini-settings in its pool config) $php->getInterface()->createIniFile($phpconfig); } }
private function mimeFromShell() { if (!strstr(strtolower(PHP_OS), 'win')) { if (($this->_mime = exec('file -bi ' . escapeshellarg($this->_path))) && strlen($this->_mime)) { /* * it's a stupid exception for MS docs files * The linux command "file -bi" returns then this: * application/msword application/msword * which sucks totally :( */ if (strstr($this->_mime, ' ') && !strstr($this->_mime, ';')) { $this->_mime = explode(' ', $this->_mime); if (trim($this->_mime[0]) == $this->_mime[1]) { $this->_mime = $this->_mime[0]; } } $this->parseMime(); return true; } else { return false; } } else { return false; } }
protected function dump_base(base $base, InputInterface $input, OutputInterface $output) { $date_obj = new DateTime(); $filename = sprintf('%s%s_%s.sql', p4string::addEndSlash($input->getArgument('directory')), $base->get_dbname(), $date_obj->format('Y_m_d_H_i_s')); $command = sprintf('mysqldump %s %s %s %s %s %s --default-character-set=utf8', '--host=' . escapeshellarg($base->get_host()), '--port=' . escapeshellarg($base->get_port()), '--user='******'--password='******'--databases', escapeshellarg($base->get_dbname())); if ($input->getOption('gzip')) { $filename .= '.gz'; $command .= ' | gzip -9'; } elseif ($input->getOption('bzip')) { $filename .= '.bz2'; $command .= ' | bzip2 -9'; } $output->write(sprintf('Generating <info>%s</info> ... ', $filename)); $command .= ' > ' . escapeshellarg($filename); $process = new Process($command); $process->setTimeout((int) $input->getOption('timeout')); $process->run(); if (!$process->isSuccessful()) { $output->writeln('<error>Failed</error>'); return 1; } if (file_exists($filename) && filesize($filename) > 0) { $output->writeln('OK'); return 0; } else { $output->writeln('<error>Failed</error>'); return 1; } }
/** * The main entry point * * @throws BuildException */ function main() { $this->setup('info'); exec('git log -n 1 --no-decorate --pretty=format:"%h" ' . escapeshellarg(realpath($this->workingCopy)), $out); $version = $out[0]; $this->project->setProperty($this->getPropertyName(), $version); }
/** * Export the locale files to the browser as a tarball. * Requires tar for operation (configured in config.inc.php). */ function export($locale) { // Construct the tar command $tarBinary = Config::getVar('cli', 'tar'); if (empty($tarBinary) || !file_exists($tarBinary)) { // We can use fatalError() here as we already have a user // friendly way of dealing with the missing tar on the // index page. fatalError('The tar binary must be configured in config.inc.php\'s cli section to use the export function of this plugin!'); } $command = $tarBinary . ' cz'; $localeFilesList = TranslatorAction::getLocaleFiles($locale); $localeFilesList = array_merge($localeFilesList, TranslatorAction::getMiscLocaleFiles($locale)); $emailTemplateDao =& DAORegistry::getDAO('EmailTemplateDAO'); $localeFilesList[] = $emailTemplateDao->getMainEmailTemplateDataFilename($locale); foreach (array_values(TranslatorAction::getEmailFileMap($locale)) as $emailFile) { } // Include locale files (main file and plugin files) foreach ($localeFilesList as $file) { if (file_exists($file)) { $command .= ' ' . escapeshellarg($file); } } header('Content-Type: application/x-gtar'); header("Content-Disposition: attachment; filename=\"{$locale}.tar.gz\""); header('Cache-Control: private'); // Workarounds for IE weirdness passthru($command); }
function __construct($content) { if(extension_loaded('tidy')) { // using the tiny php extension $tidy = new Tidy(); $tidy->parseString( $content, array( 'output-xhtml' => true, 'numeric-entities' => true, ), 'utf8' ); $tidy->cleanRepair(); $tidy = str_replace('xmlns="http://www.w3.org/1999/xhtml"','',$tidy); $tidy = str_replace(' ','',$tidy); } elseif(`which tidy`) { // using tiny through cli $CLI_content = escapeshellarg($content); $tidy = `echo $CLI_content | tidy -n -q -utf8 -asxhtml 2> /dev/null`; $tidy = str_replace('xmlns="http://www.w3.org/1999/xhtml"','',$tidy); $tidy = str_replace(' ','',$tidy); } else { // no tidy library found, hence no sanitizing $tidy = $content; } $this->simpleXML = new SimpleXMLElement($tidy); }
/** * {@inheritDoc} */ public function getThumbnail($path, $maxX, $maxY, $scalingup, $fileview) { $this->initCmd(); if (is_null($this->cmd)) { return false; } $absPath = $fileview->toTmpFile($path); $tmpDir = \OC::$server->getTempManager()->getTempBaseDir(); $defaultParameters = ' -env:UserInstallation=file://' . escapeshellarg($tmpDir . '/owncloud-' . \OC_Util::getInstanceId() . '/') . ' --headless --nologo --nofirststartwizard --invisible --norestore --convert-to pdf --outdir '; $clParameters = \OCP\Config::getSystemValue('preview_office_cl_parameters', $defaultParameters); $exec = $this->cmd . $clParameters . escapeshellarg($tmpDir) . ' ' . escapeshellarg($absPath); shell_exec($exec); //create imagick object from pdf $pdfPreview = null; try { list($dirname, , , $filename) = array_values(pathinfo($absPath)); $pdfPreview = $dirname . '/' . $filename . '.pdf'; $pdf = new \imagick($pdfPreview . '[0]'); $pdf->setImageFormat('jpg'); } catch (\Exception $e) { unlink($absPath); unlink($pdfPreview); \OCP\Util::writeLog('core', $e->getmessage(), \OCP\Util::ERROR); return false; } $image = new \OC_Image(); $image->loadFromData($pdf); unlink($absPath); unlink($pdfPreview); if ($image->valid()) { $image->scaleDownToFit($maxX, $maxY); return $image; } return false; }
/** * @test */ public function subProcessCommandEvaluatesSubRequestIniEntriesCorrectly() { $settings = array('core' => array('context' => 'Testing', 'phpBinaryPathAndFilename' => '/must/be/set/according/to/schema', 'subRequestIniEntries' => array('someSetting' => 'withValue', 'someFlagSettingWithoutValue' => ''))); $actual = $this->scriptsMock->_call('buildSubprocessCommand', 'flow:foo:identifier', $settings); $this->assertContains(sprintf(' -d %s=%s ', escapeshellarg('someSetting'), escapeshellarg('withValue')), $actual); $this->assertContains(sprintf(' -d %s ', escapeshellarg('someFlagSettingWithoutValue')), $actual); }
function getimages($dir) { global $imagetypes; // array to hold return values; $retval = array(); // add trailing slashes if missing; if (substr($dir, -1) != "/") { $dir .= "/images/"; } // Full server path to dir $fulldir = "{$_SERVER['DOCUMENT_ROOT']}/{$dir}"; // $fulldir ="localhost/novademo-localhost/images/"; $d = @dir($fulldir) or die("getimages: Failed opening directory {$_SERVER['DOCUMENT_ROOT']}/{$dir} for reading"); while (false != ($entry = $d->read())) { // skip hidden files if ($entry[0] == ".") { continue; } // check for image files $f = escapeshellarg("{$fulldir}" . "{$entry}"); $mimetype = trim(`file -bi {$f}`); foreach ($imagetypes as $valid_type) { if (preg_match("@^{$valid_type}@", $mimetype)) { $retval[] = array('file' => "/{$dir}" . "{$entry}", 'size' => getimagesize("{$fulldir}" . "{$entry}")); break; } } } $d->close(); return $retval; }
/** * @Given I have started describing the :class class */ public function iHaveStartedDescribingTheClass($class) { $command = sprintf('%s %s %s', $this->buildPhpSpecCmd(), 'describe', escapeshellarg($class)); $process = new Process($command); $process->run(); expect($process->getExitCode())->toBe(0); }
/** * Execute this task * * @param \TYPO3\Surf\Domain\Model\Node $node * @param \TYPO3\Surf\Domain\Model\Application $application * @param \TYPO3\Surf\Domain\Model\Deployment $deployment * @param array $options Supported options: "scriptBasePath" and "scriptIdentifier" * @return void * @throws \TYPO3\Surf\Exception\InvalidConfigurationException * @throws \TYPO3\Surf\Exception\TaskExecutionException */ public function execute(Node $node, Application $application, Deployment $deployment, array $options = array()) { $workspacePath = $deployment->getWorkspacePath($application); $scriptBasePath = isset($options['scriptBasePath']) ? $options['scriptBasePath'] : Files::concatenatePaths(array($workspacePath, 'Web')); if (!isset($options['scriptIdentifier'])) { // Generate random identifier $factory = new \RandomLib\Factory(); $generator = $factory->getMediumStrengthGenerator(); $scriptIdentifier = $generator->generateString(32, \RandomLib\Generator::CHAR_ALNUM); // Store the script identifier as an application option $application->setOption('TYPO3\\Surf\\Task\\Php\\WebOpcacheResetExecuteTask[scriptIdentifier]', $scriptIdentifier); } else { $scriptIdentifier = $options['scriptIdentifier']; } $localhost = new Node('localhost'); $localhost->setHostname('localhost'); $commands = array('cd ' . escapeshellarg($scriptBasePath), 'rm -f surf-opcache-reset-*'); $this->shell->executeOrSimulate($commands, $localhost, $deployment); if (!$deployment->isDryRun()) { $scriptFilename = $scriptBasePath . '/surf-opcache-reset-' . $scriptIdentifier . '.php'; $result = file_put_contents($scriptFilename, '<?php if (function_exists("opcache_reset")) { opcache_reset(); } @unlink(__FILE__); echo "success"; '); if ($result === false) { throw new \TYPO3\Surf\Exception\TaskExecutionException('Could not write file "' . $scriptFilename . '"', 1421932414); } } }
public function testRender() { $testArgument = 'argument'; $testArgument2 = 'argument2'; $commandRenderer = new CommandRenderer(); $this->assertEquals("php -r " . escapeshellarg($testArgument) . " 2>&1 | grep " . escapeshellarg($testArgument2) . " 2>&1", $commandRenderer->render('php -r %s | grep %s', [$testArgument, $testArgument2])); }
/** * Search for GraphicsMagick executables in given paths. * * @param array $searchPaths List of paths to search for * @return bool TRUE if graphics magick was found in path */ protected function findImageMagick6InPaths(array $searchPaths) { $result = FALSE; foreach ($searchPaths as $path) { if (TYPO3_OS === 'WIN') { $executable = 'identify.exe'; } else { $executable = 'identify'; } if (@is_file($path . $executable)) { $command = escapeshellarg($path . $executable) . ' -version'; $executingResult = FALSE; \TYPO3\CMS\Core\Utility\CommandUtility::exec($command, $executingResult); // First line of exec command should contain string GraphicsMagick $firstResultLine = array_shift($executingResult); // Example: "Version: ImageMagick 6.6.0-4 2012-05-02 Q16 http://www.imagemagick.org" if (strpos($firstResultLine, 'ImageMagick') !== FALSE) { list(, $version) = explode('ImageMagick', $firstResultLine); // Example: "6.6.0-4" list($version) = explode(' ', trim($version)); if (version_compare($version, '6.0.0') >= 0) { $this->foundPath = $path; $result = TRUE; break; } } } } return $result; }
protected function execute(InputInterface $input, OutputInterface $output) { $manifest = $input->getOption('manifest') ?: 'https://platform.sh/cli/manifest.json'; $currentVersion = $input->getOption('current-version') ?: $this->getApplication()->getVersion(); if (extension_loaded('Phar') && !($localPhar = \Phar::running(false))) { $this->stdErr->writeln('This instance of the CLI was not installed as a Phar archive.'); if (file_exists(CLI_ROOT . '/../../autoload.php')) { $this->stdErr->writeln('Update using: <info>composer global update</info>'); } return 1; } $manager = new Manager(Manifest::loadFile($manifest)); if (isset($localPhar)) { $manager->setRunningFile($localPhar); } $onlyMinor = !$input->getOption('major'); $updated = $manager->update($currentVersion, $onlyMinor); if ($updated) { $this->stdErr->writeln("Successfully updated"); $localPhar = $manager->getRunningFile(); passthru('php ' . escapeshellarg($localPhar) . ' --version'); } else { $this->stdErr->writeln("No updates found. The Platform.sh CLI is up-to-date."); } return 0; }
private static function create_prompt_cmd($prompt, $history_path) { $prompt = escapeshellarg($prompt); $history_path = escapeshellarg($history_path); $cmd = "set -f; " . "history -r {$history_path}; " . "LINE=\"\"; " . "read -re -p {$prompt} LINE; " . "[ \$? -eq 0 ] || exit; " . "history -s \"\$LINE\"; " . "history -w {$history_path}; " . "echo \$LINE; "; return '/bin/bash -c ' . escapeshellarg($cmd); }
/** * @param $file_name * @return array * @throws ApplicationException */ public static function generate($file_name) { set_time_limit(0); $temp_file = TempFileProvider::generate("peaks", ".raw"); $command = sprintf("%s -v quiet -i %s -ac 1 -f u8 -ar 11025 -acodec pcm_u8 %s", self::$ffmpeg_cmd, escapeshellarg($file_name), escapeshellarg($temp_file)); shell_exec($command); if (!file_exists($temp_file)) { throw new ApplicationException("Waveform could not be generated!"); } $chunk_size = ceil(filesize($temp_file) / self::PEAKS_RESOLUTION); $peaks = withOpenedFile($temp_file, "r", function ($fh) use(&$chunk_size) { while ($data = fread($fh, $chunk_size)) { $peak = 0; $array = str_split($data); foreach ($array as $item) { $code = ord($item); if ($code > $peak) { $peak = $code; } if ($code == 255) { break; } } (yield $peak - 127); } }); TempFileProvider::delete($temp_file); return $peaks; }
public function getCreateDatabaseCommand() { $user = escapeshellarg($this->user); $host = escapeshellarg($this->host); $createDB = escapeshellarg(sprintf('CREATE DATABASE "%s";', $this->name)); return sprintf('psql -c %s -U %s -h %s', $createDB, $user, $host); }
/** * Main function of the Parser component. It's responsible for read and iterate * the DOM object and extract every element based on the tag and attr passed * as parameters. It uses Curl to make a request to every link of the page and * verifies the HTTP status of every one. * * @param \DOMDocument $dom DOM object with HTML loaded * @param string $pageUrl Url of the target page * @param string $tag Target tag * @param string $attr The attr of the target tag * @param int $limit Limit of links that the crawler will search * @return array Array of found links */ public function parseForLinks(\DOMDocument $dom, $pageUrl, $tag, $attr, $limit = null) { $foundLinks = []; foreach ($dom->getElementsByTagName($tag) as $key => $link) { if ($this->_checkIfItHasReachedTheLimitOfLinks($key, $limit)) { break; } $href = $link->getAttribute($attr); if (!strlen($href) || $href[0] == '#' || preg_match("'^javascript'i", $href)) { continue; } $absolutePath = $this->_convertRelativePathToAbsolute($href, $pageUrl); $href = preg_replace(["'^[^:]+://'", "'#.+\$'"], '', $absolutePath); if (isset($done[$href])) { continue; } $curlCommand = 'curl -I -A "Broken Link Checker" -s --max-redirs 5 -m 5 --retry 1 --retry-delay '; $curlCommand .= '10 -w "%{url_effective}\\t%{http_code}\\t%{time_total}" -o temp2.txt ' . escapeshellarg($href); $curlCommand = explode("\t", `{$curlCommand}`); $foundLinks[$key]['httpStatus'] = $curlCommand[1]; $foundLinks[$key]['timeResponse'] = $curlCommand[2]; $foundLinks[$key]['url'] = $curlCommand[0]; $done[$href] = true; } return $this->_orderLinks($foundLinks); }
/** * {@inheritdoc} */ public function guess($path) { if (!is_file($path)) { throw new FileNotFoundException($path); } if (!is_readable($path)) { throw new AccessDeniedException($path); } if (!self::isSupported()) { return null; } ob_start(); // need to use --mime instead of -i. see #6641 passthru(sprintf($this->cmd, escapeshellarg($path)), $return); if ($return > 0) { ob_end_clean(); return null; } $type = trim(ob_get_clean()); if (!preg_match('#^([a-z0-9\\-]+/[a-z0-9\\-]+)#i', $type, $match)) { // it's not a type, but an error message return null; } return $match[1]; }