We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 52615
    • 10 Posts
    Hi there,

    I’m having difficulties with Formit.

    Everything is working fine, except when accepting file uploads.
    I wrote my own fileSave hook (with thanks to many user contributions!) which saves the files (with an unique name) to the server.
    The next thing I want to do is to send an email, but not with the uploaded file attached. I don’t see any option for leaving out the attachment.

    The problem is that when I use both hooks after each other (first the fileSave, then email) the latter doesn't work, I just get an email with no contents.
    If I remove the fileSave hook, everything is normal (I even get an attachment that I don’t want).

    This is the code for the fileSave hook I’m using:

    <?php
    // initialize output;
    $output = true;
     
    // valid extensions
    $ext_array = array('pdf', 'txt', 'doc', 'docx', 'rtf');
     
    // create unique path for this form submission
    $uploadpath = 'assets/manuscripts/';
     
    // you can create some logic to automatically
    // generate some type of folder structure here.
    // the path that you specify will automatically
    // be created by the script if it doesn't already
    // exist.
     
    // Function to create unique filename
     function createUploadFilename($currentPath,$currentFilename) {
          
          // Create unique filename
          if(file_exists($currentPath . $currentFilename)) {
          
                  $i = 0;
                  
                  do {
                    $nF =  $i . $currentFilename;
                    $i++;
               
                  } while (file_exists($currentPath . $nF));
          }
          
          if(isset($nF)) {
              $newFilename = $currentPath . $nF;
          
          } else {
              
              $newFilename = $currentPath . $currentFilename;
          }
         
         return $newFilename;
     }
     
    // get full path to unique folder
    $target_path = $modx->config['base_path'] . $uploadpath;
     
    // get uploaded file names:
    $submittedfiles = array_keys($_FILES);
     
    // loop through files
    $countFiles = 1;
    foreach ($submittedfiles as $sf) {
     
        // Get Filename and make sure its good.
        $filename = basename( $_FILES[$sf]['name'] );
        $modx->log(modX::LOG_LEVEL_ERROR, 'Filename: ' . $filename);
        
        // Get file's extension
        $ext = pathinfo($filename, PATHINFO_EXTENSION);
        $ext = mb_strtolower($ext); // case insensitive
        $modx->log(modX::LOG_LEVEL_ERROR, 'Extension: ' . $ext );
     
        // is the file name empty (no file uploaded)
        if($filename != '') {
             
            // is this the right type of file?
            if(in_array($ext, $ext_array)) {
         
                // clean up file name and make unique
                $filename = mb_strtolower($filename); // to lowercase
                $filename = str_replace(' ', '_', $filename); // spaces to underscores
                $filename = date("Y-d-m_") . $filename; // add date
                
                // create directory to move file into if it doesn't exist
               if(!file_exists($target_path)) {
                   mkdir($target_path, 0755, true);
                   
               }
               
                // full path to new file
                $myTarget = createUploadFilename($target_path,$filename);
                $modx->log(modX::LOG_LEVEL_ERROR, 'Clean and unique filename: ' . $myTarget );
    
                // is the file moved to the proper folder successfully?
                if(move_uploaded_file($_FILES[$sf]['tmp_name'], $myTarget)) {
                    // set a new placeholder with the new full path (if you need it in subsequent hooks)
                    $modx->setPlaceholder('fi.bestand' . $countFiles, $myTarget);
                    
                    $modx->log(modX::LOG_LEVEL_ERROR, 'Placeholder set: ' . 'fi.bestand' . $countFiles);
                    // set the permissions on the file
                    if (!chmod($myTarget, 0644)) { /*some debug function*/ }
                     
                } else {
                    // File not uploaded
                     $modx->log(modX::LOG_LEVEL_ERROR, 'Bestand kon niet worden geupload!' );
                    $errorMsg = 'There was a problem uploading the file.';
                    $hook->addError($sf, $errorMsg);
                    $output = false; // generate submission error
                }
             
            } else {
                // File type not allowed
                 $modx->log(modX::LOG_LEVEL_ERROR, 'Bestandtype niet toegestaan!');
                $errorMsg = 'Type of file not allowed.';
                $hook->addError($sf, $errorMsg);
                $output = false; // generate submission error
            }
         
        // if no file, don't error, but return blank
        } else {
            $hook->setValue($sf, '');
        }
    $countFiles++; 
    }
    $modx->log(modX::LOG_LEVEL_ERROR, 'Continue? ' . $output);
    
    return $output;


    I just don't get it..
    Any help and/or ideas are appreciated!

    Thanks in advance,
    Rik

    This question has been answered by m.engel. See the first response.

    • discuss.answer
      • 40706
      • 128 Posts
      Just a Note, you can easily use MODX to clean up the Filenames, and also use translit if configured
      $filename = $modx->resource->cleanAlias($filename);


      It could be a Problem that you are moving the Files FormIt is Expecting.
      $hook->setValue($sf, '');

      Should called even if no error happens, so FormIt isn`t processing the files anymore.
      FormIt detects File uploads by checking all value for an array containing an key "tmp_name"
      [ed. note: m.engel last edited this post 7 years, 7 months ago.]
        • 52615
        • 10 Posts
        Hi Michael,

        Thnx for the advice for cleaning up the filenames, definitely more clean. Furthermore there are a lot more optimization options.. my first goal was to get it even working;-)

        $hook->setValue($sf, '');

        This is a great contribution, thank you! The file is uploaded and the mail is correctly sent (without the file(s)).

        Still I don't understand why the two hooks can't work together. Anyway I can go on now, thanks again!



          • 24629
          • 370 Posts
          Hi,
          Im trying the same thing. can you share the working script? that would help me a lot:)
          Tnx
          RDG
            • 52615
            • 10 Posts
            Quote from: rdaneeel at Sep 14, 2016, 07:41 AM
            Hi,
            Im trying the same thing. can you share the working script? that would help me a lot:)
            Tnx
            RDG

            Hi Ralph,

            I still haven't found the time to clean up the code, but it is working.

            Please let us know if it's working for you!

            <?php
            // initialize output;
            $output = true;
             
            // valid extensions
            $ext_array = array('pdf', 'txt', 'doc', 'docx', 'rtf');
             
            // create unique path for this form submission
            $uploadpath = 'assets/manuscripts/';
             
            // Unique file creation 
             function createUploadFilename($currentPath,$currentFilename) {
                  
                  // Create unique filename
                  if(file_exists($currentPath . $currentFilename)) {
                  
                          $i = 0;
                          
                          do {
                            $nF =  $i . $currentFilename;
                            $i++;
                       
                          } while (file_exists($currentPath . $nF));
                  }
                  
                  if(isset($nF)) {
                      $newFilename = $currentPath . $nF;
                      
                  } else {
                      
                      $newFilename = $currentPath . $currentFilename;
                  }
                 
                 return $newFilename;
             }
             
            // get full path to unique folder
            $target_path = $modx->config['base_path'] . $uploadpath;
            $modx->log(modX::LOG_LEVEL_ERROR, 'Target path: ' . $target_path );
            
            // get uploaded file names:
            $submittedfiles = array_keys($_FILES);
             
            // loop through files
            $countFiles = 1;
            foreach ($submittedfiles as $sf) {
             
                // Get Filename and make sure its good.
                $filename = basename( $_FILES[$sf]['name'] );
                $modx->log(modX::LOG_LEVEL_ERROR, 'Filename: ' . $filename);
                
                // Get file's extension
                $ext = pathinfo($filename, PATHINFO_EXTENSION);
                $ext = mb_strtolower($ext); // case insensitive
                $modx->log(modX::LOG_LEVEL_ERROR, 'Extension: ' . $ext );
             
                // is the file name empty (no file uploaded)
                if($filename != '') {
                     
                    // is this the right type of file?
                    if(in_array($ext, $ext_array)) {
                 
                        // clean up filename
                        $filename = $modx->resource->cleanAlias($filename);
                        $modx->log(modX::LOG_LEVEL_ERROR, 'Cleaned file: ' . $filename );
                        
                        $filename = date("Y-d-m_") . $filename; // add date
                        
                        // create directory to move file into if it doesn't exist
                       if(!file_exists($target_path)) {
                           mkdir($target_path, 0755, true);
                           
                       }
                       
                        // Create unique filename
                        $myTarget = createUploadFilename($target_path,$filename);
                        $modx->log(modX::LOG_LEVEL_ERROR, 'Clean and unique filename: ' . $myTarget );
            
                        // is the file moved to the proper folder successfully?
                        if(move_uploaded_file($_FILES[$sf]['tmp_name'], $myTarget)) {
                            // set a new placeholder with the new full path (if you need it in subsequent hooks)
                            $modx->setPlaceholder('fi.bestand' . $countFiles,  $modx->getOption('site_url') . $uploadpath . $filename);
                            
                            $modx->log(modX::LOG_LEVEL_ERROR, 'Placeholder set: ' . 'fi.bestand' . $countFiles);
                            // set the permissions on the file
                            if (!chmod($myTarget, 0644)) { /*some debug function*/ }
                             
                        } else {
                            // File not uploaded
                             $modx->log(modX::LOG_LEVEL_ERROR, 'Bestand kon niet worden geupload!' );
                            $errorMsg = 'There was a problem uploading the file.';
                            $hook->addError($sf, $errorMsg);
                            $output = false; // generate submission error
                        }
                     
                    } else {
                        // File type not allowed
                         $modx->log(modX::LOG_LEVEL_ERROR, 'Bestandtype niet toegestaan!');
                        $errorMsg = 'Type of file not allowed.';
                        $hook->addError($sf, $errorMsg);
                        $output = false; // generate submission error
                    }
                 
                // if no file, don't error, but return blank
                } else {
                    $hook->setValue($sf, '');
                }
            $countFiles++; 
            }
            $modx->log(modX::LOG_LEVEL_ERROR, 'Continue? ' . $output);
            
            $hook->setValue($sf, '');
            return $output;