"move_uploaded_file" function not working in SugarCRM logic hook - php

I am trying to move uploaded files to new location using SugarCRM's logic hook either after_save or before_save. But I am unable to do so. Kindly find my logic hook code:
class attachment
{
public function attachment(&$bean, $event, $arguments)
{
if(!empty($bean->filename_new))
{
$upload_dir = $GLOBALS['sugar_config']['upload_dir'];
$target_file = $upload_dir . basename($_FILES["filename_new_file"]["name"]);
if (move_uploaded_file($_FILES["filename_new_file"]["tmp_name"], $target_file))
{
$GLOBALS['log']->fatal("The file has been uploaded");
}
else
{
$GLOBALS['log']->fatal("Sorry, there was an error uploading your file.");
}
}
}
}
Here, when I print $_FILES, I am getting desired output:
Array
(
[name] => twitter.png
[type] => image/png
[tmp_name] => /tmp/php5wBmgK
[error] => 0
[size] => 203
)
Now I have seen many posts, where they mentioned solution for this is to make sure the correct file permission and file ownership. I tried that, but didn't work out.
Lastly, to remove the possibility of issue with file permission or file ownership, I made one file upload script and run that script outside of CRM and that time move_uploaded_file function worked as it should.
But when I try to achieve the same with the use of logic hook, I am unable to get desired output. Kindly guide me here.

If you are using UNIX please check Permission also.
Check this file Rootapp/include/upload_file.php you will get different function related to file .I use this to copy file.
And you want to change location of file where file saving then ,
If you look at your config.php file, you will see a line that looks like this.
'upload_dir' => 'upload/',
to copy a file i did like this,
$bean->file_mime_type = $result->file_mime_type;
$bean->filename = $result->filename;
require_once('include/upload_file.php');
$uploadFile = new UploadFile();
$upoad_atachment =
$uploadFile->duplicate_file($result->id, $bean->id)
IN logic hook after save when i get email with attachment i copy that attachment and insert that files into my custom module.
Every image have some id , the image name uploaded with that id, so find that id , for email that attachment information save into notes module, In your case you find in your module. then get that information in your result and copy that in other module.

Related

ZipArchive not saving file on live server in Laravel

I have some encrypted responses that I convert to a Zip file in my Laravel application. The function below downloads the API response, saves it as a Zip file, and then extracts it while I read the folder's contents. In my local environment, it works well. However, the Zip file is not getting saved to the storage folder on the live server. No error is being shown, only an empty JSON response. Please, what could be the cause?
public function downloadZipAndExtract($publication_id, $client_id)
{
/* We need to make the API call first */
$url = $this->lp_store."clients/$client_id/publications/$publication_id/file";
$file = makeSecureAPICall($url, 'raw');
// Get file path. If file already exist, just return
$path = public_path('storage/'.$publication_id);
if (!File::isDirectory($path)) {
Storage::put($publication_id.'.zip', $file);
// Zip the content
$localArchivePath = storage_path('app/'.$publication_id.'.zip');
$zip = new ZipArchive();
if (!$zip->open($localArchivePath)) {
abort(500, 'Problems experienced while reading file.');
}
// make directory with the publication_id
// then extract everything to the directory
Storage::makeDirectory($publication_id);
$zip->extractTo(storage_path('app/public/'.$publication_id));
// Delete the zip file after extracting
Storage::delete($publication_id.'.zip');
}
return;
}
First thing I'd check is if the storage file is created and if it isn't created, create it. Then I'd look at your file permissions and make sure that the the groups and users permissions are correct and that you aren't persisting file permissions on creation. I've had many instances where the process that's creating files(or trying) is not in the proper group and there is a sticky permission on the file structure.

hello I wanna use php_move_upload_file in order to move image from my temp folder to a permanent folder

hi this is the function that upload image inside temp location and save location to session for forther use
function uploadPhoto()
{
$rawImage = $_FILES['advPhoto'];
$uploader = new ImageUploader($rawImage);
$uploader->moveToProjectTempFolder();
//1 save the current image in sassion (save the attachment class inside seesion)
$uploader->saveInSession();
// $temperrary = $uploader->CurrentImgTemperraryLocation();
//2 send reponse the current image location
AjaxHelper::sendAjaxResponse("images/temp/" . $uploader->CurrentImgTemperraryLocation());
//create image tag and set the image source the "temp uploaded image path"
// done
//when the mail form is submitted
//loop through session array
//move the user uploaded/approved images to permanent folder
//save image information inside DB
}
here is the function that cause problem I wanna move the picture from temp folder to permanent location but the php_move_uploaded_file() doesn't work in my case I don't really know what is the problem please help me if you know what is the problem thnks .
function saveAdv()
{
$advTitle = $_POST['advTitle'];
$advContent = $_POST['advContent'];
if (!empty($advTitle) && !empty($advContent)) {
if (DataValidation::isOnlyPersianOrEnglish($advTitle) &&
DataValidation::isOnlyPersianOrEnglish($advContent)) {
DBconnection::insertRow('ADVERTISEMENT', ['title', 'Advertisement', 'advDate'],
[$advTitle, $advContent, date('y/m/d h:i:s')]);
// AjaxHelper::sendAjaxResponse("success");
$projectTemp = $_SESSION['ADVERTISEMENT']['Img'];
move_uploaded_file(
$projectTemp,
DOC_ROOT . "/images/advertisementImg/"
);
AjaxHelper::sendAjaxResponse($projectTemp);
}
} else {
AjaxHelper::sendErrorMessage(AjaxHelper::EMPTY_EMAIL_OR_PASSWORD);
}
}
I don't get any error I've already debuged many times but no warning and no errors at all and the location of the folders are completely correct and also there is no permission problems.
The move_uploaded_file() works pretty well at first step that I move image from system temp location to my project temp location, but doesn't work when I wanna move the image from project temp location to permanent location.
move_uploaded_file() is only for moving files which have just been uploaded in a POST request and are stored in the system temp location. As the documentation (https://php.net/manual/en/function.move-uploaded-file.php) states, it first checks whether the file is a valid upload file meaning that it was uploaded via PHP's HTTP POST upload mechanism (that's a direct quote from the docs). If it's not valid by that definition, it fails.
So, if you're trying to use move_uploaded_file() to copy files from other locations (not the system temp location) which have not been directly uploaded to that location in the current request, then it won't work. Use PHP's general file manipulation functionality for moving other files around, using the rename() function (see https://www.php.net/manual/en/function.rename.php for details).

php fopen is not working (always null)

I have the following code in a "function" file [2] in my project. It can be called for multiple types of reports in my project. The $name comes from the reports pages using the $thePDFFileName [1]:
[1] $pdf->Output($thePDFFileName);
...
[2] $f=fopen($name,'wb');
if(!$f)
{
$this->Error('Unable to create output file: '.$name);
}
fwrite($f,$this->buffer,strlen($this->buffer));
fclose($f);
...
[1] FunctionSendFile::sendPDFFile($thePDFFileName );
Example: $thePDFFileName = tmp/[Filename]_19-11-2013.pdf
What's strange is before it was working for all my reports, now all of a sudden it always returns null (empty) for $f=fopen($name,'wb'); and I have no idea why. I tried removing the if condition to force the file being created, and it makes a pdf file of 0 bytes (I'm assuming because fopen() fails).
Has anyone seen this happen before and know how to fix it? I'm not sure what i've done to make all the pdf files stop working...
NOTE: I am trying to create these files and save them in a certain location. I'm not trying to find and open files that already exist!

Create Thumbnail with SWFUpload

I am attempting a CMS photo gallery and need to create thumbnails at the end of my upload.php file. I have a function called create_square_image that works fine when run on the 'showphotos.php' page. However I don't want it to be run every time someone views the page. I have tried adding the following to SWFUpload...
// Process the file
/*
At this point we are ready to process the valid file. This sample code shows how to save the file. Other tasks
could be done such as creating an entry in a database or generating a thumbnail.
Depending on your server OS and needs you may need to set the Security Permissions on the file after it has
been saved.
*/
$thumb_save = "uploads/thumbs/thumb_" . $_FILES[$upload_name]["tmp_name"];
create_square_image($_FILES[$upload_name]["tmp_name"],$thumb_save,100);
if (!#move_uploaded_file($_FILES[$upload_name]["tmp_name"], $save_path.$file_name)) {
HandleError("File could not be saved.");
exit(0);
}
exit(0);
The create_square_image function uses this format:
create_square_image ( string $filename , string $destination, size )
I have tried it a few times and it will save the image but not the thumbnail.
Set the permissions on /uploads/thumbs/ to 777. You could also try specifying the absolute path to that location. To see your absolute path use this code: echo getcwd();

How to store a file in Moodle so that it is accessible for an external application?

I need to store a file in Moodle. This is not really a problem, it is explained here. The problem is that this file has to be accessible for everyone. Hence, there has to be a URL, e.g. www.mymoodlesite.com/temp/myfile.txt or the like, which one can enter in ones browser and access the file. I thought of copying the file into the moodledata/temp folder, but then I do not have a URL in order to access the file..
Thanks for your help in advance!
Finally I could solve my problem :-)
I used a filemanager like this:
$mform->addElement('filemanager', 'my_filemanager', 'Upload a file', null, array('maxbytes' => $CFG->maxbytes, 'maxfiles' => 1, 'accepted_types' => array('*.zip')));
Then saved the uploaded file like this:
if ($draftitemid = file_get_submitted_draft_itemid('my_filemanager')) {
file_save_draft_area_files($draftitemid, $context->id, 'mod_assignment', 'my_filemanager', 0, array('subdirs' => false, 'maxfiles' => 1));
}
The URL in order to access the uploaded file can then be created like this:
file_encode_url($CFG->wwwroot . '/pluginfile.php', '/' . $this->context->id . '/mod_assignment/my_filemanager');
Assuming that you have added the element like this :
$mform->addElement('filepicker', 'file', "Upload a Document", null, array('maxbytes' => 1024*1024, 'accepted_types' =>array('*.png', '*.jpg', '*.gif','*.jpeg', '*.doc', '*.rtf','*.pdf','*.txt')));
Now assuming that You get the data as the following
$data = $lesson_form->get_data()
See the code below to upload the file to a specified folder in your server. This is compatible with moodle 2.2+
$realfilename = $lesson_form->get_new_filename('file'); // this gets the name of the file
$random =rand(); // generate some random number
$new_file = $random.'_'.$realfilename; //add some random string to the file
$dst = "uploads/$new_file"; // directory name+ new filename
if($realfilename !=''){ // checking this to see if any file has been uploaded
save_files($dst); // moodle function to save a file in given folder
}
I faced the same problem that you're facing and it solved my problem.
N.B. -> Remember to chmod your upload folder to 0777.
You can access files uploaded through moodle's file browser without being authenticated if the following is true
- Your moodle site has forcelogin set to no
- Your file is uploaded the the files in frontpage sitefiles.
Uploaded files are saved (assuming Moodle1.9) in moodledata/1/{filepath}. Since you have to do it programatically you can store them there and reference them using the url /file.php/1/{filepath}. To say it another way. Files saved to $CFG->datadir.'/1/'.filepath are accessible with $CFG->wwwroot.'/file.php/1/'.filepath;
Alternatively if you don't want the files to show up in your front page site files through the moodle file browser you could edit file.php to forget checking permissions for files located in your special directory and instead just serve them up.
Hope this is more helpful with this edit.

Categories