How can I Upload File in SuiteCRM on fired logic hook

Hi everybody, I tried many ways but are not working… how can I upload a file in a logic hook?

to ‘die()’ function is a block of code. :’( as you can see I tried many ways but … isn’t working

This is my code in : [sourcePath]/custom/modules/Documents/uploadFile_hook_class.php

    class logic_hooks_class_fu
    {
	     function uploadFile($bean, $event, $arguments)
        {
            /*
                    <li>Sent file: <?php echo $_FILES['image']['name'];  ?>
        <li>File size: <?php echo $_FILES['image']['size'];  ?>
        <li>File type: <?php echo $_FILES['image']['type'] ?>
            */
            //echo '<script> alert("'.$_FILES["filename_file"]["tmp_name"].'"); </script>';
           // $target_file = $target_dir . basename($_FILES["filename_file"]["name"]);

           require_once('include/UploadFile.php');
           move_uploaded_file($_FILES['filename_file']['tmp_name'], '/var/www/html/files/tool.pdf');
           die();
           $orig_upload = '/var/www/html/files/';
$sugar_config['upload_dir'] = $orig_upload.$bean->id;
$file_upload = new UploadFile('filename_file');
echo '<pre>';
echo var_dump($file_upload);
if (isset($_FILES['filename_file']) /*&& $file_upload->confirm_upload()*/)
{
    $bean->filename_file = $file_upload->get_stored_file_name();
    $dest_path = $sugar_config['upload_dir'];
    if(!file_exists($sugar_config['upload_dir'])) {
       mkdir_recursive($sugar_config['upload_dir']);
    }
    $file_upload->final_move($file_upload->get_stored_file_name());
}
$sugar_config['upload_dir'] = $orig_upload;

           die();
           if ($_SERVER['CONTENT_TYPE']=='application/vnd.api+json' && $this->file || 1==1){
            $upload_file = new UploadFile('filename_file');
            $decodedFile = base64_decode($this->file);
            $upload_file->set_for_soap($this->filename, $decodedFile);
  
            $ext_pos = strrpos($upload_file->stored_file_name, ".");
            $upload_file->file_ext = substr($upload_file->stored_file_name, $ext_pos + 1);
            if (in_array($upload_file->file_ext, '/var/www/html/files/')) {
                $upload_file->stored_file_name .= ".txt";
                $upload_file->file_ext = "txt";
            }
            $upload_file->final_move($this->id);
      }


           die();
           //$uploadfile = $uploaddir . basename($_FILES['filename_file']['tmp_name']);
           $uploadfile =  $_FILES['filename_file']['tmp_name'];
           header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
        header('Cache-Control: post-check=0, pre-check=0', false);
        header('Pragma: no-cache');

 
            header('Content-type: application/pdf');

                header('Content-Disposition: inline; filename="' . $uploadfile . '";');

        // disable content type sniffing in MSIE
        header("X-Content-Type-Options: nosniff");
        header("Content-Length: " . filesize($uploadfile));
        //header('Expires: ' . gmdate('D, d M Y H:i:s \G\M\T', time() + 2592000));


           die();
           //$orig_upload = $sugar_config['upload_dir'];
           $orig_upload = '/var/www/html/files/';
$sugar_config['upload_dir'] = $orig_upload.$bean->id;
$file_upload = new UploadFile('filename_file');
if (isset($_FILES['filename_file']) /*&& $file_upload->confirm_upload()*/)
{
    $bean->filename_file = $file_upload->get_stored_file_name();
    $dest_path = $sugar_config['upload_dir'];
    if(!file_exists($sugar_config['upload_dir'])) {
       mkdir_recursive($sugar_config['upload_dir']);
    }
    $file_upload->final_move($file_upload->get_stored_file_name());
}
$sugar_config['upload_dir'] = $orig_upload;

           die();
            if (isset($_FILES['filename_file']) && $_FILES['uploadedFile']['error'] === UPLOAD_ERR_OK) {
                 
                }else{
                   // get details of the uploaded file
$fileTmpPath = $_FILES['filename_file']['tmp_name'];
$fileName = $_FILES['filename_file']['name'];
$fileSize = $_FILES['filename_file']['size'];
$fileType = $_FILES['filename_file']['type'];
$fileNameCmps = explode(".", $fileName);
$fileExtension = strtolower(end($fileNameCmps)); 

$newFileName = md5(time() . $fileName) . '.' . $fileExtension;
 $allowedfileExtensions = array('jpg', 'gif', 'png', 'zip', 'txt', 'xls', 'doc', 'pdf');
if (in_array($fileExtension, $allowedfileExtensions)) {
 // directory in which the uploaded file will be moved
$uploadFileDir = '/var/www/html/files/';
$dest_path = $uploadFileDir . $newFileName;
 echo $dest_path;
if(move_uploaded_file($fileTmpPath, $dest_path))
{
  $message ='File is successfully uploaded.';
}
else
{
  $message = 'There was some error moving the file to upload directory. Please make sure the upload directory is writable by web server.';
}
}


                }

            die();
            require_once('modules/Documents/Document.php');
    require_once('include/upload_file.php');
    
    
		     $contents = file_get_contents($_FILES["filename_file"]["tmp_name"]);
		     $contentse = file_put_contents('/var/www/html/files/'.'alfa.pdf');
   // $destination = clean_path($sugar_config['upload_dir'] . $id);
    $destination = clean_path('/var/www/html/files/');
    $fpp = sugar_fopen($destination, 'wb');

    if (!fwrite($fpp, $contents)) {
        die("ERROR: can't save file to $destination");
    }
    fclose($fpp);

           /* if (move_uploaded_file($_FILES["filename_file"]["tmp_name"], $target_file ))
            {
                $GLOBALS['log']->fatal("The file has been uploaded");
                echo "The file ". basename( $_FILES["filename_file"]["name"]). " has been uploaded.";
            }else{
                echo "The file ". basename( $_FILES["filename_file"]["name"]). " NOT has been uploaded.";
                echo "The file ". basename( $_FILES["filename_file"]["size"]). " NOT has been uploaded.";
                echo "The file ". basename( $_FILES["filename_file"]["type"]). " NOT has been uploaded.";
                echo "The file ". basename( $_FILES["filename_file"]["tmp_name"]). " NOT has been uploaded.";
            } */
            exit();
            global $db, $current_user, $sugar_config;
	        		            //$upload_dir = $GLOBALS['sugar_config']['upload_dir'];
	        		            $upload_dir = '/var/www/html/files/';

	        //$target_file = $upload_dir . basename($_FILES["filename_file"]["name"]);
	        //$target_file = $upload_dir . basename($_FILES["files[]"]["name"][0]);
	        $target_file = $upload_dir . $_FILES["filename_file"]["tmp_name"];
	         $GLOBALS['log']->fatal("The file has been uploaded. $target_file XXXXXXXX");
	        //echo "<script> alert('".$target_file."');</script>";
            echo '<script> alert("'. $_FILES["filename_file"]["name"].'"); </script>';


	        if(!empty($bean->filename_file))
				{               
		            //$upload_dir = $GLOBALS['sugar_config']['upload_dir'];
		
		            //$target_file = $upload_dir . basename($_FILES["filename_new_file"]["name"]);
		
		            if (move_uploaded_file($_FILES["filename_file"]["tmp_name"], $target_file))
		            {
                        $GLOBALS['log']->fatal("The file has been uploaded");
                        echo '<script> alert("testing"); </script>';
		            }
		            else
		            {
                        $GLOBALS['log']->fatal("Sorry, there was an error uploading your file.");
                        echo '<script> alert("testing error"); </script>';

		            }
				}
	        
	        
	         /*require_once('modules/Documents/Document.php');
    require_once('include/upload_file.php');
    
    
		     $contents = file_get_contents('uploads/' .$file.'.jpeg');
    $destination = clean_path($sugar_config['upload_dir'] . $id);
    $fpp = sugar_fopen($destination, 'wb');

    if (!fwrite($fpp, $contents)) {
        die("ERROR: can't save file to $destination");
    }
    fclose($fpp);*/

	        
	        //$arguments['isUpdate']
	       // echo "<script> alert('".$bean->id."');</script>";
	       // echo "<script> alert('".$arguments['isUpdate']."');</script>";
	       // echo $arguments['isUpdate'];

	    }

    }

Hi,
I haven’t read all your lines of code - but what exactly are you trying to do?

  • Do you want to upload a specific file while a logic hook is triggered?
  • Should this involve any user interaction, like a popup with an upload form?
  • How should the system behave if the hook is not triggered by an user?

I guess we should figure out what you’re trying to do and maybe we can discuss some options.

Hi!! @crmspace so sorry!,
I have an module semi-customized named Documents, then I’d like upload a pdf file using one form on the editview, then I’d like to use one logic hook triggered on the after_save event when the user submit the form, then I tried many different ways, using for example

my logic hook:

       $hook_version = 1;
$hook_array = Array();

$hook_array['after_save'] = Array();
$hook_array['after_save'][] = Array(
    //Processing index. For sorting the array.
    1,
    //Label. A string value to identify the hook.
    'after save upload new file',
    //The PHP file where your class is located.
    'custom/modules/Documents/uploadFile_hook_class.php',
    //The class the method is in.
    'logic_hooks_class_fu',
    //The method to call.
    'uploadFile'
); 

into uploadFile_hook_class.php:

    <?php if (!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');

class logic_hooks_class_fu
{
     function uploadFile($bean, $event, $arguments)
    {

                   // get details of the uploaded file
        $fileTmpPath = $_FILES['filename_file']['tmp_name'];
        $fileName = $_FILES['filename_file']['name'];
        $fileSize = $_FILES['filename_file']['size'];
        $fileType = $_FILES['filename_file']['type'];
        $fileNameCmps = explode(".", $fileName);
        $fileExtension = strtolower(end($fileNameCmps)); 

        $newFileName = md5(time() . $fileName) . '.' . $fileExtension;
         $allowedfileExtensions = array('jpg', 'gif', 'png', 'zip', 'txt', 'xls', 'doc', 'pdf');
        if (in_array($fileExtension, $allowedfileExtensions)) {
         // directory in which the uploaded file will be moved
        $uploadFileDir = '/var/www/html/files/';
        $dest_path = $uploadFileDir . $newFileName;
         echo $dest_path;
        if(move_uploaded_file($fileTmpPath, $dest_path))
        {
          $message ='File is successfully uploaded.';
        }
        else
        {
          $message = 'There was some error moving the file to upload directory. Please make sure the upload directory is writable by web server.';
        }
        }
}}

also I tried some like:

    require_once('modules/Documents/Document.php');
require_once('include/upload_file.php');
// require_once('include/UploadFile.php'); // this???? :S  

$contents = file_get_contents($_FILES["filename_file"]["tmp_name"]);
$contentse = file_put_contents('/var/www/html/files/'.'alfa.pdf');
// $destination = clean_path($sugar_config['upload_dir'] . $id);
$destination = clean_path('/var/www/html/files/');
$fpp = sugar_fopen($destination, 'wb');

if (!fwrite($fpp, $contents)) {
    die("ERROR: can't save file to $destination");
}
fclose($fpp); 

and finally I tried some like:

    $upload_file = new UploadFile('filename_file');
$decodedFile = base64_decode($this->file);
$upload_file->set_for_soap($this->filename, $decodedFile);

$ext_pos = strrpos($upload_file->stored_file_name, ".");
$upload_file->file_ext = substr($upload_file->stored_file_name, $ext_pos + 1);
if (in_array($upload_file->file_ext, '/var/www/html/files/')) {
    $upload_file->stored_file_name .= ".txt";
    $upload_file->file_ext = "txt";
}
$upload_file->final_move($this->id); 

all of them without work… :C I don’t know what could be happening…

on the editview I’m using a custom file form field, named as the original or native fiel ‘filename_file’, originally this edit view can not permit edit the loaded file,

the idea is be able to edit or change the loadded file if the user need it…

even I tried with a shell command

triggered on the after save, like :

$cmd = shell_exec('sudo cp "'.$_FILES['filename_file']['tmp_name'].'" /path/files/test.pdf ');

but without success…

help!! please!

the logic hook has been triggered because I put some JS code with and alert and this is showing the pop up on the fly…

help! some ideA???