A client recently asked us to create a members-only curriculum section, which allows certain logged-in users to download from a library of PDFs.
The client also wanted to be able to track which users were downloading which materials in CiviCRM, so they could target the downloaders of certain materials with follow-up e-mail.
To do this, I wrote a very simple Drupal module to log the downloading of materials as an activity in Civi. It hooks Drupal's hook_file_download to make calls to the CiviCRM API. Note that this module probably shouldn't be used as is in your site - it lacks error handling. I'm posting it primarily as learning material. Also, suggestions/feedback are welcome!
// $Id: gap_log_download_civicrm.module
/**
* @file
* Custom functions for this site.
*/
function gap_log_download_civicrm_file_download($uri) {
//This is the activity ID corresponding to "Downloaded Material".
$activity_type_id = 52;
global $user;
$filePathInfo = pathinfo($uri);
$filename = $filePathInfo['filename'];
$uid = $user->uid;
if ($uid == 0) {
return;
}
civicrm_initialize();
//look up the contact_id from the uid.
$params = array(
'version' => 3,
'sequential' => 1,
'uf_id' => $uid,
);
$result = civicrm_api('UFMatch', 'get', $params);
$contact_id = $result['values'][0]['contact_id'];
$params = array(
'version' => 3,
'sequential' => 1,
'activity_type_id' => $activity_type_id,
'source_contact_id' => $contact_id,
'contact_id' => $contact_id,
'activity_subject' => $filename,
);
$result = civicrm_api('Activity', 'create', $params);
}