Task:
- allow file downloads for only registered users in Drupal
- for admins, show download count for each file
- show which user downloaded which files
The download_count module is great for #1 and #2. However, it doesn’t save any information about users.
Here’s some modifications I’ve added to it to accomplish #3.
In the download_count.module file, find download_count_file_download() function. It saves the information about downloaded files into “file_downloads” table.
- I created another similar table, called it “file_download_users” (columns: filename, user_id, timestamp) where I am going to save information about each download and keep user IDs.
- Made sure I use global $user in this function
- Insert the information about users into my new table:
db_query(“INSERT INTO {file_downloads_users} (filename, user_id, timestamp) VALUES (‘%s’, %d,%d)”, $filename, $user->uid, time());
Now I write my own hook_user function:
<?php/**
* Implementation of hook_user()
*/
function download_count_user($op, &$edit, &$account, $caterory = NULL) {
if ($op == 'view')
{
$result = db_query("SELECT filename FROM file_downloads_users WHERE user_id = %d", $account->uid);
while ($file_array = db_fetch_object($result)) {
$file_str .= $file_array->filename . '<br/>';
}
$account->content['summary']['file_downloads'] = array(
'#type' => 'user_profile_item',
'#title' => t('File Downloads'),
'#value' => $file_str,
'#weight' => 1
);
}
}
?>
The above is Drupal 6 version. First I wrote one for Drupal 5 and it just didn’t work for me, until some nice fellow from StackOverflow pointed out the difference between 5 and 6 when it comes to handling user hooks.
Here’s the Drupal 5 version:
<?php
function download_count_user($op, &$edit, &$account, $caterory = NULL) {
if ($op == 'view')
{
$result = db_query("SELECT filename FROM file_downloads_users WHERE user_id = %d", $account->uid);
while ($file = db_fetch_object($result)) {
$file_str .= $file->filename . '<br/>';
}
$items['downloads'] = array(
'title' => t('Files'),
'value' => $file_str,
'class' => 'member'
);
return array(t('Downloads')=>$items);
}
}
?>
Now when you login into your user account after downloading some files, you’ll see that info displayed as a part of your user profile:
