So I'm having issues on getting the blobs inside my container - I'm able to successfully grab all the blobs inside a container, but not inside a folder in the container - How would I be able to successfully do that?
Problem:
I have a folder inside my container called 'big/' - How would I be able to grab all the blobs from that folder instead of just the generic container as I'm doing below?
All help would be appreciated!
So here is the getBlobs() method that I have (View the image and code below):
/**
* Get all blobs from container
*
* #param int $max
* #return array
*/
public function getBlobs(int $max = 5000) : array
{
// Check if a container is set
if (!$this->containerName) {
return [];
}
try {
$blobMeta = [];
$blobOptions = new ListBlobsOptions();
// Set the max results at 5000 (Default: 5000)
$blobOptions->setMaxResults($max);
do {
// Grab the defined container
$blob_list = $this->connect()->listBlobs(
$this->containerName,
$blobOptions
);
var_dump($blob_list);
die();
// Loop through all the
foreach ($blob_list->getBlobs() as $blob) {
$blobMeta[] = [
'name' => $blob->getName(),
'url' => $blob->getUrl(),
];
}
$blobOptions->setContinuationToken($blob_list->getContinuationToken());
} while ($blob_list->getContinuationToken());
return $blobMeta;
} catch (ServiceException $e) {
$code = $e->getCode();
$error_message = $e->getMessage();
echo $code . ": " . $error_message . PHP_EOL;
return [];
}
}
If you want to list blobs under a folder, you can use ListBlobsOptions to setPrefix("YourFolderName/") to do this. You can find a detailed code sample in listBlobsSample function at line 430 here.
Related
for the command to work it needs 3 permissions, but how could I reduce its size and simplify it for it to identify the missing ones and send a list, and not go from one in one?
e.g.
list = {
USE_EXTERNAL_EMOJIS: 'use external emojis',
EMBED_LINKS: 'embed links',
READ_MESSAGE_HISTORY: 'read message history'
}
CODE:
if (!message.channel.permissionsFor(client.user).has('USE_EXTERNAL_EMOJIS' && 'EMBED_LINKS')) {
return message.channel.send('missing permissions use external emojis and embed links');
}
if (!message.channel.permissionsFor(client.user).has('EMBED_LINKS')) {
return message.channel.send('missing permission embed links');
}
if (!message.channel.permissionsFor(client.user).has('USE_EXTERNAL_EMOJIS')) {
return message.message.channel.send('missing permission use external emojis');
}
if (!message.channel.permissionsFor(client.user).has('READ_MESSAGE_HISTORY')) {
return message.channel.send('missing permission read message history');
}
You can use Object.entries() to get an iterable array of key - value pairs and use a method like this
const neededPermsObj = {
USE_EXTERNAL_EMOJIS: 'use external emojis',
EMBED_LINKS: 'embed links',
READ_MESSAGE_HISTORY: 'read message history'
}
const missingPerms = [];
for (const [key, value] of Object.entries(neededPermsObj)) {
if (!message.channel.permissionsFor(client.user).has(key.toString())) {
missingPerms.push(`${key}: ${value}`)
}
}
if (missingPerms.length != 0) return message.channel.send(missingPerms.join('\n')); // prevent from running cmd
else // execute command code here
This would check if bot has the specified permissions from the object provided, and will return an array with all the missing permissions
Hello i am trying to create img filter there are Range input sliders from which user select filter value and then applied to selected image object its working but every time input changes it added a new filter and multiply how can i resolve this issue below is my code:
$('.img-fillter-controller .range-field').on("change", "input", function () {
t = $(this).data("filter");
v = $(this).val();
o = activeCanvas.getActiveObject();
switch(t) {
case 'brightness':
f = new fabric.Image.filters.Brightness({brightness: v/100 });
applyImgFilter(f);
return;
case 'saturation':
return;
case 'contrast':
return;
case 'blur':
return;
case 'exposure':
return;
case 'colorify':
return;
case 'hue':
}
});
function applyImgFilter(f) {
o.filters.push(f);
o.applyFilters();
activeCanvas.renderAll();
}
For apply filter properly on image, we need to fix filter index or can say that assign filter by static index.
You should replace This funciton :
function applyImgFilter(f) {
o.filters.push(f);
o.applyFilters();
activeCanvas.renderAll();
}
With New funciton :
function applyImgFilter(f) {
o.filters[0] = f
o.applyFilters();
activeCanvas.renderAll();
}
I'm working on a Symfony 3 website and I need to call a URL of my website with a cron job.
My website is hosted on OVH where I can configure my cron job.
For now, I have setup the command : ./demo/Becowo/batch/emailNewUser.php
emailNewUser.php content :
<?php
header("Location: https://demo.becowo.com/email/newusers");
?>
In the log I have :
[2017-03-07 08:08:04] ## OVH ## END - 2017-03-07 08:08:04.448008 exitcode: 0
[2017-03-07 09:08:03] ## OVH ## START - 2017-03-07 09:08:03.988105 executing: /usr/local/php5.6/bin/php /homez.2332/coworkinwq/./demo/Becowo/batch/emailNewUser.php
But emails are not sent.
How should I configure my cron job to execute this URL ?
Or should I call directly my controller ? How ?
ok, finally it works !!!
Here are the step I followed for others :
1/ You need a controller to send emails :
As the controller will be called via command, you need to injec some services
em : entity manager to flush data
mailer : to access swiftMailer service to send the email
templating : to access TWIG service to use template in the email body
MemberController.php
<?php
namespace Becowo\MemberBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Becowo\CoreBundle\Form\Type\ContactType;
use Becowo\CoreBundle\Entity\Contact;
use Doctrine\ORM\EntityManager;
use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface;
class MemberController extends Controller
{
private $em = null;
private $mailer = null;
private $templating = null;
private $appMember = null;
public function __construct(EntityManager $em, $mailer, EngineInterface $templating, $appMember)
{
$this->em = $em;
$this->mailer = $mailer;
$this->templating = $templating;
$this->appMember = $appMember;
}
public function sendEmailToNewUsersAction()
{
// To call this method, use the command declared in Becowo\CronBundle\Command\EmailNewUserCommand
// php bin/console app:send-email-new-users
$members = $this->appMember->getMembersHasNotReceivedMailNewUser();
$nbMembers = 0;
$nbEmails = 0;
$listEmails = "";
foreach ($members as $member) {
$nbMembers++;
if($member->getEmail() !== null)
{
$message = \Swift_Message::newInstance()
->setSubject("Hello")
->setFrom(array('toto#xxx.com' => 'Contact Becowo'))
->setTo($member->getEmail())
->setContentType("text/html")
->setBody(
$this->templating->render(
'CommonViews/Mail/NewMember.html.twig',
array('member' => $member)
))
;
$this->mailer->send($message);
$nbEmails++;
$listEmails = $listEmails . "\n" . $member->getEmail() ;
$member->setHasReceivedEmailNewUser(true);
$this->em->persist($member);
}
}
$this->em->flush();
$result = " Nombre de nouveaux membres : " . $nbMembers . "\n Nombre d'emails envoyes : " . $nbEmails . "\n Liste des emails : " . $listEmails ;
return $result;
}
}
2/ Call you controller as a service
app/config/services.yml
app.member.sendEmailNewUsers :
class: Becowo\MemberBundle\Controller\MemberController
arguments: ['#doctrine.orm.entity_manager', '#mailer', '#templating', '#app.member']
3/ Create a console command to call your controller
Doc : http://symfony.com/doc/current/console.html
YourBundle/Command/EmailNewUserCommand.php
<?php
namespace Becowo\CronBundle\Command;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
class EmailNewUserCommand extends ContainerAwareCommand
{
protected function configure()
{
// the name of the command (the part after "php bin/console")
$this->setName('app:send-email-new-users')
->setDescription('Send welcome emails to new users')
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
// outputs a message to the console followed by a "\n"
$output->writeln('Debut de la commande d\'envoi d\'emails');
// access the container using getContainer()
$memberService = $this->getContainer()->get('app.member.sendEmailNewUsers');
$results = $memberService->sendEmailToNewUsersAction();
$output->writeln($results);
}
}
4/ Test your command !
In the console, call you command : php bin/console app:send-email-new-users
5/ Create a script to run the command
Doc (french) : http://www.christophe-meneses.fr/article/deployer-son-projet-symfony-sur-un-hebergement-perso-ovh
..Web/Batch/EmailNewUsers.sh
#!/bin/bash
today=$(date +"%Y-%m-%d-%H")
/usr/local/php5.6/bin/php /homez.1111/coworkinwq/./demo/toto/bin/console app:send-email-new-users --env=demo > /homez.1111/coworkinwq/./demo/toto/var/logs/Cron/emailNewUsers-$today.txt
Here it took me some time to get the correct script.
Take care of php5.6 : it has to match your PHP version on OVH
Don't forget to upload bin/console file on the server
homez.xxxx/name has to match with your config (I found mine on OVH, and then in the logs)
IMPORTANT : when you upload the file on the server, add execute right (CHMOD 704)
6/ Create the cron job in OVH
Call your script with the command : ./demo/Becowo/web/Batch/EmailNewUsers.sh
Language : other
7/ Wait !
You need to wait for the next run. Then have a look on OVH cron logs, or on your own logs created via the command in the .sh file
It took me several days to get it..
Enjoy !!
As commented above, you should do it with a symfony commaad. This is an example for you.
NOTE: Although it is working, you can always improve this example. Especially the way command calls your endpoint.
Controller service definition:
services:
yow_application.controller.default:
class: yow\ApplicationBundle\Controller\DefaultController
Controller itself
namespace yow\ApplicationBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\HttpFoundation\Response;
/**
* #Route("", service="yow_application.controller.default")
*/
class DefaultController
{
/**
* #Method({"GET"})
* #Route("/plain", name="plain_response")
*
* #return Response
*/
public function plainResponseAction()
{
return new Response('This is a plain response!');
}
}
Command service definition
services:
yow_application.command.email_users:
class: yow\ApplicationBundle\Command\EmailUsersCommand
arguments:
- '#http_kernel'
tags:
- { name: console.command }
Command itself
namespace yow\ApplicationBundle\Command;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpKernelInterface;
class EmailUsersCommand extends Command
{
private $httpKernel;
public function __construct(HttpKernelInterface $httpKernel)
{
parent::__construct();
$this->httpKernel = $httpKernel;
}
protected function configure()
{
$this->setName('email:users')->setDescription('Emails users');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$request = new Request();
$attributes = [
'_controller' => 'yow_application.controller.default:plainResponseAction',
'request' => $request
];
$subRequest = $request->duplicate([], null, $attributes);
$response = $this->httpKernel->handle($subRequest, HttpKernelInterface::SUB_REQUEST);
$output->writeln($response);
}
}
Test
$ php bin/console email:users
Cache-Control: no-cache, private
X-Debug-Token: 99d025
X-Debug-Token-Link: /_profiler/99d025
This is a plain response!
1.0
200
OK
I have some code that iterates over the rows and columns of an Excel sheet and replaces text with other text. This is done with a service that has the excel file and a dictionary as parameters like this.
$mappedTemplate = $this->get('app.entity.translate')->translate($phpExcelObject, $dictionary);
The service itself looks like this.
public function translate($template, $dictionary)
{
foreach ($template->getWorksheetIterator() as $worksheet) {
foreach ($worksheet->getRowIterator() as $row) {
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false); // Loop all cells, even if it is not set
foreach ($cellIterator as $cell) {
if (!is_null($cell)) {
if (!is_null($cell->getCalculatedValue())) {
if (array_key_exists((string)$cell->getCalculatedValue(), $dictionary)) {
$worksheet->setCellValue(
$cell->getCoordinate(),
$dictionary[$cell->getCalculatedValue()]
);
}
}
}
}
}
}
return $template;
}
After some debugging I found out that the text actually is replaced and that the service works like it should. The problem is that when I return the new PHPExcel file as a response to download, the excel is empty.
This is the code I use to return the file.
// create the writer
$writer = $this->get('phpexcel')->createWriter($mappedTemplate, 'Excel5');
// create the response
$response = $this->get('phpexcel')->createStreamedResponse($writer);
// adding headers
$dispositionHeader = $response->headers->makeDisposition(
ResponseHeaderBag::DISPOSITION_ATTACHMENT,
$file_name
);
$response->headers->set('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
$response->headers->set('Pragma', 'public');
$response->headers->set('Cache-Control', 'maxage=1');
$response->headers->set('Content-Disposition', $dispositionHeader);
return $response;
What am I missing?
Your code is missing the calls to the writer.
You only create the writer, but never use it, at least not in your shared code examples:
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
$response = $this->get('phpexcel')->createStreamedResponse($objWriter)
Another thing is the content type: Do you have the apache content types setup correctly?
$response->headers->set('Content-Type', 'application/vnd.ms-excel; charset=utf-8');
I have been trying image uploading in Laravel 5 (upload generated through laravelcollective/forms, and processed using Intervention Image library).
What I wanna do is when user uploads any photo, I want to set the extension based on its mimetype. There should be some basic check to protect against spurious data injection.
$file_profile_image->getClientMimeType();
To do that, should I simply be mapping like so ?
['image/jpeg' => 'jpg', 'image/gif'=> 'gif']
I would use the Intervention package to check if you're loading a valid image and get the mime from there.
Something like this:
/**
* Store a file
*
* #return Response
*/
public function store(Filesystem $filesystem)
{
// check if file was posted
$uploadedFile = Request::file('file');
// other checks here, ->isValid() && filesize
try {
$image = Image::make(\File::get($uploadedFile));
} catch (\Intervention\Image\Exception\NotReadableException $e) {
\Log::error('Unsupported filetype');
dd('Unsupported filetype');
// return proper error here
}
// mime as returned by Intervention
$mime = $image->mime();
// other stuff
// store # fs
}
This is how I would do it:
$source_file = $request->file('image')->getRealPath();
$info = get_image_details($source_file);
The get_image_details($path) function can be defined as follows:
function get_image_details($path)
{
$details = #getimagesize( $path );
if ( is_array($details) && count($details) > 2 ) {
$info = [
'width' => $details[0],
'height' => $details[1],
'mime' => $details['mime'],
'size' => #filesize($path),
'path' => $path,
];
switch ($details['2']) {
case IMG_PNG:
case 3:
$info['type'] = 'png';
break;
case IMG_JPG:
case 2:
$info['type'] = 'jpg';
break;
case IMG_GIF:
case 1:
$info['type'] = 'gif';
break;
default:
$info['type'] = $details[2];
break;
}
return $info;
}
return false;
}
File objects have a method just for this case. All you have to do is call the guessExtension method on your file object like so
$file_profile_image->guessExtension()