How can I use cloudflare-bypass? - guzzle

I want to use the
Cloudflare-bypass.
I am using https://github.com/jaymoulin/guzzlehttp-cloudflare/.
This is my code
$sUrl = 'https://thebot.net/';
$oClient = new \GuzzleHttp\Client([
'cookies' => new \GuzzleHttp\Cookie\FileCookieJar( tempnam('/tmp', __CLASS__) ),
'headers' => ['Referer' => $sUrl],
]); // 1. Create Guzzle instance
$aOptions = [
'cache' => new \CloudflareBypass\Storage( '/tmp' ),
]; // Example for cache, this is completely optional, with $sPathToYourCacheFolder a string to your cache folder
/** #var \GuzzleHttp\HandlerStack $oHandler */
$oHandler = $oClient->getConfig('handler');
$oHandler->push(\GuzzleCloudflare\Middleware::create($aOptions)); //2. ???
echo (string)$oClient->request('GET', $sUrl)->getBody(); //3. Profit!!
Error:-
Fatal error: Uncaught Error: Class 'CloudflareBypass\Storage' not found in
Does anyone know how can I use this correctly?
Also, Can I use cookies with the Cloudflare-bypass?

The cache is optional, try with $aOptions = []; instead.

Related

Zend_Cache understanding issue

I try to use Zend_Cache (first try) to save information about user grants. The idea and most of the source code comes from Oleg Krivtsovs tutorial.
I get an error, if I try to retrieve my cache.
Call to a member function getItem() on array
Here the implementation of FilesystemCache, in my global.php
'caches' => [
'FilesystemCache' => [
'adapter' => [
'name' => Filesystem::class,
'options' => [
// Store cached data in this directory.
'cache_dir' => './data/cache',
// Store cached data for 1 hour.
'ttl' => 60*60*1
],
],
'plugins' => [
[
'name' => 'serializer',
'options' => [
],
],
],
],
],
Here my factory class:
<?php
namespace User\Service;
use User\Controller\Plugin\AuthPlugin;
use User\Model\GrantsTable;
use User\Model\UserTable;
use Zend\Authentication\AuthenticationService;
use Zend\ServiceManager\Factory\FactoryInterface;
use Interop\Container\ContainerInterface;
class AccessControlFactory implements FactoryInterface {
public function __invoke(ContainerInterface $container, $requestedName, array $options = null) {
$config = $container->get('config');
$userTable = $container->get(UserTable::class);
$grantsTable = $container->get(GrantsTable::class);
$cache = $config['caches']['FilesystemCache'];
$userplugin = $container->get(AuthPlugin::class);
// $authentication = $container->get( \Zend\Authentication\AuthenticationService::class);
return new AccessControl($userTable, $grantsTable, $cache, $userplugin);//, $authentication
}
}
Now in the init function within my AccessControl Service, I try to retrieve from the cache:
$this->cache->getItem('rbac_container', $result);
There I get the above error.
Any help with a bit of explanation would be appreciated.
What you're injecting to the AccessControl constructor is an array, not a cache implementation, because $config['caches']['FilesystemCache'] returns an array of FilesystemCache options (adapter, plugins, etc.). What you're supposed to do is fetch the cache implementation via the ContainerInterface, like this:
$cache = $container->get('FilesystemCache');
Then the ContainerInterface will depend on StorageCacheAbstractServiceFactory to find your requested cache configs and return the class for you.

How to get the query parameters in a Guzzle/ Psr7 request

I am using Guzzle 6.
I am trying to mock a client and use it like so:
<?php
use GuzzleHttp\Client;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
$mock_handler = new MockHandler([
new Response(200, ['Content-Type' => 'application/json'], 'foo'),
]);
$history = [];
$history_middleware = Middleware::history($history);
$handler_stack = HandlerStack::create($mock_handler);
$handler_stack->push($history_middleware);
$mock_client = new Client(['handler' => $handler_stack]);
// Use mock client in some way
$mock_client->get("http://example.com", [
'query' => [
'bar' => '10',
'hello' => '20'
],
]);
// ------
// get original request using history
$transaction = $history[0];
/** #var Request $request */
$request = $transaction['request'];
// How can I get the query parameters that was used in the request (i.e. bar)
My question is how can I get the query parameters used in the GuzzleHttp\Psr7\Request class?
The closest I managed to get is the following: $request->getUri()->getQuery(), but this just returns a string like so: bar=10&hello=20.
I seem to have solved my problem.
I can simply do this:
parse_str($request->getUri()->getQuery(), $query);
and I now have an array of the query parameters.
Other solutions are welcome!

Multiple duplicate uri parameters in GuzzleHttp

I am accessing the Echo Nest API, which requires me to repeat the same uri parameter name bucket. However I can't make this work in Guzzle 6. I read a similar issue from 2012, however the approach does not work.
I have tried adding it manually into the query string without any success.
A sample API call could be:
http://developer.echonest.com/api/v4/song/search?format=json&results=10&api_key=someKey&artist=Silbermond&title=Ja&bucket=id:spotify&bucket=tracks&bucket=audio_summary
Here's my example Client:
/**
* #param array $urlParameters
* #return Client
*/
protected function getClient()
{
return new Client([
'base_uri' => 'http://developer.echonest.com/api/v4/',
'timeout' => 5.0,
'headers' => [
'Accept' => 'application/json',
],
'query' => [
'api_key' => 'someKey',
'format' => 'json',
'results' => '10',
'bucket' => 'id:spotify' // I need multiple bucket parameter values with the 'bucket'-name
]);
}
/**
* #param $artist
* #param $title
* #return stdClass|null
*/
public function searchForArtistAndTitle($artist, $title)
{
$response = $this->getClient()->get(
'song/search?' . $this->generateBucketUriString(),
[
'query' => array_merge($client->getConfig('query'), [
'artist' => $artist,
'title' => $title
])
]
);
// ...
}
Can you help me?
In the Guzzle 6 you are not allowed to pass any aggregate function anymore. Whenever you will pass an array to the query config it will be serialized with the http_build_query function:
if (isset($options['query'])) {
$value = $options['query'];
if (is_array($value)) {
$value = http_build_query($value, null, '&', PHP_QUERY_RFC3986);
}
To avoid it you should serialize a query string by your own and pass it as string.
new Client([
'query' => $this->serializeWithDuplicates([
'bucket' => ['id:spotify', 'id:spotify2']
]) // serialize the way to get bucket=id:spotify&bucket=id:spotify2
...
$response = $this->getClient()->get(
...
'query' => $client->getConfig('query').$this->serializeWithDuplicates([
'artist' => $artist,
'title' => $title
])
...
);
Otherwise you could pass into the handler option an adjusted HandlerStack that will have in its stack your Middleware Handler. The one will read some new config param, say, query_with_duplicates, build acceptable Query String and modify Request's Uri with it accordingly.
I had the same need today, but now we are on Guzzle 7, the easiest way of getting duplicates for params (bucket=value1&bucket=value2&bucket=value3...) is to use the Query Build method. For this to work do the following:
// Import the class
use GuzzleHttp\Psr7\Query;
Example params
$params = [
'bucket' => 'value1',
'bucket' => 'value2',
'bucket' => 'value3',
];
Then when passing the params array to the query key, first pass it through the Query::build method
$response = $client->get('/api', [
'query' => Query::build($params),
]);

Typo3: How to upload a file and create a file reference?

i'll try to upload a file (or later multiple files) in FE. This works, like my current code. But how can i get a file reference of this file now?
/**
*
* #var array $fileData
* #var integer $feUserId
* #return \TYPO3\CMS\Extbase\Domain\Model\FileReference
*/
private function uploadFile($fileData, $feUserId) {
$storageRepository = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Resource\\StorageRepository');
$storage = $storageRepository->findByUid(1); # Fileadmin = 1
$saveFolder = $storage->getFolder($this->settings['uploadFolder']);
// Datei speichern
$fileObject = $storage->addFile($fileData['tmp_name'], $saveFolder, $feUserId.'_'.$fileData['name']);
// Dateiobjekt
$repositoryFileObject = $storage->getFile($fileObject->getIdentifier());
die(\TYPO3\CMS\Extbase\Utility\DebuggerUtility::var_dump($repositoryFileObject));
#$newFileReference = $this->objectManager->get('TYPO3\CMS\Extbase\Domain\Model\FileReference');
#$newFileReference->setOriginalResource($repositoryFileObject);
return $newFileReference;
}
There should be something like »setFileReference« by now, but I can not find the like in the API http://typo3.org/api/typo3cms/class_t_y_p_o3_1_1_c_m_s_1_1_core_1_1_resource_1_1_file_reference.html
Well, you may wanna use the following script as temporary solution, which uses the datamap process to create file references.
$sys_file_uid = $file->getUid();
$tt_content_uid = 42;
$tt_content_pid = 1337;
// Do not directly insert a record into sys_file_reference, as this bypasses all sanity checks and automatic updates done!
$data = array();
$data['sys_file_reference']['NEW' . $sys_file_uid] = array(
'uid_local' => $sys_file_uid,
'table_local' => 'sys_file',
'uid_foreign' => $tt_content_uid,
'tablenames' => 'tt_content',
'fieldname' => 'image',
'pid' => $tt_content_pid,
);
$data['tt_content'][$tt_content_uid] = array('image' => 'NEW' . $sys_file_uid);
$tce = t3lib_div::makeInstance('t3lib_TCEmain'); // create TCE instance
$tce->start($data, array());
$tce->process_datamap();
if ($tce->errorLog) {
// Error - Reference not created
// t3lib_utility_Debug::viewArray($tce->errorLog);
}
else {
// Success - Reference created
}
after hitting google for a while i figured out a article that sounded quite well to me.. gonna examine it tomorrow:
http://insight.helhum.io/post/85015526410/file-upload-using-extbase-and-fal-in-typo3-6-2
(just in case somebody else needs this before i could test it)

Phalcon Paginator error: Syntax error, unexpected EOF

my problem is, every time I click in the paginator link in the view, the controller returns me this error:
Syntax error, unexpected EOF
What is this? EOF?
My controller:
$domicilios = Domicilios::find();
$paginator = new \Phalcon\Paginator\Adapter\Model(
array(
"data" => $domicilios,
"limit"=> 5,
"page" => $currentPage
)
);
$pagina = $paginator->getPaginate();
$this->view->setVar("estado", $estado);
$this->view->setVar("pagina", $pagina);
The content in the model Domicilios is returning right, but why the paginator keeps returning this error?
Thanks in advance!
EOF is end of file. there might be several issues. 1stly if you upload this file to server, there might be problems with upload process and file is not fully uploaded and you have broken end of file (EOF).
try converting your php file to utf8. you can do it with notepad++ and many other programs.
here are my working pagination:
$page = $this->request->get('page', 'int', 1);
$this->view->page = $page;
if ($page < 1) {
$page = 1;
}
$user = $this->session->get('auth');
$questions = Model_UserQuestion::find(array(
'user_id=:user_id:',
'bind' => array('user_id' => $user['id']),
"order" => "id DESC",
));
// Create a Model paginator, show 10 rows by page starting from $currentPage
$paginator = new \Phalcon\Paginator\Adapter\Model(
array(
"data" => $questions,
"limit" => $this->config->application->itemsPerPage,
"page" => $page
)
);
$page = $paginator->getPaginate();
$this->view->questions = $page->items;
notice that to get items you have to use this:
$page->items