Testing File uploads in Symfony2 - symfony

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);

Related

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.

Facebook post wirth php error: (#200) The user hasn't authorized the application to perform this action

i want to post from my website to my facebook site. i have created a app for my site. I use this code (i replace data from my app with '[]'):
require_once 'lib/php-graph-sdk-5.4/src/Facebook/autoload.php';
// initialize Facebook class using your own Facebook App credentials
// see: https://developers.facebook.com/docs/php/gettingstarted/#install
$access_token = '[aaccesstoken]';
$config = array();
$config['app_id'] = '[appid]';
$config['app_secret'] = '[appsecret]';
$config['fileUpload'] = false; // optional
$fb = new \Facebook\Facebook($config);
// define your POST parameters (replace with your own values)
$params = array(
"access_token" => $access_token, // see: https://developers.facebook.com/docs/facebook-login/access-tokens/
"message" => "Test Message",
"link" => "http://www.frauen-styles.de",
"picture" => "http://www.frauen-styles.de/site/assets/files/3545/20.jpg",
"name" => "Test Name",
"caption" => "Caption",
"description" => "Beschreibung"
);
// post to Facebook
// see: https://developers.facebook.com/docs/reference/php/facebook-api/
try {
$ret = $fb->post('/me/feed', $params);
echo 'Successfully posted to Facebook';
} catch(Exception $e) {
echo $e->getMessage();
}
what i'm doing wrong? im administrator of the page. support tells me that no publish_pages is requiered for the app for admins. I only want to send a post from my website to my facebook-page.
support tells me that no publish_pages is requiered
As you can read in the API reference in the official docs, you do need publish_pages and manage_pages to post to a Page (as Page).
Docs: https://developers.facebook.com/docs/graph-api/reference/page/feed#publish

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.

Edit include/mail.inc, add my own SMTP setting there

The following function is contained in include/mail.inc of Drupal6, it uses the default SMTP settings buried in a file named "php.ini" to send mail.
function drupal_mail_send($message) {
// Allow for a custom mail backend.
if (variable_get('smtp_library', '') && file_exists(variable_get('smtp_library', ''))) {
include_once './'. variable_get('smtp_library', '');
return drupal_mail_wrapper($message);
}
else {
$mimeheaders = array();
foreach ($message['headers'] as $name => $value) {
$mimeheaders[] = $name .': '. mime_header_encode($value);
}
return mail(
$message['to'],
mime_header_encode($message['subject']),
// Note: e-mail uses CRLF for line-endings, but PHP's API requires LF.
// They will appear correctly in the actual e-mail that is sent.
str_replace("\r", '', $message['body']),
// For headers, PHP's API suggests that we use CRLF normally,
// but some MTAs incorrecly replace LF with CRLF. See #234403.
join("\n", $mimeheaders)
);
}
}
but I use shared host, therefore i can't edit php.ini, i want to edit the above function "drupal_mail_send", add the codes below into that function so that it can bypass the PHP mail() function and send email directly to my favorite SMTP server.
include('Mail.php');
$recipients = array( 'someone#example.com' ); # Can be one or more emails
$headers = array (
'From' => 'someone#example.com',
'To' => join(', ', $recipients),
'Subject' => 'Testing email from project web',
);
$body = "This was sent via php from project web!\n";
$mail_object =& Mail::factory('smtp',
array(
'host' => 'prwebmail',
'auth' => true,
'username' => 'YOUR_PROJECT_NAME',
'password' => 'PASSWORD', # As set on your project's config page
#'debug' => true, # uncomment to enable debugging
));
$mail_object->send($recipients, $headers, $body);
Could you write down the modified code for my reference?
The code in drupal_mail_send is part o the Drupal core functionality and should not be changed directly as your changes may be overwritten when you update Drupal.
Modifications of Drupal core files is often referred to by the Drupal community as "hacking core" and is largely discouraged.
Drupal already has a number of modules available which may help you. See:
http://drupal.org/project/phpmailer module:
Adds SMTP support for sending e-mails using the PHPMailer library.
Comes with detailed configuration instructions for how to use Google
Mail as mail server.
http://drupal.org/project/smtp module:
This module allows Drupal to bypass the PHP mail() function and send
email directly to an SMTP server.

Zend_Service_Twitter & Zend_Oauth_Token_Access behind proxy?

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)

Resources