Uploading facebook event picture throws error - php

I am trying to create event with picture, but when i upload picture to facebook it throws me an error (#324) Missing or invalid image file
this is the function to upload picture.
public function uploadFacebookEventPicture($fullPath, $eventId) {
$mainImage = '#' . $fullPath;
$imgData = array(
'picture' => $mainImage
);
try {
$data = $this->facebook->api('/'.$eventId, 'post', $imgData);
return $data;
} catch (FacebookApiException $e) {
error_log('Failed to attach picture to event. Exception: ' . $e->getMessage());
}
return null;
}
the par of code i use after form post
if ($file[$name]['error'] == 0) {
$fileName = $file[$name]['name'];
$fileInfo = pathinfo($fileName);
$newFileName = md5($fileName . microtime()) . '.' . $fileInfo['extension'];
$fullPath = $this->config->applications->uploadPath . $newFileName;
$form->$name->addFilter('Rename', $fullPath);
if ($form->$name->receive()) {
$resize = new SimpleImage();
$resize->load($fullPath);
$resize->resizeToWidth($this->config->applications->resize->width);
$resize->save($fullPath);
// Gathering data for saving files information
$fileInfo = array(
'name' => $newFileName,
'type' => FileTypes::IMAGE,
'description' => 'Application: Uploaded from Events form in back-end',
);
$fileId = $dbFiles->save($fileInfo);
$eventFileData = array(
'event_id' => $eventId,
'file_id' => $fileId,
'main_image' => ($name == 'mainImage') ? 1 : 0
);
$dbEventFiles->save($eventFileData);
if ($name === 'mainImage') {
$success = **$this->uploadFacebookEventPicture($fullPath, $eventData['fb_event_id']**);
}
}
}
facebook object is created with upload file true
$facebook = new Facebook(array(
'appId' => $config->facebook->appId,
'secret' => $config->facebook->secret,
'fileUpload' => true
));

According to Facebook bug tracker, this bug has been fixed:
Bug tracker post
Status changed to Fixed
Code above works fine for uploading facebook event picture.

Related

Upload file to API endpoint Laravel

I'm trying to upload files via API, in POSTMAN I can do it perfectly. However when doing in my application is not accepted.
Store in Controller:
public function store(Request $request)
{
$data = $request->validate([
'projeto_id' => 'required|integer',
'name' => 'required|string|max:255',
'logo' => 'nullable|image|mimes:jpeg,png,jpg|max:2000',
'telephone' => 'required|string|max:255',
'desc' => 'required|string',
'quantity' => 'required|integer|gt:0|lt:51',
'sequential' => 'required|integer|gt:0',
]);
$user = Auth::user()->id;
if($user != Auth::id()){
abort(403);
}
//UPLOAD IMAGEM DO GRUPO
$logo = $request['logo'];
// Check if a profile image has been uploaded
if ($request->has('logo')) {
// Get image file
$image = $request->file('logo');
// Make a image name based on user name and current timestamp
$name = Str::slug($user.'_'.time());
// Define folder path
$folder = '/uploads/images/'.$user.'/groupimg/logo/';
// Make a file path where image will be stored [ folder path + file name + file extension]
$filePath = $folder . $name. '.' . $image->getClientOriginalExtension();
// Upload image
$this->uploadOne($image, $folder, 'public', $name);
// Set user profile image path in database to filePath
$logo = $filePath;
}
$gPrivado = '0';
if($request->has('private')){
$gPrivado = '1';
}
$i = 0;
$delayCounter = 0;
$sequential = $data['sequential'];
while ($i < (int)$data['quantity']) {
$delay = $delayCounter + rand(10, 15);
CreateGroups::dispatch($data['name'] . " {$sequential}", $logo , $data['desc'], $gPrivado, [$data['telephone']], $data['projeto_id'], auth()->user())
->delay(Carbon::now()
->addSeconds($delay));
$delayCounter = $delay;
$i++;
$sequential++;
}
return redirect()->back()->with('success', 'Grupos adicionados em fila de criação, aguarde alguns minutos .');
}
Use Job to proccess:
public function handle()
{
$user = $this->user;
if ($user->instance_connected) {
$ZApi = new ZApi($user->zapi_instance_id, $user->zapi_token);
$createdGroup = $ZApi
->createGroup($this->name, $this->phones);
sleep(3);
foreach($createdGroup->groupInfo as $informacoes){
$linkInvite = $ZApi->getGroupInvite($informacoes->id);
$idGroup = $informacoes->id;
}
//DESCRICAO DO GRUPO
$descricao = $this->desc;
$setDescricao = $ZApi->setGroupDescription($idGroup, $descricao);
//GRUPO PRIVADO
if ($this->private == '1'){
$grupoPrivado = $ZApi->setGroupMessages($idGroup, 'true');
$adminOnly = $ZApi->setGroupEdit($idGroup, 'true');
}
$setImg = $ZApi->groupImage($idGroup, $this->logo);
The last line send to API, I'm using Guzzle
And this is my API function
public function groupImage(string $groupId, string $value)
{
return $this->doRequest2('POST', "group-pic", [
'multipart' => [
[
'name' => 'phone',
'contents' => $groupId,
],
[
'Content-type' => 'multipart/form-data',
'name' => 'file',
'contents' => fopen('storage'.$value, 'r'),
]
]
]);
}
But get this error response
GuzzleHttp\Exception\ClientException Client error: POST http://localhost:8081/api/danilo/group-pic resulted in a 400 Bad Request response: {"status":"Error","message":"File parameter is
required!"}
Can someone help me?

PHP Uploading Zero Bytes To S3

I am trying to upload mp3 files to Amazon S3 but for some reason anything I upload is uploaded with a byte length of zero. I cannot seem to figure out why this is happening. I've tried following a tutorial and adjusting the code myself. Any help is appreciated.
<?php
error_reporting(0);
require '../../../../includes/aws-sdk-php/vendor/autoload.php';
use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;
if (isset($_GET['test'])){
if($_GET['test'] == "true"){
include("../../depend.php");
include("../../../../includes/okta-jwt/okta-jwt-functions.php");
include("../../../../includes/aws-s3/functions.php");
$jwtToken = $_GET['token'];
$validateJWT = validateJWT($jwtToken);
echo "$validateJWT";
die();
}
}
include("../../depend.php");
include("../../../../includes/okta-jwt/okta-jwt-functions.php");
if(isset($_POST['episodeTitle'])){
$episodeTitle = $_POST['episodeTitle'];
}
if(isset($_POST['episodeDescription'])){
$episodeDescription = $_POST['episodeDescription'];
}
if(isset($_POST['explicitContent'])){
$explicitContent = $_POST['explicitContent'];
}
if(isset($_POST['episodeShowID'])){
$episodeShowID = $_POST['episodeShowID'];
}
if(isset($_POST['jwtToken'])){
$jwtToken = $_POST['jwtToken'];
}
if(isset($_POST['audioFile'])){
$episodeAudio = $_POST['audioFile'];
}
$validateJWT = validateJWT($jwtToken);
$payloadJSON = json_decode($validateJWT);
$payloadDecoded = $payloadJSON;
$payloadUserID = $payloadDecoded->userID;
//Check if JWT Token Is Valid
if($payloadUserID != 0){
$payloadUserOrgID = $payloadDecoded->userOrgID;
$payloadRole = $payloadDecoded->role;
$payloadExp = $payloadDecoded->exp;
$payloadState = $payloadDecoded->state;
$payloadFirstName = $payloadDecoded->firstName;
$payloadLastName = $payloadDecoded->lastName;
$payloadFullName = $payloadDecoded->fullName;
$episodeStateCode = bin2hex(random_bytes(25));
date_default_timezone_set('UTC');
$showUtcTimestamp = date("Y-m-d H:i:s");
// AWS Info
$bucketName = 'XXX';
$IAM_KEY = 'XXX';
$IAM_SECRET = 'XXX';
// Connect to AWS
try {
// You may need to change the region. It will say in the URL when the bucket is open
// and on creation.
$s3 = S3Client::factory(
array(
'credentials' => array(
'key' => $IAM_KEY,
'secret' => $IAM_SECRET
),
'version' => 'latest',
'region' => 'us-east-2'
)
);
} catch (Exception $e) {
// We use a die, so if this fails. It stops here. Typically this is a REST call so this would
// return a json object.
die("Error: " . $e->getMessage());
}
// $keyName = "test_example/" . basename($_FILES["audioFile"]['name']);
// $keyName = "org-$payloadUserOrgID/$episodeStateCode-" . basename($_FILES["audioFile"]['name']);
$keyName = "org-$payloadUserOrgID/$episodeStateCode.mp3";
$pathInS3 = 'https://s3.us-east-2.amazonaws.com/' . $bucketName . '/' . $keyName;
// Add it to S3
try {
// Uploaded:
$file = $_FILES["audioFile"]['tmp_file'];
$s3->putObject(
array(
'Bucket'=>$bucketName,
'Key' => $keyName,
'SourceFile' => $file,
'StorageClass' => 'STANDARD'
)
);
} catch (S3Exception $e) {
die('Error:' . $e->getMessage());
} catch (Exception $e) {
die('Error:' . $e->getMessage());
}
echo 'Done';
}
?>
I can confirm that the file is being uploaded to S3 but the data in the file is not there. Any help in this would be very much appreciated.

Google API PHP Update File

I'm trying to update the content of the file. Use the PHP function:
function updateFile($service, $fileId, $newTitle, $newDescription, $newMimeType, $newFileName, $newRevision) {
try {
// First retrieve the file from the API.
$file = $service->files->get($fileId);
// File's new metadata.
$file->setTitle($newTitle);
$file->setDescription($newDescription);
$file->setMimeType($newMimeType);
// File's new content.
$data = file_get_contents($newFileName);
$additionalParams = array(
'newRevision' => $newRevision,
'data' => $data,
'mimeType' => $newMimeType
);
// Send the request to the API.
$updatedFile = $service->files->update($fileId, $file, $additionalParams);
return $updatedFile;
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}
....
$data = retrieveAllFiles($service);
$fileName = 'test.txt';
$mimeType = mime_content_type('./'.$fileName);
$res = updateFile($service, $data[0]['id'], $data[0]['title'], 'update', $mimeType, $fileName, true);
I'm trying to add a text file line "test string". Function updates the data file (description, lastModifyingUser...), but the content of the file remains the same. Who can tell what's wrong?
In additionalParams need to add :
'uploadType' => 'multipart',
or
'uploadType' => 'media',
Hope it helps!

Zend Framework 2: upload and rename multiple files

I have a Zend Form and offer the option to upload multiple files with the form. I use dropzone.js. When I upload a single file, everything works fine, I get the Post data and the file gets renamed and moved into the correct folder, but as soon I upload 2 files, I get an Error Message: Notice: Array to string conversion which points to $upload->addFilters('File\Rename'.....
What am I doing wrong here? I have everything in a foreach loop, should this not solve the issue? I can not find a solution for it. Anyone got a tip for me?
Here my Sourcecode so far:
$upload = new \Zend\File\Transfer\Adapter\Http();
// Limit the amount of files
$upload->addValidator('Count', false, 2);
// Limit the MIME type of all given files to gif and jpeg images
$upload->addValidator('MimeType', false, array('image/gif', 'image/jpeg',));
if (!$upload->isValid()) {
$data = new JsonModel(array(
'success' => "failed",
'message' => "validation failed",
));
return $data;
}else{
$files = $upload->getFileInfo();
$upload->setDestination('./public/uploads/tmp/');
// loop through the file array
foreach ($files as $file => $info) {
$file_ext = #strtolower(#strrchr($originalName,"."));
$file_ext = #substr($file_ext, 1); // remove dot
$newFilename = md5(uniqid(rand(), true)) .time(). '.' . $file_ext;
$upload->addFilter('File\Rename',
array('target' => $upload->getDestination() . DIRECTORY_SEPARATOR . $newFilename,
'overwrite' => true));
if (!$upload->receive()) {
$data = new JsonModel(array(
'success' => "upload failed",
));
}else{
$data = new JsonModel(array(
'success' => "upload ok",
));
}
return $data;
} // end foreach
}

Facebook upload photo from computer

i am trying to make a facebook app that uploads photos from the computer to a specific album on facebook. i have the code below but i get an error: failed creating formpost data.
require_once 'include.php';
$config = array(
'appId' => $app_id,
'secret' => $app_secret,
);
$facebook = new Facebook($config);
$user = $facebook->getUser();
if($user && isset($_POST['submit'])){
try {
$facebook->setFileUploadSupport(true);
//Create an album
$album_details = array(
'message'=> 'Album desc',
'name'=> 'Album name'
);
$create_album = $facebook->api('/me/albums', 'POST', $album_details);
//Get album ID of the album you've just created
$album_uid = $create_album['id'];
//Upload a photo to album of ID...
$photo = realpath($_FILES['miss_photo']['tmp_name']);
$photo2 = $photo . '.jpg';
//echo $photo2; exit();
$photo_details['image'] = '#' . $photo2;
$upload_photo = $facebook->api('/'.$album_uid.'/photos', 'POST', $photo_details);
} catch (FacebookApiException $e) {
echo ($e->getMessage());
}
}
else
echo 'error';
any idea why i get the error message?
You cant use files in that way, you need to provide path to your file, like:
photo_details = array(
'message'=> 'some test'
);
$photo_details['image'] = '#' . realpath('/path/to/your/image_file.jpg');
$upload_photo = $facebook->api('/'.$album_uid.'/photos', 'post', $photo_details);
Hope that helps

Categories