Zend_Service_Twitter & Zend_Oauth_Token_Access behind proxy? - http

I'm currently stuck with some of Zend's methods, im trying to make a simple Zend_Service_Twitter request through a proxy, however i keep getting:
Unable to Connect to tcp://api.twitter.com:80. Error #0:
php_network_getaddresses: gethostbyname failed.
I am able to do http calls with the Zend_Http_Client library by itself, so I believe my problem is with the code where I pass the httpClient instance to the Zend_Service_Twitter... But enough rant i guess, basically I have the following:
$config = array(
'adapter' => 'Zend_Http_Client_Adapter_Proxy',
'proxy_host' => self::PROXY_HOST,
'proxy_port' => self::PROXY_PORT,
'timeout' => 240,
);
$httpClient = new Zend_Http_Client(self::TWITTER_API_URL, $config);
$token = new Zend_Oauth_Token_Access;
$token->setParams(array(
Zend_Oauth_Token_Access::TOKEN_PARAM_KEY => self::TWITTER_OAUTH_TOKEN,
Zend_Oauth_Token_Access::TOKEN_SECRET_PARAM_KEY => self::TWITTER_OAUTH_TOKEN_SECRET
));
$twitter = new Zend_Service_Twitter(array(
'username' => 'MYUSERNAME',
'accessToken' => $token
));
$twitter->getHttpClient($httpClient);
$response = $twitter->account->rateLimitStatus();
Any pointers would be appreciated!

While taking a closer look at the Zend_Service_Twitter class, all you need to do in order to set up the proxy parameters is this:
$twitter = new Zend_Service_Twitter(array(
'username' => 'MYUSERNAME',
'accessToken' => $token
));
$twitter->setLocalHttpClient($twitter->getHttpClient($httpClient));
($httpClient being an instance of Zend_Http_Client which contains your proxy configuration)

Related

Symfony 5 httpClient Windows AD connection

Is it possible to connect to an API with windows Credentials?
I need to connect on an API witch uses Windows AD authentication.
I thought thats works with auth_basic but it's not the good way...
Thanks by advance for your answers
$httpClient = HttpClient::create([
'auth_basic' => ['username', 'password']
]);
$response = $httpClient->request('GET', 'https://apiURL', [
'headers' => ['accept' => 'text/plain'],
]);
dump($response->getStatusCode());
dump($response);
Yes, it's possibile using the auth_ntlm option. But this option is supported only by the cURL client, so you must have the cURL PHP extension installed and enabled in your system.
Here's the code:
$httpClient = new CurlHttpClient(['auth_ntlm' => "username:password"]);
$response = $httpClient->request('GET', 'https://apiURL', [
'headers' => ['accept' => 'text/plain'],
]);
dump($response->getStatusCode());
dump($response);

401(woocommerce_api_user_cannot_read_product) response--Woocommerce REST API

the API works when ck_ and cs_ keys are for Admin and returns the std class object but when keys are for a different user returns You do not have permission to read this product 401(woocommerce_api_user_cannot_read_product) Error response: even when user has read/write privileges. but goes ahead to create the product in the database. Any help on this issue is highly appreciated
require_once( 'lib/woocommerce-api.php' );
$options = array(
'debug' => true,
'return_as_array' => false,
'validate_url' => false,
'timeout' => 30,
'ssl_verify' => false,
);
try {
$client = new WC_API_Client( $the_url, 'ck_xxxx', 'cs_xxxx', $options);
Try adding into your $options array:
$options['query_string_auth'] = true;
As noted in the documentation this will "Force Basic Authentication as query string true" in other words it will append your consumer key and consumer secret to your request URL as a query string. This is only supported on HTTPS.

FMElfinderBundle 5 - how to set temp folder for upload

I am using FMElfinderBundle v.5 (for some reasons I cannot use latest version) with Symfony 2.8.12. I followed documentation and it worked fine, until there was request to allow upload large files (up to 20MB). I changed upload_max_size parameter to 20M and it was ok, but during upload files are split to 2MB chunks and elfinder tries to store them in temp directory. Problem is, that it has no access there. It does not read settings from virtual host definition, it always uses system temp folder.
Reading documentation I have found that there can be used two parameters for configuring elfinder temp dir - upload_temp_path and common_temp_path. But i didn't have luck with setting them. Every time I run in PHPStorm console command s cache: clear --no-warmup I get InvalidConfigurationException.
I tried to put parameters somewhere else in config structure under fm_elfinder key, but still the same exception.
This is my configuration in config.yml:
fm_elfinder:
instances:
default:
locale: %locale%
editor: ckeditor
fullscreen: true
theme: smoothness
include_assets: true
relative_path: false
connector:
roots:
uploads:
driver: LocalFileSystem
path: uploads
upload_max_size: 20M
Anyone please can help me, how to set temp dir?
Ok, some detailed info:
I took ElFinderConfigurationReader from ElFinder bundle and saved it into my project under name ElFinderConfigurationCustomReader. Then this class i defined as a service:
service.custom_fm_elfinder.configurator:
class: CSBN\SVJBundle\Component\ElFinder\ElFinderConfigurationCustomReader
arguments: ['%fm_elfinder%', '#request_stack', '#service_container', '%elfinder_temporary_path%']
variable elfinder_temporary_path is set in parameters.yml.
in config.yml i set my own configuration reader:
fm_elfinder:
configuration_provider: service.custom_fm_elfinder.configurator
And in my newly created file ElFinderConfigurationCustomReader i just in method getConfiguration added one row:
$options['uploadTempPath'] = $this->temporaryPath;
which is taken from service parameters in constructor.
Hope this helps you.
Edit: full function copy:
/**
* #param $instance
*
* #return array
*/
public function getConfiguration($instance)
{
$request = $this->requestStack->getCurrentRequest();
$efParameters = $this->parameters;
$parameters = $efParameters['instances'][$instance];
$options = array();
$options['corsSupport'] = $parameters['cors_support'];
$options['debug'] = $parameters['connector']['debug'];
$options['bind'] = $parameters['connector']['binds'];
$options['plugins'] = $parameters['connector']['plugins'];
$options['uploadTempPath'] = $this->temporaryPath;
$options['roots'] = array();
foreach ($parameters['connector']['roots'] as $parameter) {
$path = $parameter['path'];
$homeFolder = $request->attributes->get('homeFolder');
if ($homeFolder !== '') {
$homeFolder = '/'.$homeFolder.'/';
}
$driver = $this->container->has($parameter['driver']) ? $this->container->get($parameter['driver']) : null;
$driverOptions = array(
'driver' => $parameter['driver'],
'service' => $driver,
'glideURL' => $parameter['glide_url'],
'glideKey' => $parameter['glide_key'],
'plugin' => $parameter['plugins'],
'path' => $path.$homeFolder, //removed slash for Flysystem compatibility
'startPath' => $parameter['start_path'],
'URL' => $this->getURL($parameter, $request, $homeFolder, $path),
'alias' => $parameter['alias'],
'mimeDetect' => $parameter['mime_detect'],
'mimefile' => $parameter['mimefile'],
'imgLib' => $parameter['img_lib'],
'tmbPath' => $parameter['tmb_path'],
'tmbPathMode' => $parameter['tmb_path_mode'],
'tmbUrl' => $parameter['tmb_url'],
'tmbSize' => $parameter['tmb_size'],
'tmbCrop' => $parameter['tmb_crop'],
'tmbBgColor' => $parameter['tmb_bg_color'],
'copyOverwrite' => $parameter['copy_overwrite'],
'copyJoin' => $parameter['copy_join'],
'copyFrom' => $parameter['copy_from'],
'copyTo' => $parameter['copy_to'],
'uploadOverwrite' => $parameter['upload_overwrite'],
'uploadAllow' => $parameter['upload_allow'],
'uploadDeny' => $parameter['upload_deny'],
'uploadMaxSize' => $parameter['upload_max_size'],
'defaults' => $parameter['defaults'],
'attributes' => $parameter['attributes'],
'acceptedName' => $parameter['accepted_name'],
'disabled' => $parameter['disabled_commands'],
'treeDeep' => $parameter['tree_deep'],
'checkSubfolders' => $parameter['check_subfolders'],
'separator' => $parameter['separator'],
'timeFormat' => $parameter['time_format'],
'archiveMimes' => $parameter['archive_mimes'],
'archivers' => $parameter['archivers'],
);
if ($parameter['volume_id'] > 0) {
$driverOptions['id'] = $parameter['volume_id'];
}
if (!$parameter['show_hidden']) {
$driverOptions['accessControl'] = array($this, 'access');
};
$options['roots'][] = array_merge($driverOptions, $this->configureDriver($parameter));
}
return $options;
}
Ok, i have found solution. It is necessary to make yoour own custom configuration reader and replace the original one. Configuration class must implement ElFinderConfigurationProviderInterface. See [https://github.com/helios-ag/FMElfinderBundle/blob/master/Resources/doc/advanced-configuration.md#custom-configuration-provider][1] for more details.

Laravel Cashier fake user subscription for tests

I'm using Laravel's Cashier for billing which is great. I'm trying to be good and keep my code tested but I'm having trouble "faking" a user with a subscription.
I've tried:
$user = App\Models\User::create([
'first_name' => $this->faker->firstName,
'last_name' => $this->faker->lastName,
'email' => $this->faker->email,
'password' => 'password1234',
'stripe_plan' => 'name_of_plan',
'stripe_active' => 1
]);
$this->be($user);
But if I then check $user->onPlan('name_of_plan') I get false :(
Is there a way to do this? As I'm sure you can appreciate I don't really want to launch the payment system until I've got tests to back it up!
Check that 'stripe_plan' and 'stripe_active' are defined as fillable for User. If they aren't then it may not be actually setting those values in User::create() which is why your test fails.
class User extends Model implements AuthenticatableContract, CanResetPasswordContract, BillableContract {
use Authenticatable, CanResetPassword, Billable;
protected $table = 'users';
protected $fillable = [
'first_name',
'last_name',
'email',
'password',
'stripe_plan',
'stripe_active'
];
}

Testing File uploads in Symfony2

In the Symfony2 documentation it gives the simple example of:
$client->request('POST', '/submit', array('name' => 'Fabien'), array('photo' => '/path/to/photo'));
To simulate a file upload.
However in all my tests I am getting nothing in the $request object in the app and nothing in the $_FILES array.
Here is a simple WebTestCase which is failing. It is self contained and tests the request that the $client constructs based on the parameters you pass in. It's not testing the app.
class UploadTest extends WebTestCase {
public function testNewPhotos() {
$client = $this->createClient();
$client->request(
'POST',
'/submit',
array('name' => 'Fabien'),
array('photo' => __FILE__)
);
$this->assertEquals(1, count($client->getRequest()->files->all()));
}
}
Just to be clear. This is not a question about how to do file uploads, that I can do. It is about how to test them in Symfony2.
Edit
I'm convinced I'm doing it right. So I've created a test for the Framework and made a pull request.
https://github.com/symfony/symfony/pull/1891
This was an error in the documentation.
Fixed here:
use Symfony\Component\HttpFoundation\File\UploadedFile;
$photo = new UploadedFile('/path/to/photo.jpg', 'photo.jpg', 'image/jpeg', 123);
// or
$photo = array('tmp_name' => '/path/to/photo.jpg', 'name' => 'photo.jpg', 'type' => 'image/jpeg', 'size' => 123, 'error' => UPLOAD_ERR_OK);
$client = static::createClient();
$client->request('POST', '/submit', array('name' => 'Fabien'), array('photo' => $photo));
Documentation here
Here is a code which works with Symfony 2.3 (I didn't tried with another version):
I created an photo.jpg image file and put it in Acme\Bundle\Tests\uploads.
Here is an excerpt from Acme\Bundle\Tests\Controller\AcmeTest.php:
function testUpload()
{
// Open the page
...
// Select the file from the filesystem
$image = new UploadedFile(
// Path to the file to send
dirname(__FILE__).'/../uploads/photo.jpg',
// Name of the sent file
'filename.jpg',
// MIME type
'image/jpeg',
// Size of the file
9988
);
// Select the form (adapt it for your needs)
$form = $crawler->filter('input[type=submit]...')->form();
// Put the file in the upload field
$form['... name of your field ....']->upload($image);
// Send it
$crawler = $this->client->submit($form);
// Check that the file has been successfully sent
// (in my case the filename is displayed in a <a> link so I check
// that it appears on the page)
$this->assertEquals(
1,
$crawler->filter('a:contains("filename.jpg")')->count()
);
}
Even if the question is related to Symfony2, it appears in the top results when searching for Symfony4 in Google.
Instancing an UploadedFile works, but the shortest way I found was also actually in the official documentation:
$crawler = $client->request('GET', '/post/hello-world');
$buttonCrawlerNode = $crawler->selectButton('submit');
$form = $buttonCrawlerNode->form();
$form['photo']->upload('/path/to/lucas.jpg');
https://symfony.com/doc/current/testing.html#forms
I found this article, https://coderwall.com/p/vp52ew/symfony2-unit-testing-uploaded-file, and works perfect.
Regards
if you want to mock a UploadedFile without a client request, you can use:
$path = 'path/to/file.test';
$originalName = 'original_name.test';
$file = new UploadedFile($path, $originalName, null, UPLOAD_ERR_OK, true);
$testSubject->method($file);

Resources