/** * @param string $path * @return string */ function parse($path) { if (!file_exists($this->pathMails = $this->config['cacheDir'] . DIRECTORY_SEPARATOR . $this->siteHash . DIRECTORY_SEPARATOR . $path)) { mkdir($this->pathMails); } foreach ($this->getLinks() as $file => $url) { $readStream = fopen($url, 'r'); $writeStream = fopen($this->pathSiteHash . DIRECTORY_SEPARATOR . $file, 'w'); stream_set_blocking($readStream, 0); stream_set_blocking($writeStream, 0); $read = new \React\Stream\Stream($readStream, $this->loop); $write = new \React\Stream\Stream($writeStream, $this->loop); $read->on('end', function () use($file, &$files) { $path = $this->pathSiteHash . DIRECTORY_SEPARATOR . $file; $crawler = new Crawler(); $crawler->add(file_get_contents($path)); $arrLinks = $crawler->filter('a')->each(function (Crawler $nodeCrawler) { return [$nodeCrawler->filter('a')->attr('href')]; }); $validMails = []; foreach ($arrLinks as $k => $url) { if (filter_var($url[0], FILTER_VALIDATE_EMAIL)) { $validMails[] = $url[0]; } else { if (filter_var($m = str_replace('mailto:', '', $url[0]), FILTER_VALIDATE_EMAIL)) { $validMails[] = $m; } } } $mails = []; foreach ($validMails as $m) { array_push($mails, str_replace('mailto:', '', $m)); } file_put_contents($this->pathMails . DIRECTORY_SEPARATOR . $file, implode(PHP_EOL, $mails)); unset($files[$file]); }); $read->pipe($write); } // каждые $this->config['periodTime'] секунд выполнять какое-то действие $this->loop->addPeriodicTimer($this->config['periodTime'], function ($timer) use(&$files) { if (0 === count($files)) { $timer->cancel(); } echo PHP_EOL . "Passed {$this->config['periodTime']} sec. " . PHP_EOL; }); echo "This script will show the download status every {$this->config['periodTime']} seconds." . PHP_EOL; $this->loop->run(); return 'Dir of result in: ' . $this->config['cacheDir'] . DIRECTORY_SEPARATOR . $this->siteHash . DIRECTORY_SEPARATOR . $path; }
if (!empty($xml) && $conn) { $conn->write(trim($xml)); #fwrite(STDERR, colorize(trim($xml), 'yellow')." : ".colorize('sent to XMPP', 'green')."\n"); } } } else { $buffer .= $data; } $loop->tick(); }; $xmpp_behaviour = function (React\Stream\Stream $stream) use(&$conn, $loop, &$stdin, $stdin_behaviour, $parser) { $conn = $stream; fwrite(STDERR, colorize(getenv('sid'), 'yellow') . " : " . colorize('linker launched', 'blue') . "\n"); fwrite(STDERR, colorize(getenv('sid'), 'yellow') . " launched : " . \sizeToCleanSize(memory_get_usage()) . "\n"); $stdin->removeAllListeners('data'); $stdin->on('data', $stdin_behaviour); // We define a huge buffer to prevent issues with SSL streams, see https://bugs.php.net/bug.php?id=65137 $conn->bufferSize = 1024 * 32; $conn->on('data', function ($message) use(&$conn, $loop, $parser) { if (!empty($message)) { $restart = false; if ($message == '</stream:stream>') { $conn->close(); $loop->stop(); } elseif ($message == "<proceed xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>" || $message == '<proceed xmlns="urn:ietf:params:xml:ns:xmpp-tls"/>') { stream_set_blocking($conn->stream, 1); $out = stream_socket_enable_crypto($conn->stream, 1, STREAM_CRYPTO_METHOD_TLS_CLIENT); $restart = true; } #fwrite(STDERR, colorize($message, 'yellow')." : ".colorize('received', 'green')."\n"); #fwrite(STDERR, colorize(getenv('sid'), 'yellow')." widgets : ".\sizeToCleanSize(memory_get_usage())."\n");
{ return function ($request, $response) use($gifServer) { $gifServer($request, $response); $gifServer->addFrame(createGifFrame([''])); }; } $loop = React\EventLoop\Factory::create(); $socket = new React\Socket\Server($loop); $http = new React\Http\Server($socket); $gifServer = new React\Gifsocket\Server($loop); $messages = []; $addMessage = function ($message) use($gifServer, &$messages) { $messages[] = $message; if (count($messages) > 18) { $messages = array_slice($messages, count($messages) - 18); } $frame = createGifFrame($messages); $gifServer->addFrame($frame); }; $stdin = new React\Stream\Stream(STDIN, $loop); $stdin->on('data', function ($data) use($addMessage) { $messages = explode("\n", trim($data)); foreach ($messages as $message) { $addMessage($message); } }); $router = new React\Gifsocket\Router(['/' => sendEmptyFrameAfter($gifServer)]); $http->on('request', $router); echo "Webserver running on localhost:8080\n"; $socket->listen(8080); $loop->run();
$t = isset($args['t']) ? $args['t'] : 1; // passing file descriptors requires mapping paths (https://bugs.php.net/bug.php?id=53465) $if = str_replace('/dev/fd/', 'php://fd/', $if); $of = str_replace('/dev/fd/', 'php://fd/', $of); $loop = new React\EventLoop\StreamSelectLoop(); // setup information stream $info = new React\Stream\Stream(STDERR, $loop); $info->pause(); if (extension_loaded('xdebug')) { $info->write('NOTICE: The "xdebug" extension is loaded, this has a major impact on performance.' . PHP_EOL); } $info->write('piping from ' . $if . ' to ' . $of . ' (for max ' . $t . ' second(s)) ...' . PHP_EOL); // setup input and output streams and pipe inbetween $in = new React\Stream\Stream(fopen($if, 'r'), $loop); $out = new React\Stream\Stream(fopen($of, 'w'), $loop); $out->pause(); $in->pipe($out); // stop input stream in $t seconds $start = microtime(true); $timeout = $loop->addTimer($t, function () use($in, &$bytes) { $in->close(); }); // print stream position once stream closes $in->on('close', function () use($in, $start, $timeout, $info) { $t = microtime(true) - $start; $timeout->cancel(); $bytes = ftell($in->stream); $info->write('read ' . $bytes . ' byte(s) in ' . round($t, 3) . ' second(s) => ' . round($bytes / 1024 / 1024 / $t, 1) . ' MiB/s' . PHP_EOL); $info->write('peak memory usage of ' . round(memory_get_peak_usage(true) / 1024 / 1024, 1) . ' MiB' . PHP_EOL); }); $loop->run();
public function onWeb(\React\Socket\Connection $incoming) { $slaveId = $this->getNextSlave(); $port = $this->slaves[$slaveId]['port']; $client = stream_socket_client('tcp://127.0.0.1:' . $port); $redirect = new \React\Stream\Stream($client, $this->loop); $redirect->on('close', function () use($incoming) { $incoming->end(); }); $incoming->on('data', function ($data) use($redirect) { $redirect->write($data); }); $redirect->on('data', function ($data) use($incoming) { $incoming->write($data); }); }
<?php // downloading the two best technologies ever in parallel require __DIR__ . '/../vendor/autoload.php'; $loop = React\EventLoop\Factory::create(); $files = array('node-v0.6.18.tar.gz' => 'http://nodejs.org/dist/v0.6.18/node-v0.6.18.tar.gz', 'php-5.4.3.tar.gz' => 'http://it.php.net/get/php-5.4.3.tar.gz/from/this/mirror'); $buffers = array(); foreach ($files as $file => $url) { $readStream = fopen($url, 'r'); $writeStream = fopen($file, 'w'); stream_set_blocking($readStream, 0); stream_set_blocking($writeStream, 0); $read = new React\Stream\Stream($readStream, $loop); $write = new React\Stream\Stream($writeStream, $loop); $read->on('end', function () use($file, &$files) { unset($files[$file]); echo "Finished downloading {$file}\n"; }); $read->pipe($write); } $loop->addPeriodicTimer(5, function ($timer) use(&$files) { if (0 === count($files)) { $timer->cancel(); } foreach ($files as $file => $url) { $mbytes = filesize($file) / (1024 * 1024); $formatted = number_format($mbytes, 3); echo "{$file}: {$formatted} MiB\n"; } }); echo "This script will show the download status every 5 seconds.\n"; $loop->run();
/** * Creates a new ProcessSlave instance. * * @param integer $port */ protected function newInstance($port) { if ($this->inShutdown) { //when we are in the shutdown phase, we close all connections //as a result it actually tries to reconnect the slave, but we forbid it in this phase. return; } $keepClosed = false; $bootstrapFailed = 0; if (isset($this->slaves[$port])) { $bootstrapFailed = $this->slaves[$port]['bootstrapFailed']; $keepClosed = $this->slaves[$port]['keepClosed']; if ($keepClosed) { return; } } if ($this->output->isVeryVerbose()) { $this->output->writeln(sprintf("Start new worker #%d", $port)); } $host = Utils::isWindows() ? 'tcp://127.0.0.1' : $this->getNewSlaveSocket($port); $slave = ['ready' => false, 'pid' => null, 'port' => $port, 'closeWhenFree' => false, 'waitForRegister' => true, 'duringBootstrap' => false, 'bootstrapFailed' => $bootstrapFailed, 'keepClosed' => $keepClosed, 'busy' => false, 'requests' => 0, 'connections' => 0, 'connection' => null, 'host' => $host]; $bridge = var_export($this->getBridge(), true); $bootstrap = var_export($this->getAppBootstrap(), true); $config = ['port' => $slave['port'], 'host' => $slave['host'], 'session_path' => session_save_path(), 'controllerHost' => Utils::isWindows() ? 'tcp://127.0.0.1' : $this->controllerHost, 'app-env' => $this->getAppEnv(), 'debug' => $this->isDebug(), 'logging' => $this->isLogging(), 'static' => $this->isServingStatic()]; $config = var_export($config, true); $dir = var_export(__DIR__, true); $script = <<<EOF <?php set_time_limit(0); require_once file_exists({$dir} . '/vendor/autoload.php') ? {$dir} . '/vendor/autoload.php' : {$dir} . '/../../autoload.php'; require_once {$dir} . '/functions.php'; //global for all global functions \\PHPPM\\ProcessSlave::\$slave = new \\PHPPM\\ProcessSlave({$bridge}, {$bootstrap}, {$config}); \\PHPPM\\ProcessSlave::\$slave->run(); EOF; $commandline = $this->phpCgiExecutable; $file = tempnam(sys_get_temp_dir(), 'dbg'); file_put_contents($file, $script); register_shutdown_function('unlink', $file); //we can not use -q since this disables basically all header support //but since this is necessary at least in Symfony we can not use it. //e.g. headers_sent() returns always true, although wrong. $commandline .= ' -C ' . ProcessUtils::escapeArgument($file); $descriptorspec = [['pipe', 'r'], ['pipe', 'w'], ['pipe', 'w']]; $this->slaves[$port] = $slave; $this->slaves[$port]['process'] = proc_open($commandline, $descriptorspec, $pipes); $stderr = new \React\Stream\Stream($pipes[2], $this->loop); $stderr->on('data', function ($data) use($port) { if ($this->lastWorkerErrorPrintBy !== $port) { $this->output->writeln("<info>--- Worker {$port} stderr ---</info>"); $this->lastWorkerErrorPrintBy = $port; } $this->output->write("<error>{$data}</error>"); }); $this->slaves[$port]['stderr'] = $stderr; }
<?php require 'vendor/autoload.php'; $loop = React\EventLoop\Factory::create(); $superFab = new \Fab\SuperFab(); $read = new \React\Stream\Stream(fopen('php://stdin', 'r+'), $loop); $write = new \React\Stream\Stream(fopen('php://stdout', 'w+'), $loop); $read->on('data', function ($data, $read) use($write, $superFab) { if (trim($data) == 'quit') { $write->close(); $read->close(); } $input = trim($data); $line = Kitten::get() . ' says "' . $input . '"'; $line = $superFab->paint($line); $line .= PHP_EOL; $write->write($line); }); $loop->run();
<?php require __DIR__ . '/../vendor/autoload.php'; $loop = React\EventLoop\Factory::create(); $client = new PhpCoap\Client($loop); $client->post('coap://skynet.im/devices', 'type=test', function ($data) use($loop, $client) { $data = json_decode($data); $uuid = $data->uuid; $token = $data->token; printf("UUID: %s\nToken: %s\n", $uuid, $token); $stdin = new React\Stream\Stream(fopen('php://stdin', 'r'), $loop); $stdin->on('data', function ($data) use($client, $uuid, $token) { $query = http_build_query(array('token' => $token, 'value' => trim($data))); $client->post(sprintf('coap://skynet.im/data/%s', $uuid), $query, function ($data) { var_dump(json_decode($data)); }); }); }); $loop->run();
<?php require 'vendor/autoload.php'; $loop = React\EventLoop\Factory::create(); $read = new \React\Stream\Stream(STDIN, $loop); $read->on('data', function ($datas) use($loop) { $datas = explode(PHP_EOL, trim($datas)); foreach ($datas as $data) { if ($data == 15) { $loop->stop(); return; } for ($i = 0; $i < 100000; $i++) { $data = hash('sha256', time() . $data); } echo $data, PHP_EOL; } }); $loop->run();
<?php require 'vendor/autoload.php'; $loop = React\EventLoop\Factory::create(); $read = new \React\Stream\Stream(STDIN, $loop); $read->on('data', function ($data) use($loop) { $data = trim($data); if ($data == 15) { $loop->stop(); } }); $read->pipe(new \React\Stream\Stream(STDOUT, $loop)); $loop->run();
<?php require __DIR__ . '/../vendor/autoload.php'; /** @var $loop \React\EventLoop\ExtEventLoop */ $cfg = new \EventConfig(); $cfg->requireFeatures(\EventConfig::FEATURE_FDS); $loop = new \React\EventLoop\ExtEventLoop($cfg); $dir = getcwd(); $fd = fopen($dir . DIRECTORY_SEPARATOR . 'test.dmg', "r"); stream_set_blocking($fd, 0); $stream = new \React\Stream\Stream($fd, $loop); $stream->on('data', function () { echo 'test' . PHP_EOL; }); $loop->addPeriodicTimer(0.01, function () { echo "Timer" . PHP_EOL; }); $loop->run();