/** * Boot Browser * @return JonnyW\PhantomJs\Client */ public function boot() { $client = Client::getInstance(); $client->setBinDir(base_path() . '/bin'); $client->addOption('--load-images=true'); $client->addOption('--ignore-ssl-errors=true'); $client->addOption('--ssl-protocol=any'); $this->client = $client; return $client; }
protected function request($method, $path = 'index.php', array $params = array(), $debug = false) { $client = \JonnyW\PhantomJs\Client::getInstance(); $request = $client->getMessageFactory()->createRequest(); $response = $client->getMessageFactory()->createResponse(); $debugParams = array('tubepress_debug' => $debug ? 'true' : 'false', 'XDEBUG_SESSION_START' => 'true'); $encodedOpts = base64_encode(serialize($this->_options)); $finalParams = array_merge($debugParams, array('options' => $encodedOpts), $params); $urlFactory = new tubepress_url_impl_puzzle_UrlFactory(); $url = $urlFactory->fromString('http://' . self::$_WEB_SERVER_ADDRESS)->setPath($path)->setQuery($finalParams); $request->setMethod($method); $request->setUrl($url->toString()); $client->getEngine()->setPath(self::_getProjectRoot() . '/bin/phantomjs'); $client->send($request, $response); if ($response->getStatus() !== 200) { throw new RuntimeException(sprintf('%s returned HTTP %s: %s', $url, $response->getStatus(), $response->getContent())); } return $response; }
public function takeScreenshots($site, $newDir, $stats, $siteStatus, $auth) { $delay = $stats["delay"]; $urlHost = parse_url($site)["host"]; $urlPath = isset(parse_url($site)['path']) ? parse_url($site)['path'] : ''; $urlPathName = str_replace("/", "", $urlPath); if ($siteStatus === "OK") { $filepath = $newDir . $urlHost . "_" . $urlPathName . ".jpg"; } elseif ($siteStatus === "404") { $filepath = $newDir . $urlHost . "_" . $urlPathName . "_" . $siteStatus . ".jpg"; } $client = Client::getInstance(); $client->getEngine()->setPath(base_path() . '/bin/phantomjs'); $width = $stats["width"]; $height = $stats["height"]; $top = 0; $left = 0; try { /** * @see JonnyW\PhantomJs\Message\CaptureRequest **/ $request = $client->getMessageFactory()->createCaptureRequest($site, 'GET'); if ($auth["status"] == true) { $request->addHeader('Authorization', 'Basic ' . base64_encode($auth["username"] . ":" . $auth["password"])); } $request->setDelay($delay); $request->setOutputFile($filepath); $request->setViewportSize($width, $height); /** * @see JonnyW\PhantomJs\Message\Response **/ $response = $client->getMessageFactory()->createResponse(); // Send the request $client->send($request, $response); } catch (\Exception $e) { // echo 'Caught exception: ', $e->getMessage(), "\n"; $this->exceptionLinks[] = $e->getMessage(); // push error links to array } }
/** * Execute the command. * * @return void */ public function handle() { $bookmark = $this->bookmark; $client = Client::getInstance(); $client->setBinDir(base_path('bin')); $client->addOption('--ignore-ssl-errors=true'); $client->addOption('--ssl-protocol=any'); $client->addOption('--web-security=false'); //$client->debug(true); $request = $client->getMessageFactory()->createCaptureRequest(); $response = $client->getMessageFactory()->createResponse(); $width = 800; $height = 800; $captureFile = public_path("images/screenshots/{$bookmark->id}.png"); $thumbFile = public_path("images/screenshots/{$bookmark->id}_thumb.png"); $request->setMethod('GET'); $request->setUrl($bookmark->url); $request->setCaptureFile($captureFile); $request->setCaptureDimensions($width, $height); $request->setViewportSize($width, $height); $timeout = 20000; // 20 seconds $request->setTimeout($timeout); //$delay = 5; // 5 seconds //$request->setDelay($delay); $client->send($request, $response); $status = $response->getStatus(); if ($status === 200 || $status === 301 || $status === 302) { $img = Image::make($captureFile); $img->widen(228)->crop(228, 160, 0, 0); $img->save($thumbFile); $bookmark->thumbnail = 1; $bookmark->save(); Log::info('TakeSnapshot completed. log:' . $client->getLog()); } else { Log::error('TakeSnapshot error. response status : ' . $status . ', log:' . $client->getLog()); } }
protected function execute(InputInterface $input, OutputInterface $output) { $app = $this->getProjectApplication(); $this->logger = $this->getLogger(); $this->regionService = $app['region.skyforge.service']; $this->regionService->setRegion($input->getOption('region')); $authData = $this->regionService->getAuthOptions(); $client = Client::getInstance(); // $client->getEngine()->debug(true); $client->getEngine()->addOption('--config=' . $app['config']['app']['path'] . '/phantomjs.json'); $client->getEngine()->setPath($app['config']['app']['path'] . '/../bin/phantomjs'); // $request = $client->getMessageFactory()->createCaptureRequest($authData['url'], $authData['method']); // $request->setRequestData($authData['data']); $request = $client->getMessageFactory()->createCaptureRequest('http://erliz.ru/', 'GET'); $response = $client->getMessageFactory()->createResponse(); $request->setDelay(5); $request->setViewportSize(1920, 1080); $request->setOutputFile($app['config']['app']['path'] . '/log/screen_test_' . time() . '.jpg'); $client->send($request, $response); if ($response->getStatus() === 200) { print_r($response->getContent()); } // print_r($client->getLog()); }
use JonnyW\PhantomJs\Client; use JonnyW\PhantomJs\DependencyInjection\ServiceContainer; // Create a file with a custom name // e.g. custom_procedure.proc and save it // somewhere. Set the parameters below to // the name of your file and the location of // your file. You can have many files in the // same location and you only need to create // 1 procedure loader with the path to your // files. The only restriction is the extension // your files must be .proc $fileName = 'custom_procedure'; $filePath = '/path/to/your/procedure/'; $serviceContainer = ServiceContainer::getInstance(); $procedureLoaderFactory = $serviceContainer->get('procedure_loader_factory'); $procedureLoader = $procedureLoaderFactory->createProcedureLoader($filePath); // Set the path to your custom procedure(s) $client = Client::getInstance(); $client->getProcedureLoader()->addLoader($procedureLoader); // Add new loader with path to you procedures to the chain loader $request = $client->getMessageFactory()->createRequest(); $response = $client->getMessageFactory()->createResponse(); $request->setType($fileName); // Set the request type to the name of your procedure you want to execute for this request $client->send($request, $response); var_dump($response); // If your debug log contains 'SyntaxError: Parse error' // then your custom procedure has a javascript error. Try // setting $client->debug(true) before making your request // to get more information about your error. var_dump($client->getLog());
/** * @return string */ public function Export() { $assetPath = ASSETS_PATH; $reflowPath = REFLOW_DIR; $deckSegment = $this->URLSegment; $manager = new ProcessManager(); $manager->setLogPath(ASSETS_PATH); $rule = new InMemoryRule(); $rule->setProcesses(5); $rule->setMinimumProcessorUsage(0); $rule->setMaximumProcessorUsage(100); $manager->addRule($rule); $manager->addTask(new ProcessCallbackTask(function () use($assetPath, $deckSegment) { exec("mkdir {$assetPath}/{$deckSegment}/export"); })); /** @var Slide $slide */ foreach ($this->Slides() as $slide) { $slideLink = $slide->AbsoluteLink("Capture"); $slideSegment = $slide->URLSegment; $link = rtrim($this->AbsoluteLink(), "/") . "#" . $slide->URLSegment; $manager->addTask(new ProcessCallbackTask(function () use($link, $assetPath, $reflowPath, $slideLink, $slideSegment, $deckSegment) { $client = Client::getInstance(); $client->setBinDir($reflowPath . "/../vendor/bin"); /** * @see JonnyW\PhantomJs\Message\CaptureRequest **/ $request = $client->getMessageFactory()->createCaptureRequest($link, "GET"); $request->setViewportSize(1440, 900); // TODO $request->setDelay(3); // TODO $request->setCaptureFile("{$assetPath}/{$deckSegment}/{$slideSegment}.png"); /** * @see JonnyW\PhantomJs\Message\Response **/ $response = $client->getMessageFactory()->createResponse(); // Send the request $client->send($request, $response); })); print "Exporting: " . $slide->Title . "<br>"; } $slides = []; /** @var Slide $slide */ foreach ($this->Slides() as $slide) { $slideSegment = $slide->URLSegment; $slides[] = "{$assetPath}/{$deckSegment}/export/{$slideSegment}.png"; } while ($manager->tick()) { usleep(10); } $manager->addTask(new ProcessCallbackTask(function () use($assetPath, $deckSegment, $slides) { $pdf = new FPDF(); /** @var Slide $slide */ foreach ($slides as $slide) { $pdf->AddPage("L", array(15 * 72, 9.380000000000001 * 72)); $pdf->Image($slide, 0, 0, 15 * 72, 9.380000000000001 * 72); } $pdf->Output("{$assetPath}/{$deckSegment}/export.pdf", "F"); })); while ($manager->tick()) { usleep(10); } }
/** * Test can get client through * factory method. * * @access public * @return void */ public function testCanGetClientThroughFactoryMethod() { $this->assertInstanceOf('\\JonnyW\\PhantomJs\\Client', Client::getInstance()); }
/** * Rasterizes an SVG image to a PNG. * * Uses phantomjs to save the SVG as a PNG image at the specified size. * * @access public * * @param string $file The path to the file that should be rasterized. * @param string $dest The path to the directory where the output PNG should be saved. * @param integer $columns The number of columns in the output image. 0 = maintain aspect ratio based on $rows. * @param integer $rows The number of rows in the output image. 0 = maintain aspect ratio based on $columns. */ public static function rasterize($file, $dest, $columns, $rows) { // check the input if (!file_exists($file)) { return false; } if (!file_exists($dest) || !is_dir($dest)) { return false; } // figure out the output width and height $svgTmp = new Respimg($file); $width = (double) $svgTmp->getImageWidth(); $height = (double) $svgTmp->getImageHeight(); $new_width = $columns; $new_height = $rows; $x_factor = $columns / $width; $y_factor = $rows / $height; if ($rows < 1) { $new_height = round($x_factor * $height); } elseif ($columns < 1) { $new_width = round($y_factor * $width); } // get the svg data $svgdata = file_get_contents($file); // figure out some path stuff $dest = rtrim($dest, '/'); $filename = substr($file, strrpos($file, '/') + 1); $filename_base = substr($filename, 0, strrpos($filename, '.')); // setup the request $client = Client::getInstance(); $serviceContainer = ServiceContainer::getInstance(); $procedureLoaderFactory = $serviceContainer->get('procedure_loader_factory'); $procedureLoader = $procedureLoaderFactory->createProcedureLoader(__DIR__); $client->getProcedureLoader()->addLoader($procedureLoader); $request = new RespimgCaptureRequest(); $request->setType('svg2png'); $request->setMethod('GET'); $request->setSVG(base64_encode($svgdata)); $request->setViewportSize($new_width, $new_height); $request->setRasterFile($dest . '/' . $filename_base . '-w' . $new_width . '.png'); $request->setWidth($new_width); $request->setHeight($new_height); $response = $client->getMessageFactory()->createResponse(); // send + return $client->send($request, $response); return true; }
/** * Get procedure loader. * * @access protected * @return \JonnyW\PhantomJs\Procedure\ProcedureLoader */ protected function getProcedureLoader() { return Client::getInstance()->getProcedureLoader(); }
/** * Test get instance returns instance * of client. * * @access public * @return void */ public function testGetInstanceReturnsInstanceOfClient() { $this->assertInstanceOf('\\JonnyW\\PhantomJs\\Client', Client::getInstance()); }
/** * Perform the actual download. * * @param string $url * @param int $delay * @param bool $opendata * * @return array */ private function doDownload($url, $delay = 5, $opendata = false) { $client = PJClient::getInstance(); if ($this->proxyManager->useProxy()) { $client->addOption('--proxy=' . $this->proxyManager->getProxyAddress()); } $client->addOption('--load-images=false'); $request = $client->getMessageFactory()->createRequest($this->fullURL($url, true, $opendata)); $request->setDelay($delay); $request->setTimeout(60000); $request->addHeader('User-Agent', $this->identity->getUserAgent($opendata)); $response = $client->getMessageFactory()->createResponse(); $client->send($request, $response); $status = $response->getStatus(); $html = $response->getContent(); sleep(max(10, min(0, $this->proxyManager->getProxyLastUsageTime() + 10000 - time()))); return ['status' => $status, 'html' => preg_replace('|charset="?windows-1251"?|u', 'charset="utf-8"', $html)]; }
/** * Get client instance. * * @return \JonnyW\PhantomJs\Client */ protected function getClient() { return Client::getInstance(); }