Drupal download files: Add confirmation to downloads

This CodeLet adds a confirmation form when a user tries to dowload a file from a Drupal site. The data then saved in the db and also mailed to the administrator. Once the form is submitted, file dowload starts. File download start with Jquery after 3 seconds. Administrator can also view all the form submissions.

Drupal download files: Add confirmation to downloads | Drupal Developer
CodeLet: 

.install file

<?php
/**
 * @file
 *
 * Create scheema for downlo addon module
 *
 * @author DrupalD <DrupalD@twitter>
 */


/**
 * Implemenation of hook_schema
 *
 * @author DrupalD <DrupalD@twitter>
 */
function download_addon_schema() {
   
$schema['download_addon_user_data'] = array(
     
'fields' => array(
       
'id' => array(
         
'type' => 'serial',
         
'lenght' => 11,
        ),
       
       
'fid' => array(
         
'type' => 'int',
         
'lenght' => 11,
        ),
       
       
'uid' => array(
         
'type' => 'int',
         
'lenght' => 11,
        ),
       
       
'user_details' => array(
         
'type' => 'text',
         
'not null' => TRUE,
        ),
       
       
'created' => array(
       
'type' => 'int',
       
'lenght' => 11,
      ),
      ),
     
'primary key' => array('id'),
    );
   
    return
$schema;
}
?>

.module file

<?php
/**
 * @file
 *
 * Adds extra fields to file download form.
 *
 * @author DrupalD <DrupalD@twitter>
 */


/**
 * Implementation of hook_menu
 *
 * @author DrupalD <DrupalD@twitter>
 */
function download_addon_menu() {
   
$items = array();
   
$items['thankyou'] = array(
     
'type' => MENU_CALLBACK,
     
'page callback' => 'download_addon_thankyou',
     
'access callback' => TRUE,
    );
   
   
$items['brochure-request'] = array(
     
'type' => MENU_CALLBACK,
     
'page callback' => 'download_addon_brochure_overview',
     
'access callback' => TRUE,
    );   
   
   
$items['brochure-request/%'] = array(
     
'type' => MENU_CALLBACK,
     
'page callback' => 'download_addon_brochure_overview',
     
'page arguments' => array(1),
     
'access callback' => TRUE,
    );   
   
   
   
$items['redirect/%'] = array(
     
'type' => MENU_CALLBACK,
     
'page callback' => 'download_addon_get_file',
     
'page arguments' => array(1),
     
'access callback' => TRUE,
    );
   
   
$items['confirm/%/%'] = array(
     
'type' => MENU_CALLBACK,
     
'page callback' => 'drupal_get_form',
     
'page arguments' => array('_get_user_form', 1),
     
'access callback' => TRUE,
    );
    return
$items;
}



/**
 * Implementation of hook_file_download
 *
 * @param $uri
 * @author DrupalD <DrupalD@twitter>
 */
function download_addon_file_download($uri) {
    return array(
'Content-Type' => file_get_mimetype($uri));
}


/**
 * _get_user_form
 *
 * @param $form
 * @param $form_status
 * @param $sn__fid
 * @param $ss__filename
 *
 * @author DrupalD <DrupalD@twitter>
 */
function _get_user_form($form, $form_status, $sn__fid) {
   
module_load_include('inc', 'popup', 'includes/popup.api');
   
$form['form_id'] = 'user_download_confirm';
   
$form['#help'] = "";
   
$form['fid'] = array(
     
'#type' => 'hidden',
     
'#value' => $sn__fid,
    );
   
   
$form['help_text'] = array(
     
'#markup' => '<p>All demonstrations are conducted from MUMBAI, INDIA having time zone as UTC+5.30.<br>
We are conducting demonstration 24 hours a day and all the 7 days a week. If client needs presentation in KANSAS-USA  AT 10 AM ( KANSAN USA time) and following are the time difference :<br>
For conversion of time zone pl use : <a href="http://www.timeanddate.com/worldclock/converter.html">http://www.timeanddate.com/worldclock/converter.html</a><br>
Mumbai&nbsp;(India - Maharashtra)<br>
Tuesday, 14 May 2013, 00:00:00<br>
IST<br>
UTC+5:30 hours<br>
Topeka&nbsp;(U.S.A. - Kansas)<br>
Monday, 13 May 2013, 13:30:00<br>
CDT<br>
UTC-5 hours<br>
    Date : 15 april 2013<br>
    Local time : 10 am  or (24 hours time )<br>
    TIME ZONE : UTC +  OR UTC-  ( FOR EXAMPLE For India local time is UTC-5 )<br>
You will get the mail on your e-mail id upon clicking the link you will be connected to the secession where you can listen demonstration and see the live demonstration.<br>
<strong>Pre requisite for the demonstration:</strong><br>
Computer/laptop/smart mobile<br>
With internet connection and audio visual facility (Speaker and mike).</p>'
,
    
'#weight' => -12,
    );
   
   
$form['abbrivation'] = array(
     
'#type' => 'select',
     
'#title' => t('Abbreviation'),
     
'#required' => TRUE,
     
'#options' => array(
       
'Mr.' => t('Mr.'),
       
'Mrs.' => t('Mrs.'),
       
'Ms.' => t('Ms.'),
    ),
   
'#weight' => -11,
    );
   
   
$form['first_name'] = array(
     
'#type' => 'textfield',
     
'#title' => t('First name'),
     
'#required' => TRUE,
     
'#weight' => -10,
    );
   
$form['middle_name'] = array(
     
'#type' => 'textfield',
     
'#title' => t('Middle name'),
     
'#required' => TRUE,
     
'#weight' => -9,
    );
   
   
$form['last_name'] = array(
     
'#type' => 'textfield',
     
'#title' => t('Last name'),
     
'#required' => TRUE,
     
'#weight' => -8,
    );
   
   
$form['organization'] = array(
     
'#type' => 'textfield',
     
'#title' => t('Organization'),
     
'#required' => TRUE,
     
'#weight' => -7,
    );
   
   
$form['contact_number'] = array(
     
'#type' => 'textfield',
     
'#title' => t('Contact number'),
     
'#required' => TRUE,
     
'#weight' => -7,
    );
   
   
$form['email'] = array(
     
'#type' => 'textfield',
     
'#title' => t('Email'),
     
'#required' => TRUE,
     
'#weight' => -6,
    );

   
   
$form['brochure_for'] = array(
     
'#type' => 'checkboxes',
     
'#title' => t('Need demonstration/Brochure for'),
     
'#required' => TRUE,
     
'#options' => array(
       
'AUTOSPOOL' => t('AUTOSPOOL'),
       
'SPOOLMAN/ERMAN' => t('SPOOLMAN/ERMAN'),
       
'ISOMEC' => t('ISOMEC'),
       
'MATCONTRK/STOREMAN' => t('MATCONTRK/STOREMAN'),
      ),
     
'#weight' => -5,
    );
   
   
$form['demonstration'] = array(
     
'#type' => 'fieldset',
     
'#title' => t('When you would like to see the demonstration?'),
     
'#required' => TRUE,
     
'#weight' => -4,
    );
   
   
$form['demonstration']['demo_date'] = array(
     
'#type' => 'textfield',
     
'#title' => t('Date'),
     
'#description' => t('Format: dd/mm/YYYY'),
     
'#required' => TRUE,
     
'#weight' => -10,
    );
   
   
$form['demonstration']['localtime'] = array(
     
'#type' => 'textfield',
     
'#title' => t('Local time'),
     
'#required' => TRUE,
     
'#weight' => -9,
    );
   
   
$form['demonstration']['timezone'] = array(
     
'#type' => 'radios',
     
'#title' => t('TIME ZONE'),
     
'#required' => TRUE,
     
'#options' => array(
       
'UTC+' => t('UTC+'),
       
'UTC-' => t('UTC-'),
      ),
     
'#description' => t('For conversion of time zone pl use : #link', array('#link' => 'http://www.timeanddate.com/worldclock/converter.html')),
     
'#weight' => -8,
    );
    
   
$form['city'] = array(
   
'#type' => 'textfield',
   
'#title' => t('City/Town'),
     
'#required' => TRUE,
   
'#weight' => -3,
  );
 
   
$form['country'] = array(
   
'#type' => 'textfield',
   
'#title' => t('Country'),
     
'#required' => TRUE,
   
'#weight' => -2,
  );
 
   
$form['send_product_brochure'] = array(
   
'#type' => 'checkbox',
   
'#title' => t('Please send me product brochure'),
   
'#weight' => -1,
  );
 
   
$form['contact_me'] = array(
   
'#type' => 'checkbox',
   
'#title' => t('Please contact me on phone/email'),
   
'#weight' => 0,
  );
 
   
$form['your_comments'] = array(
   
'#type' => 'textarea',
   
'#title' => t('Any other comments'),
   
'#weight' => 1,
  );
 
   
$form['remark'] = array(
   
'#type' => 'textarea',
   
'#title' => t('Remark'),
   
'#weight' => 2,
  );
 
 
$form['submit'] = array(
   
'#type' => 'submit',
   
'#value' => t('Submit'),
   
'#weight' => 3
 
);
    return
$form;
}


/**
 * _get_user_form_submit
 *
 * @param $form
 * @param $form_state
 * @author DrupalD <DrupalD@twitter>
 */
function _get_user_form_submit($form, &$form_state) {
  global
$user;
    foreach (
$form_state['values']['brochure_for'] as $key => $value) {
        if (
is_string($value)) {
           
$as__brochure_for[] = $value;
        }
    }
   
$sn__fid = $form_state['values']['fid'];
   
$am__values = array(
     
'abbrivation' => $form_state['values']['abbrivation'],
     
'first_name' => $form_state['values']['first_name'],
     
'middle_name' => $form_state['values']['middle_name'],
     
'last_name' => $form_state['values']['last_name'],
     
'organization' => $form_state['values']['organization'],
     
'contact_number' => $form_state['values']['contact_number'],
     
'email' => $form_state['values']['email'],
     
'brochure_for' => implode(', ', $as__brochure_for),
   
'demo_date' => $form_state['values']['demo_date'],
   
'local_time' => $form_state['values']['localtime'],
   
'time_zone' => $form_state['values']['timezone'],
   
'city' => $form_state['values']['city'],
   
'country' => $form_state['values']['country'],
   
'send_product_brochure' => $form_state['values']['send_product_brochure'] != '' ? t('Yes') : t('No'),
   
'contact_me' => $form_state['values']['contact_me'] != '' ? t('Yes') : t('No'),
   
'your_comments' => $form_state['values']['your_comments'],
   
'remark' => $form_state['values']['remark'],
    );
   
   
$sn__id = db_insert('download_addon_user_data')
      ->
fields(array(
       
'fid' => $sn__fid,
       
'uid' => $user->uid,
       
'user_details' => serialize($am__values),
       
'created' => time('now'),
      ))
      ->
execute();
     
$am__values['fid'] = $sn__fid;
     
$ss__to = variable_get('site_mail', ''); //info@eurekadsoft.com
   
$message = drupal_mail('download_addon', 'download_addon_user_data', $ss__to, language_default(), $am__values, $ss__to);
    if(
$message['result'] == 'sent') {
       
watchdog('download_addon', 'Request submitted by %sender', array('%sender' => $am__values['email']));
       
drupal_set_message(t('Your request submitted successfully!'));
    }
     
drupal_goto('thankyou', array('query' => array('fid' => $sn__fid)));
}


/**
 * download_addon_thankyou
 *
 * @param $sn__fid
 * @author DrupalD <DrupalD@twitter>
 */
function download_addon_thankyou() {
  global
$user;
   
$sn__fid = $_GET['fid'];
    unset(
$am__details);
   
$ss__node_title = _get_node_title($sn__fid);
   
$output = t('Thank you for downloading file on @node', array('@node' => $ss__node_title)) .'<br />';;
   
$output = t('Download should start shortly') .'<br />';;
   
$output .= t('Here are your submitted details:') .'<br />';
   
$result _get_user_details($sn__fid);
 
$am__details = unserialize($result['user_details']);
  foreach (
$am__details as $key => $value) {
     
$row[] = array(
       
drupal_ucfirst(str_replace('_', ' ', $key)),
       
$value,
      );
  }
 
$attributes = array('width' => '100%');
 
$output .= theme('table', array('header' => array(),'rows' => $row, 'attributes' => $attributes));
 
$file = db_query('SELECT filename FROM {file_managed} WHERE fid = :fid', array(':fid' => $sn__fid))->fetchAssoc();
 
drupal_add_js(array('download_addon' => array('fid' => $sn__fid)), 'setting');
 
drupal_add_js(array('download_addon' => array('file_name' => $file['filename'])), 'setting');
 
drupal_add_js(drupal_get_path('module', 'download_addon') .'/download_addon.js', 'file');
    return
$output;
   
}


/**
 * _get_user_details
 *
 * @param $sn__fid
 * @author DrupalD <DrupalD@twitter>
 */
function _get_user_details($sn__fid) {
    global
$user;
   
$result = db_select('download_addon_user_data', 'du')
   ->
fields('du')
   ->
condition('fid', $sn__fid, '=')
   ->
condition('uid', $user->uid, '=')
   ->
orderBy('created', 'DESC')
   ->
range(0,1)
   ->
execute()
   ->
fetchAssoc();
  
   return
$result;
}

/**
 * Implementation of hook_mail
 * @param $key
 * @param $message
 * @param $params
 * @author DrupalD <DrupalD@twitter>
 */
function download_addon_mail($key, &$message, $params) {
    switch (
$key) {
        case
'download_addon_user_data':
           
$ss__node_title = _get_node_title($params['fid']);
            unset(
$params['fid']);
            foreach (
$params as $key => $value) {
                if (isset(
$value)) {
                   
$row[] = array(
             
drupal_ucfirst(str_replace('_', ' ', $key)),
             
$value,
            );
                }
          }
         
$attributes = array('width' => '100%');
         
$output = theme('table', array('header' => array(),'rows' => $row, 'attributes' => $attributes));
           
$message['subject'] = t('Inquiry: @node', array('@node' => $ss__node_title));
           
$message['body'][] = $output;
        if (isset(
$params['headers']) && is_array($params['headers'])) { 
       
$message['headers'] += $params['headers'];
      }
            break;
    }
}

/**
 * _get_node_title
 *
 * @param unknown_type $sn__fid
 * @author DrupalD <DrupalD@twitter>
 */
function _get_node_title($sn__fid) {
   
$query = db_select('field_data_field_downloads', 'fdd');
   
$query->join('node', 'n', 'n.nid = fdd.entity_id');
   
$query->fields('n', array('title'))
      ->
condition('fdd.field_downloads_fid', $sn__fid, '=')
      ->
condition('fdd.entity_type', 'node', '=')
      ->
condition('fdd.bundle', 'products', '=');
   
$result = $query->execute();
   
$record = $result->fetchAssoc();
    return
$record['title'];
}

/**
 * download_addon_brochure_overview
 *
 * @author DrupalD <DrupalD@twitter>
 */
function download_addon_brochure_overview($sn__id = NULL) {
    if (
$sn__id == '') {
       
$header = array(t('Email'), t('Contact number'), t('Name'), t('Product'), t('Demo date'));
     
$result = db_select('download_addon_user_data', 'du')
       ->
fields('du')
       ->
execute();
     
$row[] = array('data' => array(t('Email'), t('Contact number'), t('Name'), t('Product'), t('Demo date')));
      while (
$record = $result->fetchAssoc()) {
       
$am__details = unserialize($record['user_details']);
       
$row[] = array(
         
l($am__details['email'], 'brochure-request/'. $record['id']),
         
$am__details['contact_number'],
         
$am__details['first_name'] .' '. $am__details['last_name'],
         
_get_node_title($record['fid']),
         
$am__details['demo_date'],
        );
      }
     
$attributes = array('width' => '100%');
      return
theme('table', array('header' => array(), 'rows' => $row, 'attributes' => $attributes));
    }
    else {
       
$result = db_select('download_addon_user_data', 'du')
       ->
fields('du')
       ->
condition('id', $sn__id, '=')
       ->
execute()
       ->
fetchAssoc();
      
$am__details = unserialize($result['user_details']);
       foreach (
$am__details as $key => $value) {
       
$row[] = array(
         
drupal_ucfirst(str_replace('_', ' ', $key)),
         
$value,
        );
      }
     
$attributes = array('width' => '100%');
      return
l(t('< Back'), 'brochure-request') .'<br />'. theme('table', array('header' => array(),'rows' => $row, 'attributes' => $attributes));
    }
}

/**
 * download_addon_get_file
 *
 * @param unknown_type $sn__fid
 * @author DrupalD <DrupalD@twitter>
 */
function download_addon_get_file($sn__fid) {
   
$file = db_query('SELECT filename FROM {file_managed} WHERE fid = :fid', array(':fid' => $sn__fid))->fetchAssoc();
 
$headers = array(
   
'Pragma' => 'hack',
   
'Cache-Control' => 'public, must-revalidate',
   
'Content-Type' => $file['filemime'],
   
'Content-Disposition' => 'attachment',
   
'Content-Transfer-Encoding' => 'binary',
  );
 
file_transfer($file['filename'], $headers);
}
?>

.js file

jQuery(document).ready(function (){
var myDown = setInterval(function(){get_file()},3000);
var file_id = Drupal.settings.download_addon.fid;
var file_name = Drupal.settings.download_addon.file_name;
function get_file() {
$.ajax({
type: "POST",
url: "resource/" + file_id,
//data: wireIdList,
cache: false,
success: function(response)
{
window.open(response);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('Error occurred while downlodng file');
}
});
clearInterval(myDown);
}
});

Compatibility: 
Is CodeLet useful?: