public static function run($pluginsInitCode, Kwf_SourceMaps_SourceMap $sourcemap)
 {
     $js = "\n            require('es6-promise').polyfill(); //required for older nodejs\n            var postcss = require('postcss');\n            var plugins = [];\n            " . $pluginsInitCode . "\n            var instance = postcss( plugins );\n            var css = '';\n            process.stdin.setEncoding('utf-8')\n            process.stdin.on('data', function(buf) { css += buf.toString(); });\n            process.stdin.on('end', function() {\n                instance.process(css).then(function (result) {\n                    process.stdout.write(result.css);\n                }).catch(function(e) {\n                    console.log(e);\n                    process.exit(1);\n                });\n            });\n            process.stdin.resume();\n        ";
     $runfile = tempnam("temp/", 'postcss');
     file_put_contents($runfile, $js);
     putenv("NODE_PATH=" . getcwd() . "/node_modules" . PATH_SEPARATOR . getcwd() . "/" . KWF_PATH . PATH_SEPARATOR . getcwd() . "/");
     $cmd = getcwd() . "/" . VENDOR_PATH . "/bin/node " . $runfile;
     $cmd .= " 2>&1";
     $process = new Symfony\Component\Process\Process($cmd);
     $mapData = $sourcemap->getMapContentsData(false);
     $hasSourcemap = !!$mapData->mappings;
     if ($hasSourcemap) {
         $process->setInput($sourcemap->getFileContentsInlineMap(false));
     } else {
         $process->setInput($sourcemap->getFileContents());
     }
     if ($process->run() !== 0) {
         throw new Kwf_Exception("Process '{$cmd}' failed with " . $process->getExitCode() . "\n" . $process->getOutput());
     }
     putenv("NODE_PATH=");
     unlink($runfile);
     $out = $process->getOutput();
     if (Kwf_SourceMaps_SourceMap::hasInline($out)) {
         $ret = Kwf_SourceMaps_SourceMap::createFromInline($out);
     } else {
         $ret = Kwf_SourceMaps_SourceMap::createEmptyMap($out);
         $ret->setMimeType('text/css');
     }
     $ret->setSources($sourcemap->getSources());
     return $ret;
 }
 public static function pack($data)
 {
     $cmd = getcwd() . "/" . VENDOR_PATH . "/bin/node " . __DIR__ . "/BrowserPack.js";
     $process = new Symfony\Component\Process\Process($cmd);
     $process->setInput(json_encode($data));
     $process->mustRun();
     return $process->getOutput();
 }
 public static function count($contents)
 {
     $cmd = getcwd() . "/" . VENDOR_PATH . "/bin/node " . KWF_PATH . "/Kwf/Assets/Util/CssSelectorCount.js";
     $cmd .= " 2>&1";
     $process = new Symfony\Component\Process\Process($cmd);
     $process->setEnv(array('NODE_PATH' => getcwd() . '/node_modules'));
     $process->setInput($contents);
     $process->mustRun();
     $out = json_decode($process->getOutput(), true);
     return $out['selectors'];
 }
 public static function parse($filename)
 {
     $cmd = getcwd() . "/" . VENDOR_PATH . "/bin/node " . __DIR__ . "/ModuleDepsParser.js " . $filename;
     $process = new Symfony\Component\Process\Process($cmd);
     $process->mustRun();
     $out = json_decode($process->getOutput(), true);
     $ret = array('source' => $out[0]['source'], 'deps' => array());
     foreach (array_keys($out[0]['deps']) as $i) {
         $ret['deps'][] = $i;
     }
     return $ret;
 }
Beispiel #5
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $dir = implode(DIRECTORY_SEPARATOR, [$this->getContainer()->get('kernel')->getRootDir(), '..', 'utils', 'dumpdb']);
     $command = implode(DIRECTORY_SEPARATOR, [$dir, 'dumpdb']);
     chdir($dir);
     $process = new \Symfony\Component\Process\Process($command);
     $process->mustRun();
     if (!$process->isSuccessful()) {
         throw new ProcessFailedException($process);
     }
     $stderr = $process->getErrorOutput();
     $stderr = trim($stderr);
     $stdout = $process->getOutput();
     $result = implode("\n\n", [$stderr, $stdout]);
     $output->writeln($result);
 }
 public static function parse($filename)
 {
     if (substr($filename, 0, strlen(getcwd() . '/temp/')) == getcwd() . '/temp/') {
         $cacheId = md5_file($filename);
     } else {
         $cacheId = str_replace(array('/', '.', '-'), '_', $filename) . '__' . md5_file($filename);
     }
     $ret = self::_getCache()->load($cacheId);
     if ($ret === false) {
         $cmd = getcwd() . "/" . VENDOR_PATH . "/bin/node " . __DIR__ . "/Parser.js " . $filename;
         $process = new Symfony\Component\Process\Process($cmd);
         $process->mustRun();
         $out = json_decode($process->getOutput(), true);
         $ret = array();
         foreach (array_keys($out[0]['deps']) as $i) {
             $ret[] = $i;
         }
         self::_getCache()->save($ret, $cacheId);
     }
     return $ret;
 }
 public function filter(Kwf_SourceMaps_SourceMap $sourcemap)
 {
     putenv("NODE_PATH=" . getcwd() . "/node_modules");
     $cmd = getcwd() . "/" . VENDOR_PATH . "/bin/node " . __DIR__ . "/CssChunks.js";
     $cmd .= " 2>&1";
     $process = new Symfony\Component\Process\Process($cmd);
     $process->setInput($sourcemap->getFileContentsInlineMap(false));
     $process->mustRun();
     $out = $process->getOutput();
     $out = explode("\n/* ***** NEXT CHUNK ***** */\n", $out);
     $ret = array();
     foreach ($out as $chunk) {
         if (Kwf_SourceMaps_SourceMap::hasInline($chunk)) {
             $mapChunk = Kwf_SourceMaps_SourceMap::createFromInline($chunk);
         } else {
             $mapChunk = Kwf_SourceMaps_SourceMap::createEmptyMap($chunk);
             $mapChunk->setMimeType('text/css');
         }
         $ret[] = $mapChunk;
     }
     return $ret;
 }
Beispiel #8
0
 private function getSystemGroups()
 {
     $process = new \Symfony\Component\Process\Process('cat /etc/group | cut -d: -f1');
     $process->run();
     foreach (explode("\n", $process->getOutput()) as $line) {
         if ($line != '' && substr($line, 0, 1) != '#') {
             $groups[] = $line;
         }
     }
     return $groups;
 }
Beispiel #9
0
 /**
  * Run the queue fetching process.
  * @param string  $command The command.
  * @param string  $cwd     The working directory.
  * @param integer $timeout The timeout.
  * @param array   $env     The environment to be passed.
  * @return void
  */
 protected function runQueueFetching($command, $cwd = null, $timeout = null, array $env = [])
 {
     $process = new \Symfony\Component\Process\Process($command, isset($cwd) ? $cwd : getcwd(), $env, null, $timeout);
     $process->setTimeout($timeout);
     $process->setIdleTimeout(null);
     $process->run();
     if ($process->isSuccessful()) {
         //TODO logging.
         $this->stdout($process->getOutput() . PHP_EOL);
         $this->stdout($process->getErrorOutput() . PHP_EOL);
     } else {
         //TODO logging.
         $this->stdout($process->getOutput() . PHP_EOL);
         $this->stdout($process->getErrorOutput() . PHP_EOL);
     }
 }
Beispiel #10
0
<?php

require 'vendor/autoload.php';
$pathToGit = 'git';
$process = new \Symfony\Component\Process\Process(escapeshellarg($pathToGit) . ' --version');
$process->run();
if ($process->isSuccessful()) {
    echo $process->getOutput();
} else {
    echo "Git not found or Symfony\\Process couldn't read the process output";
}
 /**
  * Notify client about stopped task
  * 
  * @param bool $manual True means process stopped manually
  */
 protected function _stopped($manual = false)
 {
     $this->_task = array('stdout' => $this->_Process->getOutput(), 'stderr' => $this->_Process->getErrorOutput(), 'stopped' => $this->_getCurrentDateTime(), 'process_id' => 0) + $this->_task;
     $this->_TaskServer->stopped($this->_task, $manual);
     $this->_Shell->out("Task #{$this->_task['id']} stopped, code " . (string) $this->_task['code']);
 }
 protected function compileWithCommand($bin, $source, $target)
 {
     $sourceFilePath = trim(Director::getAbsFile($source));
     $targetFilePath = trim(Director::getAbsFile($target));
     $command = $bin . " " . escapeshellarg($sourceFilePath);
     $process = new \Symfony\Component\Process\Process($command);
     $process->run();
     if ($process->isSuccessful()) {
         $css = $process->getOutput();
         if (!file_exists(dirname($targetFilePath))) {
             mkdir(dirname($targetFilePath), null, true);
         }
         file_put_contents($targetFilePath, $css);
         $this->filesCacheAdd($source);
         $this->log[] = ["compiled {$source} to {$target}", 'info'];
     } else {
         $message = $process->getErrorOutput();
         if ($process->getExitCode() != 1 || !$message) {
             $message = "\"{$command}\": non-zero exit code {$process->getExitCode()} '{$process->getExitCodeText()}'. (Output: '{$message}')";
         }
         $this->log[] = ["failed to compile {$source} with {$bin}: {$message}", 'error'];
         SS_Log::log(new Exception($message), SS_Log::ERR);
     }
 }
 public function clientAction()
 {
     set_time_limit(0);
     //ini_set('max_execution_time', 0);
     //ini_set('memory_limit', '256M');
     if ($_SERVER['REQUEST_METHOD'] == 'POST') {
         if (!empty($_FILES) && !empty($_FILES["inputFile"]["name"])) {
             $file = TMP_UPLOAD_PATH . '/' . str_replace(array(' ', '+', '(', ')'), '', $_FILES["inputFile"]["name"]);
             $tmpFile = $_FILES["inputFile"]["tmp_name"];
             $inputFile = $_FILES['inputFile'];
             if (move_uploaded_file($tmpFile, $file)) {
                 /* @var $objReader \PHPExcel_Reader_Excel2007 */
                 $objReader = \PHPExcel_IOFactory::createReaderForFile($file);
                 if (get_class($objReader) == 'PHPExcel_Reader_CSV') {
                     $this->get('session')->setFlash('sonata_flash_error', $this->admin->trans('Fichier non lisible'));
                     return $this->render(':redirects:back.html.twig');
                 }
                 $_FILES = array();
                 //create fake process id
                 $pid = time();
                 $user = $this->get('security.context')->getToken()->getUser();
                 $kernel = $this->get('kernel');
                 $command = 'php ' . $kernel->getRootDir() . '/console clientbundle:import:initial client ' . $user->getId() . ' ' . realpath($file) . ' ' . $pid . ' --env=' . $kernel->getEnvironment();
                 // . ' --no-debug ';
                 /* var_dump($command);
                 			exit; */
                 $process = new \Symfony\Component\Process\Process($command);
                 $process->setTimeout(3600);
                 $process->start();
                 $start = microtime(true);
                 while ($process->isRunning()) {
                     $total = microtime(true) - $start;
                     if ($total / 60 >= 2) {
                         // if process is too long (2 minutes)
                         //var_dump(($total/60));
                         $em = $this->getDoctrine()->getManager();
                         $importNotif = new ImportNotification();
                         $importNotif->setPid($pid)->setUser($user)->setClientId(0);
                         $em->persist($importNotif);
                         $em->flush();
                         $this->_hasImportErrors = true;
                         $this->get('session')->setFlash('sonata_flash_error', \AppKernel::getStaticContainer()->get('translator')->trans('There are too many data to be processed. We will just notify you once it\'s done. Check your email (' . $user->getEmail() . ') within few hours.'));
                         break;
                         return $this->render(':redirects:back.html.twig');
                     }
                 }
                 $output = unserialize($process->getOutput());
                 $messages = $output['messages'];
                 $import_counts = $output['import_counts'];
             }
         } else {
             $this->get('session')->setFlash('sonata_flash_error|raw', 'Please upload a file');
         }
         //$messages = $this->getCountMessageImports();
         if (!empty($messages)) {
             $this->get('session')->setFlash('sonata_flash_info|raw', implode("<br />", $messages));
         }
         return $this->render(':redirects:back.html.twig');
     }
     return $this->render('ApplicationSonataClientBundle:InitialImport:client.html.twig');
 }
Beispiel #14
0
#!/usr/bin/php
<?php 
$config = ['git_urls' => ['https://github.com/symfony/Process.git' => 'sf_process/'], 'autoload_config' => ['sf_process/' => 'Symfony\\Component\\Process'], 'example' => function () {
    $process = new Symfony\Component\Process\Process('ls -lsa');
    $process->setTimeout(5);
    $process->run();
    print $process->getOutput();
}];
if ($return_config) {
    return $config;
}
require_once __DIR__ . '/_yf_autoloader.php';
new yf_autoloader($config);
 /**
  * {@inheritdoc}
  */
 public function importAction()
 {
     set_time_limit(1200);
     $this->getLockingAccessDenied();
     $import_counts = array();
     $messages = array();
     if (!empty($_FILES) && !empty($_FILES["inputFile"])) {
         $file = TMP_UPLOAD_PATH . '/' . $_FILES["inputFile"]["name"];
         $tmpFile = $_FILES["inputFile"]["tmp_name"];
         $inputFile = $_FILES['inputFile'];
         $error_counts = 0;
         if ($this->importFileValidate($inputFile)) {
             if (move_uploaded_file($tmpFile, $file)) {
                 $objReader = \PHPExcel_IOFactory::createReaderForFile($file);
                 if (get_class($objReader) == 'PHPExcel_Reader_CSV') {
                     unset($objReader);
                     $this->get('session')->setFlash('sonata_flash_error', $this->admin->trans('Fichier non lisible'));
                     return $this->render(':redirects:back.html.twig');
                 }
                 $_FILES = array();
                 //create fake process id
                 $pid = time();
                 $user = $this->get('security.context')->getToken()->getUser();
                 $kernel = $this->get('kernel');
                 $command = 'php ' . $kernel->getRootDir() . '/console clientoperationsbundle:import:excel ' . $user->getId() . ' ' . $this->client_id . ' application.sonata.admin.v01tva ' . $file . ' ' . $inputFile['name'] . ' ' . $this->getLocking() . ' ' . $this->_year . ' ' . $this->_month . ' ' . $pid . ' --env=' . $kernel->getEnvironment() . ' --no-debug ';
                 /* var_dump($command);
                   	exit; */
                 $process = new \Symfony\Component\Process\Process($command);
                 $process->setTimeout(3600);
                 $process->start();
                 $start = microtime(true);
                 while ($process->isRunning()) {
                     $total = microtime(true) - $start;
                     if ($total / 60 >= 2) {
                         // if process is too long (2 minutes)
                         //var_dump(($total/60));
                         $em = $this->getDoctrine()->getManager();
                         $importNotif = new ImportNotification();
                         $importNotif->setPid($pid)->setUser($user)->setClientId($this->client_id);
                         $em->persist($importNotif);
                         $em->flush();
                         $this->_hasImportErrors = true;
                         $this->get('session')->setFlash('sonata_flash_error', $this->admin->trans('There are too many data to be processed. We will just notify you once it\'s done. Check your email (' . $user->getEmail() . ') within few hours.'));
                         break;
                         return $this->render(':redirects:back.html.twig');
                     }
                 }
                 $output = unserialize($process->getOutput());
                 $messages = $output['messages'];
                 $import_counts = $output['import_counts'];
                 $error_counts = $output['error_counts'];
             }
         }
     }
     if (!empty($messages) || $error_counts) {
         $this->get('session')->setFlash('sonata_flash_info|raw', implode("<br/>", $messages));
     } else {
         $message = trim($this->get('session')->getFlash('sonata_flash_info|raw'));
         if ($message == '') {
             $this->get('session')->setFlash('sonata_flash_info|raw', $this->admin->trans('Imported : %count%', array('%count%' => 0)));
         } else {
             $this->get('session')->setFlash('sonata_flash_info|raw', $message);
         }
     }
     if (isset($import_counts['rows']['errors']) && !empty($import_counts['rows']['errors']) || $this->_hasImportErrors) {
         return $this->render(':redirects:back.html.twig');
     } else {
         return $this->redirect($this->generateUrl('rapprochement_index', array('client_id' => $this->client_id, 'month' => $this->_query_month, 'fromImport' => 1)));
     }
 }
Beispiel #16
0
        $data = json_decode($payload, true);
        $payloadHash = hash_hmac($algo, $payload, $secret);
        if ($hash === $payloadHash) {
            $request->attributes->set('payload', $data);
        } else {
            return new Response('Payload hash does not match hub signature.', Response::HTTP_FORBIDDEN);
        }
    }
}, Silex\Application::EARLY_EVENT);
// Auto update deployer.phar on GitHub WebHook.
$controller->post('update/deployer', function (Request $request) use($app) {
    $event = $request->headers->get('X-Github-Event');
    $payload = $request->attributes->get('payload');
    if ($event === 'create' && $payload['ref_type'] === 'tag') {
        file_put_contents($app['schedule'], "update:deployer\n", FILE_APPEND);
        return new Response('Schedule task to update deployer created.', Response::HTTP_OK, ['Content-Type' => 'text/plain']);
    }
    return new Response('', Response::HTTP_FORBIDDEN, ['Content-Type' => 'text/plain']);
});
// Auto update docs on GitHub WebHook.
$controller->post('update/{what}', function (Request $request, $what) use($app) {
    $event = $request->headers->get('X-Github-Event');
    $payload = $request->attributes->get('payload');
    if ($event === 'pull_request' && $payload['action'] === 'closed' && $payload['pull_request']['merged'] || $event === 'push') {
        $process = new \Symfony\Component\Process\Process('php ' . $app['cli'] . ' update:' . $what);
        $process->run();
        return new Response("Update `{$what}` successfully.\n\n" . $process->getOutput(), Response::HTTP_OK, ['Content-Type' => 'text/plain']);
    }
    return new Response("The `{$what}` was not updated.", Response::HTTP_OK, ['Content-Type' => 'text/plain']);
})->assert('what', '(documentation)|(recipes)');
return $controller;
Beispiel #17
0
        $process->mustRun();
        return $process->getOutput();
    };
    if (is_file($app['recipes.path'] . '/README.md')) {
        $output->write($run('git reset --hard origin/master'));
        $output->write($run('git pull https://github.com/deployphp/recipes.git master 2>&1'));
    } else {
        $output->write($run('git clone --depth 1 https://github.com/deployphp/recipes.git . 2>&1'));
    }
});
$console->add($updateRecipesCommand);
$scheduleCommand = new \Symfony\Component\Console\Command\Command('schedule');
$scheduleCommand->setCode(function ($input, $output) use($app) {
    $commands = explode("\n", file_get_contents($app['schedule']));
    while (count($commands) > 0) {
        $command = array_shift($commands);
        if (in_array($command, ['update:deployer', 'update:documentation', 'update:recipes'], true)) {
            // Remove same commands.
            $commands = array_filter($commands, function ($i) use($command) {
                return $i !== $command;
            });
            $output->write("Running command {$command}.\n");
            $process = new \Symfony\Component\Process\Process("php {$app['cli']} {$command}");
            $process->run();
            file_put_contents(__DIR__ . '/logs/' . $command . '.log', $process->getOutput());
        }
    }
    file_put_contents($app['schedule'], implode("\n", $commands));
});
$console->add($scheduleCommand);
$console->run();
Beispiel #18
0
/**
 * Execute commands on local machine.
 * @param string $command Command to run locally.
 * @param int $timeout (optional) Override process command timeout in seconds.
 * @return Result Output of command.
 * @throws \RuntimeException
 */
function runLocally($command, $timeout = 60)
{
    $command = env()->parse($command);
    if (isVeryVerbose()) {
        writeln("<comment>Run locally</comment>: {$command}");
    }
    $process = new Symfony\Component\Process\Process($command);
    $process->setTimeout($timeout);
    $process->run(function ($type, $buffer) {
        if (isDebug()) {
            if ('err' === $type) {
                write("<fg=red>></fg=red> {$buffer}");
            } else {
                write("<fg=green>></fg=green> {$buffer}");
            }
        }
    });
    if (!$process->isSuccessful()) {
        throw new \RuntimeException($process->getErrorOutput());
    }
    return new Result($process->getOutput());
}
Beispiel #19
0
<?php

chdir(__DIR__ . '/..');
require_once 'vendor/autoload.php';
// Fetch a list of all supported tags
$process = new \Symfony\Component\Process\Process('exiftool -f -listx');
$process->run();
$xml = $process->getOutput();
// Parse document
$doc = new DOMDocument();
$doc->loadXML($xml);
$xpath = new DOMXPath($doc);
$list = $xpath->query('//table');
// Write tags to config file:
$tags = [];
$content = [];
$content[] = '<?php return [';
foreach ($list as $tag) {
    $tag = strtolower($tag->getAttribute('g0'));
    if (in_array($tag, $tags)) {
        continue;
    }
    $tags[] = $tag;
    $content[] = "'{$tag}',";
}
$content[] = '];';
file_put_contents('config/exiftool-tags.php', implode(PHP_EOL, $content));
// Output:
printf('Written %s files to config/exiftool-tags.php', count($tags));