Пример #1
0
 /**
  * @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;
 }
Пример #2
0
 public function start(Output\OutputInterface $output)
 {
     /* @var $_loop  \React\EventLoop\LoopInterface*/
     $loop = \React\EventLoop\Factory::create();
     // create a new socket
     $socket = new \React\Socket\Server($loop);
     // pipe a connection into itself
     $socket->on('connection', function (\React\Socket\Connection $conn) use($output, $loop) {
         $output->writeln('CONNECTION ESTABLISHED: ' . $conn->getRemoteAddress());
         //$infiniteStreamHandle	= fopen('/tmp/random', 'r');
         $infiniteStreamHandle = fopen('/dev/urandom', 'r');
         $fileToStream = new \React\Stream\Stream($infiniteStreamHandle, $loop);
         $output->writeln('streaming ...');
         //$conn->pipe($infiniteStreamHandle);
         $fileToStream->pipe($conn);
     });
     echo "Socket server listening on port 4000.\n";
     echo "You can connect to it by running: telnet localhost 4000\n";
     $socket->listen(4000);
     $loop->run();
 }
Пример #3
0
 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);
     });
 }
Пример #4
0
$if = isset($args['i']) ? $args['i'] : '/dev/zero';
$of = isset($args['o']) ? $args['o'] : '/dev/null';
$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);
Пример #5
0
    /**
     * 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

// 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";
Пример #7
0
        $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);
};
$router = new React\Gifsocket\Router(['/socket.gif' => sendEmptyFrameAfter($gifServer), '/' => function ($request, $response) use($loop) {
    $response->writeHead(200, ['Content-Type' => 'text/html']);
    $fd = fopen(__DIR__ . '/views/index.html', 'r');
    $template = new React\Stream\Stream($fd, $loop);
    $template->pipe($response);
}, '/message' => function ($request, $response) use($addMessage) {
    $message = $request->getQuery()['message'];
    $addMessage($message);
    $response->writeHead(200);
    $response->end();
}]);
$http->on('request', $router);
echo "Webserver running on localhost:8080\n";
$socket->listen(8080);
$loop->run();
Пример #8
0
<?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();
Пример #9
0
<?php

require 'vendor/autoload.php';
$loop = React\EventLoop\Factory::create();
$stream = new \React\Stream\Stream(fopen('php://stdout', 'w+'), $loop);
$i = 0;
$loop->addPeriodicTimer(1, function (React\EventLoop\Timer\Timer $timer) use(&$i, $loop, $stream) {
    $stream->write(++$i . PHP_EOL);
    if ($i >= 15) {
        $loop->cancelTimer($timer);
        $stream->end();
    }
});
$loop->run();
Пример #10
0
<?php

require __DIR__ . '/../vendor/autoload.php';
$loop = React\EventLoop\Factory::create();
$in = new React\Stream\Stream(STDIN, $loop);
$out = new React\Stream\Stream(STDOUT, $loop);
$compressor = Clue\React\Zlib\ZlibFilterStream::createGzipCompressor(1);
$in->pipe($compressor)->pipe($out);
$loop->run();
Пример #11
0
<?php

require 'vendor/autoload.php';
$loop = React\EventLoop\Factory::create();
$read = new \React\Stream\Stream(fopen('php://stdin', 'r+'), $loop);
$write = new \React\Stream\Stream(fopen('php://stdout', 'w+'), $loop);
$read->pipe($write);
$loop->run();
Пример #12
0
<?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();
Пример #13
0
<?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();
Пример #14
0
{
    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();
Пример #15
0
<?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();
Пример #16
0
<?php

require __DIR__ . '/vendor/autoload.php';
define('DOCUMENT_ROOT', dirname(__FILE__));
require_once DOCUMENT_ROOT . '/bootstrap.php';
gc_enable();
$bootstrap = new Bootstrap();
$booted = $bootstrap->boot();
$loop = React\EventLoop\Factory::create();
$dnsResolverFactory = new React\Dns\Resolver\Factory();
$dns = $dnsResolverFactory->createCached('8.8.8.8', $loop);
$connector = new React\SocketClient\Connector($loop, $dns);
$stdin = new React\Stream\Stream(STDIN, $loop);
fwrite(STDERR, colorize(getenv('sid'), 'yellow') . " widgets before : " . \sizeToCleanSize(memory_get_usage()) . "\n");
// We load and register all the widgets
$wrapper = WidgetWrapper::getInstance();
$wrapper->registerAll(true);
fwrite(STDERR, colorize(getenv('sid'), 'yellow') . " widgets : " . \sizeToCleanSize(memory_get_usage()) . "\n");
$conn = null;
$parser = new \Moxl\Parser();
$buffer = '';
$stdin_behaviour = function ($data) use(&$conn, $loop, &$buffer, &$connector, &$xmpp_behaviour, &$parser) {
    if (substr($data, -1) == "") {
        $messages = explode("", $buffer . substr($data, 0, -1));
        $buffer = '';
        foreach ($messages as $message) {
            #fwrite(STDERR, colorize($message, 'yellow')." : ".colorize('received from the browser', 'green')."\n");
            $msg = json_decode($message);
            if (isset($msg)) {
                if ($msg->func == 'message' && $msg->body != '') {
                    $msg = $msg->body;
<?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();