'.t('WebFM is a hierarchical file system manager.
WebFM does not use a flat file system (a single directory indexed by a
database). WebFM allows users to arrange files on the server in the
same way they do on their local storage drives. This ability to
heirarchically arrange files greatly enhances the managability of large
collections of data.').'
'.
'
'.t('Note that webfm uses includes/file.inc which manages the
file system path. The Root Directory and Ftp root directory
paths are relative to the file system path set at %file-sys and
must be prefaced with a "/".', array('%file-sys' => url('admin/settings/file-system')))
.'
'.'
'.t('WebFM uses ajax and javascript extensively to provide
application intensive functionality such as file/dir move and ordering
of attachments via drag-and-drop. The context menuing provided by the
right mouse button click provides context sensitive menus for user
selection. Javascript must be enabled for webfm to function.').'
'.
'
'.t('WebFM presents left hand blocks to represent directory
trees and a right hand block to list the contents of the current
directory. The upper left block represents the directory structure of
file data enumerated in the database and available to the site for
metadata/attachment to content.').'
'.
'
'.t('File uploads via the UI that overwrite existing files present
version options to allow the user to transfer the existing fid and
metadata to the newer file. This allows content to be updated
such that attachments and metadata are preserved.').'
';
return $output;
case 'admin/modules#description':
return t('Enable the Web File Manager.');
}
}
/**
* Implementation of hook_link().
*/
function webfm_link($type, $node = NULL, $teaser = FALSE) {
$links = array();
// Display a link with the number of attachments
if ($teaser && $type == 'node' && isset($node->webfm_files) && user_access('view webfm attachments')) {
if($num_files = count($node->webfm_files)) {
$links['webfm_attachments'] = array(
'title' => format_plural($num_files, '1 attachment', '@count attachments'),
'href' => "node/$node->nid",
'attributes' => array('title' => t('Read full article to view attachments.')),
'fragment' => 'attachments');
}
}
return $links;
}
/**
* Form API callback to validate the webfm settings form.
*/
function webfm_admin_settings_validate($form_id, $form_values) {
$valid_webfm_root = FALSE;
$webfm_root_dir_name = $form_values['webfm_root_dir'];
if(!empty($webfm_root_dir_name)) {
if(!preg_match('/^[0-9a-zA-Z]/', $webfm_root_dir_name)) {
form_set_error('webfm_root_dir'. $rid, t('The leading character of the webfm root directory name must be alphanumeric.'));
} else if(preg_match('[\.]', $webfm_root_dir_name)) {
form_set_error('webfm_root_dir'. $rid, t('The webfm root directory name is not valid.'));
} else {
$webfm_root_dir = file_directory_path()."/".$webfm_root_dir_name;
$valid_webfm_root = file_check_directory($webfm_root_dir, FILE_CREATE_DIRECTORY, 'webfm_root_dir');
}
}
if(($form_values['webfm_max_resolution'] != '0')) {
if(!preg_match('/^[0-9]+[xX][0-9]+$/', $form_values['webfm_max_resolution'])) {
form_set_error('webfm_max_resolution', t('The maximum allowed image size expressed as WIDTHxHEIGHT (e.g. 640x480). Set to 0 for no restriction.'));
}
}
$exceed_max_msg = t('Your PHP settings limit the maximum file size per upload to %size MB.', array('%size' => file_upload_max_size())).' ';
$more_info = t("Depending on your sever environment, these settings may be changed in the system-wide php.ini file, a php.ini file in your Drupal root directory, in your Drupal site's settings.php file, or in the .htaccess file in your Drupal root directory.");
$max_upload_size = file_upload_max_size()/(1024*1024);
foreach($form_values['roles'] as $rid => $role) {
$uploadsize = $form_values['webfm_uploadsize_'. $rid];
$usersize = $form_values['webfm_usersize_'. $rid];
$role_root_dir_name = $form_values['root_dir_'.$rid];
if(!empty($role_root_dir_name)) {
if($valid_webfm_root) {
if(!preg_match('/^[0-9a-zA-Z]/', $role_root_dir_name)) {
form_set_error('root_dir_'. $rid, t('The leading character of the %role root directory must be alphanumeric.', array('%role' => $role)));
} else if(preg_match('[\.]', $role_root_dir_name)) {
form_set_error('root_dir_'. $rid, t('The %role root directory name is not valid.', array('%role' => $role)));
} else {
$role_root_dir = $webfm_root_dir."/".$role_root_dir_name;
file_check_directory($role_root_dir, FILE_CREATE_DIRECTORY, 'root_dir_'.$rid);
}
} else {
form_set_error('root_dir_'. $rid, t('The WebFM root directory must be valid for the %role root directory name to be valid.', array('%role' => $role)));
}
}
if(!is_numeric($uploadsize) || ($uploadsize <= 0)) {
form_set_error('webfm_uploadsize_'. $rid, t('The %role file size limit must be a number and greater than zero.', array('%role' => $role)));
}
if(!is_numeric($usersize) || ($usersize <= 0)) {
form_set_error('webfm_usersize_'. $rid, t('The %role file size limit must be a number and greater than zero.', array('%role' => $role)));
}
if($uploadsize > $max_upload_size) {
form_set_error('webfm_uploadsize_'. $rid, $exceed_max_msg . $more_info);
$more_info = '';
}
if($uploadsize > $usersize) {
form_set_error('webfm_uploadsize_'. $rid, t('The %role maximum file size per upload is greater than the total file size allowed per user', array('%role' => $role)));
}
}
}
/**
* Implementation of hook_settings().
*/
function webfm_admin_settings() {
global $user;
$modulepath = drupal_get_path('module', 'webfm');
$form['webfm_root_dir'] =
array('#type' => 'textfield',
'#title' => t('WebFM root directory'),
'#default_value' => variable_get('webfm_root_dir', ''),
'#maxlength' => '100',
'#size' => '70',
'#description' => t('Root directory used to present the filebrowser user interface.
This path is relative to "File system path" set in admin/settings/file-system.
If this directory path is compound (ie: path/to/root) then the path must already
exist for this setting to validate (ie: path/to).')
);
$form['webfm_icon_dir'] =
array('#type' => 'textfield',
'#title' => t('Icon directory'),
'#default_value' => variable_get('webfm_icon_dir', $modulepath. '/image/icon'),
'#maxlength' => '100',
'#size' => '70',
'#description' => t('Name of directory where file type icons are stored (relative to base url).')
);
$form['webfm_max_resolution'] =
array('#type' => 'textfield',
'#title' => t('Maximum resolution for uploaded images'),
'#default_value' => variable_get('webfm_max_resolution', 0),
'#size' => 15,
'#maxlength' => 10,
'#description' => t('The maximum allowed image size (e.g. 640x480). Set to 0 for no restriction.'),
'#field_suffix' => ''. t('WIDTHxHEIGHT') .''
);
$form['webfm_date_format'] =
array('#type' => 'radios',
'#title' => t('Date Format'),
'#default_value' => variable_get('webfm_date_format', WEBFM_DATE_FORMAT_DAY),
'#options' => array(WEBFM_DATE_FORMAT_DAY => t('dd/mm/yy'), WEBFM_DATE_FORMAT_MONTH => t('mm/dd/yy')),
'#description' => t('Set the order of day/month in date fields.')
);
$form['file_perm'] =
array('#type' => 'fieldset',
'#title' => t('Default File Permissions'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
'#description' => t('Default permissions applied to a file when inserted into the database.
If all boxes are unchecked only the file owner and administrators will have
access to the file via the filebrowser. File owners and admins can change
these settings for each individual file within the filebrowser UI.')
);
$form['file_perm']['webfm_file_perm_role'] =
array('#type' => 'checkbox',
'#title' => t('Role View Access'),
'#default_value' => variable_get('webfm_file_perm_role', ''),
'#description' => t('File is viewable/downloadable in the filebrowser by role.')
);
$form['file_perm']['webfm_file_perm_mod'] =
array('#type' => 'checkbox',
'#title' => t('Role Full Access'),
'#default_value' => variable_get('webfm_file_perm_mod', ''),
'#description' => t('Roles that can access this file via the filebrowser have the same access rights as the
file owner except for the right to change the file permissions.')
);
$form['file_perm']['webfm_file_perm_attach'] =
array('#type' => 'checkbox',
'#title' => t('Role Attach Access'),
'#default_value' => variable_get('webfm_file_perm_attach', ''),
'#description' => t('Roles that can access this file via the filebrowser have the right to attach it to content.')
);
$form['file_perm']['webfm_file_public'] =
array('#type' => 'checkbox',
'#title' => t('Public Access'),
'#default_value' => variable_get('webfm_file_public', ''),
'#description' => t('File is downloadable anonymously via webfm_send.')
);
$roles = user_roles(0,'access webfm');
$form['roles'] = array('#type' => 'value', '#value' => $roles);
// Flush extensions regex cache for upload and db enum
webfm_get_extensions_regex(WEBFM_FLUSH);
foreach ($roles as $rid => $role) {
$form["settings_role_".$rid] =
array('#type' => 'fieldset',
'#title' => t('Settings for @role role', array('@role' => $role)),
'#collapsible' => TRUE,
'#collapsed' => TRUE
);
$form["settings_role_".$rid]["root_dir_".$rid] =
array('#type' => 'textfield',
'#title' => t('Role Root directory'),
'#default_value' => variable_get("root_dir_".$rid, ''),
'#maxlength' => '100',
'#size' => '70',
'#description' => t('Root directory for this role.
This path is relative to "WebFM Root directory" set above.
If this directory path is compound then the path must already exist for this
setting to validate.')
);
$form["settings_role_".$rid]["webfm_extensions_".$rid] =
array('#type' => 'textfield',
'#title' => t('Permitted file extensions'),
'#default_value' => variable_get("webfm_extensions_".$rid, "jpg jpeg gif png txt html htm doc xls pdf ppt pps"),
'#maxlength' => 255,
'#description' => t('Extensions that users in this role can upload. Separate extensions with a space
and do not include the leading dot.')
);
$form["settings_role_".$rid]["webfm_uploadsize_".$rid] =
array('#type' => 'textfield',
'#title' => t('Maximum file size per upload'),
'#default_value' => variable_get("webfm_uploadsize_".$rid, 1),
'#size' => 5,
'#maxlength' => 5,
'#description' => t('The maximum size of a file a user can upload (in megabytes).
Cannot exceed %size limit set in php.ini.', array('%size' => format_size(file_upload_max_size())))
);
$form["settings_role_".$rid]["webfm_usersize_".$rid] =
array('#type' => 'textfield',
'#title' => t('Total file size per user'),
'#default_value' => variable_get("webfm_usersize_".$rid, 10),
'#size' => 5,
'#maxlength' => 5,
'#description' => t('The maximum size of all files a user can have on the site (in megabytes).')
);
}
$form['attach'] =
array('#type' => 'fieldset',
'#title' => t('WebFM attachments'),
'#collapsible' => TRUE,
'#collapsed' => TRUE
);
$form['attach']['webfm_attach_body'] =
array('#type' => 'checkbox',
'#title' => t('Append file links to Node Body'),
'#default_value' => variable_get('webfm_attach_body', ''),
'#description' => t('Check this box to append file attachments table to the node body.
This setting does not affect the attachment block.')
);
$form['attach']['webfm_attach_new_window'] =
array('#type' => 'checkbox',
'#title' => t('Open attachments in a new browser window'),
'#default_value' => variable_get('webfm_attach_new_window', '')
);
$form['attach']['attrib'] =
array('#type' => 'fieldset',
'#title' => t('Attachment List Properties'),
);
$form['attach']['attrib']['webfm_attach_desc'] =
array('#type' => 'checkbox',
'#title' => t('Include file description metadata'),
'#default_value' => variable_get('webfm_attach_desc', ''),
'#description' => t('Check this box to add file description metadata beneath the attachment title.')
);
$form['attach']['attrib']['webfm_attach_date'] =
array('#type' => 'checkbox',
'#title' => t('Enable file date column'),
'#default_value' => variable_get('webfm_attach_date', ''),
'#description' => t('Check this box to add a create date column to the attachment table.')
);
$form['attach']['attrib']['webfm_attach_size'] =
array('#type' => 'checkbox',
'#title' => t('Enable file size column'),
'#default_value' => variable_get('webfm_attach_size', ''),
'#description' => t('Check this box to add a file size column to the attachment table.')
);
if($user->uid == 1) {
//only user #1 gets this access
$form['ie'] =
array('#type' => 'fieldset',
'#title' => t('IE Drag-and-Drop Normalization'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
'#description' => t('number of pixels to offset drag objects from cursor position in IE browser. This quantity is usually related to relative positioning used by the css.')
);
$form['ie']['webfm_ie_dd_list_offset'] =
array('#type' => 'textfield',
'#title' => t('IE drag and drop x-axis offset for right hand listing draggables'),
'#default_value' => variable_get('webfm_ie_dd_list_offset', '-190'),
'#maxlength' => '10',
'#size' => '10',
);
$form['ie']['webfm_ie_dd_tree_offset'] =
array('#type' => 'textfield',
'#title' => t('IE drag and drop x-axis offset for directory tree draggables'),
'#default_value' => variable_get('webfm_ie_dd_tree_offset', '-34'),
'#maxlength' => '10',
'#size' => '10',
);
}
$form['debug'] =
array('#type' => 'fieldset',
'#title' => t('WebFM debug'),
'#collapsible' => TRUE,
'#collapsed' => TRUE
);
$form['debug']['webfm_debug'] =
array('#type' => 'checkbox',
'#title' => t('WebFM javascript debug'),
'#default_value' => variable_get('webfm_debug', ''),
'#description' => t('Check this box for javascript debug messaging.')
);
if($user->uid == 1) {
//only user #1 gets this access
$form['debug']['webfm_cron'] =
array('#type' => 'checkbox',
'#title' => t('WebFM cron'),
'#default_value' => variable_get('webfm_cron', ''),
'#description' => t('Check this box to enable cleanup of orphaned file records in the database.
NOTE: Use with caution - behaviour is to delete all file records without a
valid file path. Manually renaming a WebFM directory (ie: via OS shell)
and then running cron will delete all webfm_file table entries for that
directory and it\'s sub-directories.')
);
}
return system_settings_form($form);
}
/**
* Implementation of hook_perm().
*/
function webfm_perm() {
return array('access webfm', 'view webfm attachments', 'administer webfm', 'webfm upload');
}
/**
* Implementation of hook_menu().
*/
function webfm_menu($maycache) {
$items = array();
if ($maycache) {
$items[] = array(
'title' => t('Web File Manager'),
'path' => 'webfm',
'access' => user_access('access webfm'),
'callback' => 'webfm_main');
$items[] = array(
'title' => t('Web File Manager'),
'path' => 'webfm_js',
'access' => user_access('access webfm'),
'callback' => 'webfm_ajax',
'type' => MENU_CALLBACK);
$items[] = array(
'title' => t('Web File Manager'),
'path' => 'webfm/upload',
'access' => user_access('access webfm'),
'callback' => 'webfm_upload',
'type' => MENU_CALLBACK);
$items[] = array(
'title' => t('File Not Found'),
'path' => 'webfm_send',
'access' => true,
'callback' => 'webfm_send_file',
'type' => MENU_CALLBACK);
$items[] = array('path' => 'admin/settings/webfm',
'title' => t('Web File Manager Settings'),
'description' => t('Configure WebFM.'),
'callback' => 'drupal_get_form',
'callback arguments' => array('webfm_admin_settings'),
'access' => user_access('administer webfm'),
'type' => MENU_NORMAL_ITEM);
}
return $items;
}
/**
* Implementation of hook_block().
*/
function webfm_block($op = 'list', $delta = 0) {
if ($op == 'list') {
$blocks[0]['info'] = t('WebFM File Attachments');
return $blocks;
}
else if ($op == 'view' &&
user_access('access content') &&
user_access('view webfm attachments')) {
$block['content'] = webfm_attach_box();
$block['subject'] = t('Attachments');
return $block;
}
}
/**
* Implementation of hook_cron().
*/
function webfm_cron() {
//cleanup any corrupted file records that have no physical files
//Warning - running this after renaming a directory outside of WebFM will
// delete all file records contained in that directory
if(variable_get('webfm_cron','')) {
$result = db_query('SELECT fpath, fid FROM {webfm_file}');
while ($f = db_fetch_array($result)) {
if(!(is_file($f['fpath']))) {
_webfm_dbdelete_file_fid($f['fid']);
}
}
}
}
/**
* Implementation of hook_nodeapi().
*/
function webfm_nodeapi(&$node, $op, $teaser) {
switch ($op) {
case 'load':
if ((variable_get("wfm_attach_$node->type", 1) == 1) &&
user_access('view webfm attachments')) {
$output['webfm_files'] = webfm_get_attachments($node->nid);
}
return $output;
break;
case 'view':
// Add the attachments list to node body if configured to appear in body
if (is_array($node->webfm_files) && variable_get('webfm_attach_body', '')) {
if (count($node->webfm_files) && !$teaser) {
$node->content['webfm_attachments'] = array(
'#value' => theme('webfm_attachments', $node->webfm_files),
'#weight' => 10,
);
drupal_add_css(drupal_get_path('module', 'webfm').'/css/webfm.css');
}
}
break;
case 'insert':
if($_POST['attachlist']) {
$files = explode(',', $_POST['attachlist']);
$i = 0;
foreach($files as $fid) {
if($fid)
// weight argument determined by position in csv
webfm_dbinsert_attach($node->nid, $fid, $i++);
}
}
break;
case 'update':
$files = explode(',', $_POST['attachlist']);
webfm_dbupdate_attach($node->nid, $files);
break;
}
}
/**
* Implementation of hook_form_alter().
*/
function webfm_form_alter($form_id, &$form) {
global $base_url;
global $user;
if(($user->uid == 1) || user_access('administer webfm') || user_access('access webfm'))
$access = TRUE;
else
$access = FALSE;
if ($form_id == 'node_type_form' && $access) {
$form['workflow']['webfm_attach'] = array(
'#type' => 'radios',
'#title' => t('WebFM Attachments'),
'#default_value' => variable_get('webfm_attach_'.$form['#node_type']->type, 0),
'#options' => array(0 => t('Disabled'), 1 => t('Enabled')),
'#description' => t('Should this content type allow upload & file attachment via WebFM?'),
);
}
if (isset($form['type'])) {
$node = $form['#node'];
if ($access &&
$form['type']['#value'] .'_node_form' == $form_id &&
variable_get('webfm_attach_'.$node->type, 0)) {
$modulepath = drupal_get_path('module', 'webfm');
drupal_add_js($modulepath.'/js/webfm.js');
drupal_add_css($modulepath.'/css/webfm.css');
if(is_null($inline_js)) {
$clean_url = variable_get('clean_url', 0);
$clean = (($clean_url == 0) || ($clean_url == '0')) ? FALSE : TRUE;
$inline_js = webfm_inline_js($base_url, $clean, $user->uid);
}
// Attachments fieldset
$form['webfm-attach']['#theme'] = 'webfm_upload_form';
$form['webfm-attach']['attach'] = array(
'#type' => 'fieldset',
'#title' => t('WebFM Attachments'),
'#description' => t('Drag attachments to set order. Changes made to the attachments are not permanent until you save this post.'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
'#weight' => 29,
);
$form['webfm-attach']['attach']['attachedfiles'] = array(
'#prefix' => '
'."\n";
return $output;
}
function webfm_upload_fieldset() {
$form = array();
$form['webfm_uploads'] = array(
'#type' => 'fieldset',
'#title' => t('File Upload'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
'#description' => t('Uploaded file will be saved to the current directory.'),
'#prefix' => '
',
'#suffix' => '
',
'#weight' => 30);
// Wrapper for fieldset contents (used by upload JS).
// NOTE: upload.js requires six char prefix on wrapper/button names
$form['webfm_uploads']['wrapper'] = array(
'#prefix' => '
',
'#suffix' => '
');
$form['webfm_uploads']['wrapper'] += webfm_upload_form('webfm/upload');
$form['#attributes'] = array('enctype' => "multipart/form-data");
return $form;
}
function webfm_upload_form($upload_url) {
$form['#theme'] = 'webfm_upload_form';
// This div is hidden when the user uploads through JS.
$form['new'] = array( '#prefix' => '
', '#suffix' => '
');
// this following key used by file_check_upload(()
$form['new']['webfm_upload'] = array('#type' => 'file', '#title' => t('Upload file'), '#size' => 40);
$form['new']['wfmatt'] = array('#type' => 'button', '#value' => t('Upload'), '#name'=> 'attach', '#id' => 'wfmatt-button');
// Hidden input field for js to supply current directory value
$form['webfmuploadpath'] = array('#type' => 'hidden', '#value' => '');
// The class triggers the js upload behaviour.
$form['wfmatt-url'] = array('#type' => 'hidden', '#value' => url($upload_url, NULL, NULL, TRUE), '#attributes' => array('class' => 'webfmupload'));
return $form;
}
function webfm_version_form($filename) {
$form['select'] = array(
'#prefix' => '
',
'#suffix' => '
',
'#type' => 'radios',
'#title' => t('Select File Versioning Option'),
'#options' => array('Replace and rename original copy of '.$filename,'Replace and delete original copy of '.$filename,'Rename new copy of '.$filename,'Cancel'),
'#required' => TRUE,
);
return $form;
}
/**
* Theme the attachment form.
* Note: required to output prefix/suffix.
*/
function theme_webfm_upload_form($form) {
$output = drupal_render($form);
return $output;
}
/**
* Inline javascript
* Function to pass base_url, icon directory, debug and cleanurl flags
*/
function webfm_inline_js($base_url, $clean_url, $uid) {
$js = '' ;
drupal_set_html_head($js);
return $js;
}
/**
* Helper function to check for root path at base of input path
*/
function webfm_check_path($path, $root) {
if(strncmp($path, $root, strlen($root)) == 0) {
if((strlen($path) == strlen($root)) ||
(substr($path, strlen($root), 1) == '/')) {
return $path;
}
}
return '';
}
/**
* Helper function to get root path of webfm
*/
function webfm_get_root_path () {
static $webfm_root_path;
//Get root directory of module
if(empty($webfm_root_path)) {
$webfm_root_path = variable_get('webfm_root_dir', '');
if(empty($webfm_root_path)) {
$webfm_root_path = NULL;
} else {
$webfm_root_path = '/'.$webfm_root_path;
}
}
return $webfm_root_path;
}
/**
* Helper function to get array of role root directories for a user
*/
function webfm_get_root_dirs($flush = FALSE) {
global $user;
static $webfm_access_roles = array();
static $webfm_roots = array();
if($flush)
$webfm_access_roles = array();
// Roles with 'access webfm' perm
if(!count($webfm_access_roles)) {
//allow anonymous role to have 'access webfm' right
$webfm_access_roles = user_roles(FALSE, 'access webfm');
$webfm_roots = array();
foreach($user->roles as $key => $role) {
if(array_key_exists($key, $webfm_access_roles)) {
// Roles with 'access webfm' perm that user possesses
$path = variable_get("root_dir_".$key, '');
if(!empty($path)) {
// Prevent redundant trees for roles with common root dir
if(!in_array($path, $webfm_roots)) {
$webfm_roots[$key] = "/".$path;
}
}
}
}
//If anonymous role has webfm access...
if(array_key_exists(1, $webfm_access_roles)) {
$path = variable_get("root_dir_1", '');
if(!empty($path)) {
$webfm_roots[1] = "/".$path;
}
}
}
return $webfm_roots;
}
/**
* Helper function to determine if a webfm_file record is modifiable by a
* user with 'access webfm'
*/
function webfm_file_mod_access($webfm_file) {
if((int)$webfm_file->perm & WEBFM_FILE_ACCESS_ROLE_FULL) {
return webfm_path_access($webfm_file->fpath);
}
return FALSE;
}
/**
* Helper function to determine if a webfm_file record is viewable by a
* user with 'access webfm'
*/
function webfm_file_view_access($webfm_file) {
if((int)$webfm_file->perm & WEBFM_FILE_ACCESS_ROLE_VIEW) {
return webfm_path_access($webfm_file->fpath);
}
return FALSE;
}
function webfm_file_att_access($webfm_file) {
if((int)$webfm_file->perm & WEBFM_FILE_ACCESS_ROLE_ATTACH) {
return webfm_path_access($webfm_file->fpath);
}
return FALSE;
}
/**
* Helper function to determine if a path is accessible by a user with 'access webfm'
*/
function webfm_path_access($path) {
//admins don't call this routine so include webfm root path
$root_dir = file_directory_path().webfm_get_root_path();
$webfm_roots = webfm_get_root_dirs();
foreach($webfm_roots as $key => $sub_root) {
// The read path must be contained within a legitimate role root dir for this user
if(webfm_check_path($path, $root_dir.$sub_root)) {
return TRUE;
}
}
return FALSE;
}
/**
* Helper function to set default file permissions
*/
function webfm_default_file_perm() {
$perm = (int)(variable_get('webfm_file_perm_role', '') ? WEBFM_FILE_ACCESS_ROLE_VIEW : 0);
$perm += (int)(variable_get('webfm_file_perm_mod', '') ? WEBFM_FILE_ACCESS_ROLE_FULL : 0);
$perm += (int)(variable_get('webfm_file_perm_attach', '') ? WEBFM_FILE_ACCESS_ROLE_ATTACH : 0);
$perm += (int)(variable_get('webfm_file_public', '') ? WEBFM_FILE_ACCESS_PUBLIC_VIEW : 0);
return $perm;
}
/**
* Helper function to get date format string
*/
function webfm_get_date_format() {
static $dateformat;
if(!$dateformat) {
$date_format_type = (variable_get('webfm_date_format', WEBFM_DATE_FORMAT_DAY));
switch($date_format_type)
{
case WEBFM_DATE_FORMAT_MONTH:
$dateformat = 'm/d/y g:i a';
break;
case WEBFM_DATE_FORMAT_DAY:
default:
$dateformat = 'd/m/y g:i a';
break;
}
}
return $dateformat;
}
/**
* Class to build the directory, file and breadcrumb listings
* ..for the directory at $path for javascript Load_dirlist()
*/
class webfm_build_dir_list {
var $dirs = array();
var $files = array();
var $breadcrumb = array();
//Constructor
function webfm_build_dir_list($root, $path, $perm) {
global $user;
$bl = array('.', '..', '.htaccess');
$_dirs = array();
$_files = array();
$full_path = $root.$path;
if(is_dir($full_path)) {
chdir($full_path);
if($handle = opendir('.')) {
// breadcrumb keeps file-sys root hidden
$non_root_arr = explode('/', trim($path, '/'));
foreach($non_root_arr as $piece) {
$this->breadcrumb[] = $piece;
}
while(($readdir = readdir($handle)) !== false) {
// check that directory element is readable and not in black list
if(!in_array(strtolower($readdir), $bl)){
if(is_dir($readdir))
$_dirs[] = $readdir;
if(is_file($readdir))
$_files[] = $readdir;
}
}
closedir($handle);
}
if(is_array($_dirs)) {
foreach($_dirs as $dir) {
$dd = new stdClass();
$dd->n = $dir;
$dd->p = $path."/".$dir;
$dd->m = (filemtime($dir)) ? @filemtime($dir) : "";
$this->dirs[] = $dd;
}
}
if(is_array($_files)) {
foreach($_files as $file) {
if($_file = webfm_get_file_record('', $full_path.'/'.$file)) {
if(($perm == WEBFM_ADMIN) ||
($_file->uid == $user->uid) ||
((int)$_file->perm & WEBFM_FILE_ACCESS_ROLE_FULL) ||
((int)$_file->perm & WEBFM_FILE_ACCESS_ROLE_VIEW)) {
$fd = new stdClass();
$fd->id = $_file->fid;
if((int)$_file->perm & WEBFM_FILE_ACCESS_ROLE_FULL) {
// A bit of a hack for js functionality but safe since this is
// always validated on server side
$fd->u = $user->uid;
} else {
$fd->u = $_file->uid;
}
$fd->m = @filemtime($file);
$fd->s = @filesize($file);
} else {
// permission denied to view this file
continue;
}
} else if($perm == WEBFM_ADMIN) {
$fd = new stdClass();
$fd->id = 0; //invalid fid signals no db entry
$fd->u = 0; //file has no owner
$fd->m = @filemtime($file);
$fd->s = @filesize($file);
} else {
// permission denied to view this file
continue;
}
$fd->n = $file;
$fd->p = $path;
//if file is an image...
if($i = @getimagesize($file)) {
//if valid width/height...
if(($i[0] != 0) && ($i[1] != 0))
//return type
$fd->i = $i[2];
} else
$fd->i = 0;
if(strpos($file, ".") === false) {
$fd->e = "";
} else {
$fd->e = strtolower(substr($file, strrpos($file, ".") + 1));
}
$this->files[] = $fd;
}
}
}
}
function get_dir_listing() {
return $this->dirs;
}
function get_file_listing() {
return $this->files;
}
function get_breadcrumb() {
return $this->breadcrumb;
}
}
/**
* Build directory tree
*/
function webfm_tree($rootpath, $path) {
if(!isset($_SESSION['tree_'.$path])) {
$tree = array();
$tree[$path] = recurse_build_tree($rootpath.$path, false);
$_SESSION['tree_'.$path] = $tree;
return $tree;
}
return $_SESSION['tree_'.$path];
}
// Function to recursively read the complete directory tree
function recurse_build_tree($dir, $full) {
if ($handle = opendir($dir)) {
while (false !== ($readdir = readdir($handle))) {
if(($readdir != '.') && ($readdir != '..')) {
$path = $dir.'/'.$readdir;
//directories are array keys with an array value or a null value for
//empty directories (note that a file cannot have a null value)
if(is_dir($path)) {
$tree[$readdir] = recurse_build_tree($path, $full);
}
if($full == true) {
//files are non-null, non-array key values
if(is_file($path))
$tree[] = $readdir;
}
}
}
closedir($handle);
}
return isset($tree)?$tree:'';
}
function webfm_get_attachments($nid) {
$files = array();
$file_result = db_query('SELECT * FROM {webfm_file} f INNER JOIN {webfm_attach} a ON f.fid = a.fid WHERE a.nid = %d ORDER BY a.weight', $nid);
while($file_record = db_fetch_object($file_result)) {
$_file = new webfm_fdesc($file_record);
if($_file->result == TRUE) {
$files[] = $_file;
}
}
return $files;
}
/**
* File description class
*/
class webfm_fdesc {
var $result;
// Constructor:
function webfm_fdesc($file) {
$cwd = getcwd();
$this->result = FALSE;
$dir = dirname($file->fpath);
//assume the object $file record path has a directory before the file name
if (is_dir($dir)) {
if(chdir($dir)) {
if($handle = opendir('.')) {
while(($readdir = readdir($handle)) !== false) {
if(is_dir($readdir))
continue;
if(is_file($readdir) && ($readdir == basename($file->fpath))) {
$this->id = $file->fid;
$this->n = strrev(substr(strrev($file->fpath), 0, strpos(strrev($file->fpath), '/')));
$this->p = $dir;
$this->e = $file->fmime;
$this->s = $file->fsize;
$this->uid = $file->uid;
/* rename fields for expected js variables
$this->fid = $file->fid;
$this->fpath = $file->fpath;
$this->fname = $file->fname;
$this->fsize = $file->fsize;
$this->fmime = $file->fmime;
*/
// urldecode required for fields where user input is urlencoded
$this->ftitle = urldecode($file->ftitle);
$this->fdesc = urldecode($file->fdesc);
$this->fcreatedate = $file->fcreatedate;
$this->flang = urldecode($file->flang);
$this->fpublisher = urldecode($file->fpublisher);
$this->fformat = urldecode($file->fformat);
$this->fversion = $file->fversion;
$this->m = (filemtime($readdir)) ? @filemtime($readdir) : "";
if($i = @getimagesize($readdir)) {
$this->w = (int) $i[0];
$this->h = (int) $i[1];
$this->i = $i[2];
if(($i[0] == 0) || ($i[1] == 0))
$this->i = 0;
} else
$this->i = 0;
$this->result = TRUE;
break;
}
}
closedir($handle);
}
// Restore current working directory
chdir($cwd);
}
}
}
}
/**
* Function to sanitize long filenames
*/
function webfm_sanlen($x) {
if(strlen($x) > 80)
return substr($x, 0, 40)."...".substr($x, -40, 40);
return $x;
}
/**
* Class to search for files matching a regexp pattern
*/
class webfm_searchFiles {
var $count = 0;
var $files = array();
var $hidefilepattern;
var $uid = 0;
//Constructor
function webfm_searchFiles($root_dir, $dir, $searchpattern, $regexpsearch = FALSE, $user) {
$this->hidefilepattern = "^(CVS|\..*)$";
/*
if(!$regexpsearch) {
$searchpattern = "^".str_replace("*", ".*", str_replace("?", ".", str_replace(".", "\.", $searchpattern)))."$";
}
*/
$this->uid = $user;
$this->searchFilesRecur($root_dir, $dir, $searchpattern);
}
function get_files() {
return $this->files;
}
function get_count() {
return $this->count;
}
function build_file_list($name, $path, $id) {
$sfd = new stdClass();
$sfd->n = $name;
$sfd->p = $path;
$sfd->id = $id;
$this->files[] = $sfd;
$this->count++;
}
function searchFilesRecur($root_dir, $dir, $searchpattern) {
$dir = rtrim($dir, '/');
//hide filesys root by not returning full path
$full_dir = $root_dir.$dir;
$handle = @opendir($full_dir);
while (($file = @readdir($handle))) {
if(@is_dir($full_dir."/".$file) && ($file != ".") && ($file != "..")) {
$this->searchFilesRecur($root_dir, $dir."/".$file, $searchpattern);
} else if (ereg(strtolower($searchpattern), strtolower($file)) && !ereg($this->hidefilepattern, $file)) {
if($frec = webfm_get_file_record('', $full_dir."/".$file)) {
//return files in db (role level permission)
if($this->uid == 1 || $this->uid == $frec->uid || webfm_file_view_access($frec))
$this->build_file_list($file, $dir, $frec->fid);
} else if($this->uid == 1) {
//admins can search files not in db
$this->build_file_list($file, $dir, 0);
}
}
}
@closedir($handle);
}
}
/**
* webfm_send_file - streams a file privately for download
*
* If $fid arg is numeric then file path is referenced via db, otherwise the arg
* ...is a urlencoded path that must be converted and concatenated to base file dir
*
* @param object $fid - file id
* @param bool $attach - 1 = attach / 0 = inline
*/
function webfm_send_file($fid, $attach = false) {
global $user;
$match = FALSE;
$f = false;
// User has either admin access, webfm access or view attach access
if(($user->uid == 1) || user_access('administer webfm')) {
// Admins have total access
$webfm_perm = WEBFM_ADMIN;
$match = TRUE;
} else if(user_access('access webfm')) {
$webfm_perm = WEBFM_USER;
} else if(user_access('view webfm attachments')) {
$webfm_perm = WEBFM_ATTACH_VIEW;
} else {
$webfm_perm = 0;
}
if(is_numeric($fid)) {
if(($f = webfm_get_file_record($fid)) === FALSE) {
print theme('page', "");
return;
} else {
if($f->uid == $user->uid)
// Even if file has been moved to an inaccessible dir this works
$match = TRUE;
}
} else if($webfm_perm == WEBFM_ADMIN) {
// Only allow admins to download files without fid
$f = new stdClass();
$str_arr = array();
$str_arr = split('[~]', rawurldecode($fid));
$f->fpath = file_directory_path()."/".implode('/', $str_arr);
if(!(is_file($f->fpath))) {
print theme('page', "");
return;
} else {
$match = TRUE;
}
} else {
print theme('page', "");
return;
}
// Files that have been attached are alway considered public to whoever can
// access that node (nodeaccess security)
if($match == FALSE && $webfm_perm != WEBFM_ADMIN) {
if($f->perm & WEBFM_FILE_ACCESS_PUBLIC_VIEW) {
$match = TRUE;
} else if($webfm_perm == WEBFM_USER || $webfm_perm == WEBFM_ATTACH_VIEW){
//Check if the file is attached to a node
$query = 'SELECT nid FROM {webfm_attach} WHERE fid = %d';
$result = db_query($query, $f->fid);
if($result !== FALSE) {
while ($dbfid = db_fetch_array($result)) {
$node = node_load($dbfid['nid']);
if (node_access('view', $node)) {
$match = TRUE;
break;
}
}
}
}
}
// Files that are viewable via the filebrowser UI are downloadable
if($match == FALSE &&
$webfm_perm == WEBFM_USER &&
(webfm_file_view_access($f) || webfm_file_mod_access($f))) {
$match = TRUE;
}
if(!$match) {
print theme('page', "");
return;
}
$name=basename($f->fpath);
//filenames in IE containing dots will screw up the
//filename unless we add this
if(strstr($_SERVER['HTTP_USER_AGENT'], "MSIE"))
$name = preg_replace('/\./', '%2e', $name, substr_count($name, '.') - 1);
// Get file extension
$ext = explode('.', $name);
$extension = $ext[count($ext)-1];
// Try and find appropriate type
switch(strtolower($extension)) {
case 'txt': $type = 'text/plain'; break;
case "pdf": $type = 'application/pdf'; break;
case "exe": $type = 'application/octet-stream'; break;
case "zip": $type = 'application/zip'; break;
case "doc": $type = 'application/msword'; break;
case "xls": $type = 'application/vnd.ms-excel'; break;
case "ppt": $type = 'application/vnd.ms-powerpoint'; break;
case "gif": $type = 'image/gif'; break;
case "png": $type = 'image/png'; break;
case "jpg": $type = 'image/jpeg'; break;
case "jpeg": $type = 'image/jpeg'; break;
case "html": $type = 'text/html'; break;
default: $type = 'application/force-download';
}
//download headers:
$header = array();
if($attach === '1') {
// prompt for download file or view
$header[] = 'Pragma: no-cache';
$header[] = 'Cache-Control: no-cache, must-revalidate';
$header[] = 'Content-Disposition: attachment; filename="'.$name.'";' ;
if(!empty($f->fid)) {
$cnt = array();
$cnt['dl_cnt'] = (int)$f->dl_cnt + 1;
webfm_dbupdate_file($f->fid, '', $cnt);
}
} else {
// view file via browser
$header[] = 'Pragma: public'; // required
$header[] = 'Expires: 0';
$header[] = 'Cache-Control: must-revalidate, post-check=0, pre-check=0';
$header[] = 'Content-Transfer-Encoding: binary';
$header[] = 'Content-Disposition: inline; filename="'.$name.'";' ;
// consider an app run inside the browser as a 'download'
if(!empty($f->fid) && (strpos($type, "application") === 0)) {
$cnt = array();
$cnt['dl_cnt'] = (int)$f->dl_cnt + 1;
webfm_dbupdate_file($f->fid, '', $cnt);
}
}
$header[] = 'Content-Type: '.$type;
$header[] = 'Content-Length: '.(string)(@filesize($f->fpath));
$header[] = 'Connection: close';
//drupal file_transfer will fail if file is not inside file system directory
file_transfer($f->fpath, $header);
}
/**
* webfm_dbinsert_file - inserts a file object into the webfm_file table
*
* @param object $file - complete file object
* @param string $path - a string containing the path relative to drupal root
* @param array $metadata - an array of key => value pairs, where key matches a field in the webfm_file table
*
* @return bool - TRUE if query executed successfully, otherwise FALSE
*/
function webfm_dbinsert_file($file, &$error, $metadata = array()){
//we need our user
global $user;
//add additional values to $metadata
unset($metadata['fid']);
$metadata['uid'] = $user->uid;
$metadata['fpath'] = $file->filepath;
$metadata['fname'] = strrev(substr(strrev($file->filepath), 0, strpos(strrev($file->filepath), '/')));
$metadata['fsize'] = $file->filesize ? $file->filesize : @filesize($file->filepath);
$metadata['fcreatedate'] = @filemtime($file->filepath);
$metadata['perm'] = $file->perm ? $file->perm : webfm_default_file_perm();
$metadata['dl_cnt'] = $file->dl_cnt ? $file->dl_cnt : 0;
// Get file extension
if($file->filemime) {
$metadata['fmime'] = $file->filemime;
} else {
if($pos = strrpos($file->filepath, '.')) {
$ext = substr($file->filepath, $pos + 1);
} else {
$ext = '';
}
$metadata['fmime'] = $ext;
}
$metadata['fdesc'] = $file->fdesc ? $file->fdesc : '';
//create a string of fields for the query
$fields = implode(', ', array_keys($metadata));
//build printf style list of values
foreach($metadata as $key => $value){
if(is_numeric($value)){
$printfvalues[] = '%d';
} else {
$printfvalues[] = "'%s'";
}
}
//create a srting of printf style values
$printfvalues = implode(', ', $printfvalues);
//create an array of just the values for the db_query
$values = array_values($metadata);
//make a db_query friendly query with prinf stuff
$query = "INSERT INTO {webfm_file} ($fields) VALUES ($printfvalues)";
$result = db_query($query, $values);
if($result === FALSE){
$error = $file->filepath.' could not be inserted into db';
drupal_set_message(t('Could not insert %file into the database', array('%file' => $file->filepath)), error);
return FALSE;
} else {
return TRUE;
}
}
/**
* webfm_dbupdate_file - updates information about a file
*
* @param int $fid - file id of the file to record to be altered
* @param string $path string containing the destination path relative to drupal root
* @param array $metadata - an array of key => value pairs, where key matches a field in the webfm_file table
*
* @return bool - TRUE if success - else FALSE
*/
function webfm_dbupdate_file($fid, $path = FALSE, $metadata = array()){
if($path){
//add additional values to $metadata
$metadata['fpath'] = $path;
}
//create a string of field value items in printf format
foreach($metadata as $key => $value){
if(is_numeric($value)){
$printfvalues[] = $key .'=%d';
}
else{
$printfvalues[] = $key ."='%s'";
}
}
$printfvalues = implode(', ', $printfvalues);
$values = array_values($metadata);
$values[] = $fid; //tack on the fid at the end for the last param for the update query - i.e. WHERE fid = %d
//make a db_query friendly query with prinf stuff
$query = "UPDATE {webfm_file} SET $printfvalues WHERE fid = %d";
$result = db_query($query, $values);
if($result === FALSE){
drupal_set_message(t('webfm_dbupdate_file() err: fid=%fid', array('%fid' => $fid)), error);
return FALSE;
}
return TRUE;
}
/*
* Reduce number of db queries for role extension whitelist + regex format
*/
function webfm_get_extensions_regex($rid) {
static $role_ext_regex = array();
if($rid == WEBFM_FLUSH) {
//flush static array
$role_ext_regex = array();
return '';
}
if(!$role_ext_regex[$rid]) {
$extensions = variable_get("webfm_extensions_".$rid, '');
$role_ext_regex[$rid] = '/\.('. ereg_replace(' +', '|', preg_quote($extensions)) .')$/i';
}
return $role_ext_regex[$rid];
}
/*
* Check file extension to extension whitelist for db insert
*/
function webfm_enum_validate($file, &$err_msg){
global $user;
if($user->uid == 1)
return TRUE;
$name = $file->filename ? $file->filename : strrev(substr(strrev($file->filepath), 0, strpos(strrev($file->filepath), '/')));
if(strlen($name) > 255) {
$err_msg[] = $name.' has invalid length';
return FALSE;
}
$num_roles = count($user->roles);
$error = 0;
foreach ($user->roles as $rid => $rname) {
//compare file to extension whitelist for each role
$regex = webfm_get_extensions_regex($rid);
if (!preg_match($regex, $name)) {
$err_msg[] = $file->filepath.' has invalid extension for '.$rname.' role.';
$error++;
}
}
return $error == $num_roles ? FALSE : TRUE;
}
/**
* webfm_upload_validate
* *
* @param object $file - file object
* @param string &$err_arr - ref to error array for client feedback
*
* @return bool - returns TRUE if there are no errors otherwise FALSE
*/
function webfm_upload_validate($file, &$err_arr){
global $user;
if($user->uid == 1)
return TRUE;
$copy_err = is_array($err_arr);
foreach ($user->roles as $rid => $name) {
$regex = webfm_get_extensions_regex($rid);
$uploadsize = variable_get("webfm_uploadsize_".$rid, 1) * 1024 * 1024;
$usersize = variable_get("webfm_usersize_".$rid, 1) * 1024 * 1024;
if (!preg_match($regex, $file->filename)) {
$error['extension']++;
}
if ($uploadsize && $file->filesize > $uploadsize) {
$error['uploadsize']++;
}
if ($usersize && $total_usersize + $file->filesize > $usersize) {
$error['usersize']++;
}
}
$user_roles = count($user->roles);
$valid = TRUE;
if ($error['extension'] == $user_roles) {
if($copy_err)
$err_arr[] = $file->filepath." has an invalid extension";
form_set_error('webfm_uploads', t('%name can not be uploaded because it does not have one of the following extensions: %files-allowed.', array('%name' => $file->filename, '%files-allowed' => $extensions)));
$valid = FALSE;
}
elseif ($error['uploadsize'] == $user_roles) {
if($copy_err)
$err_arr[] = $file->filepath." exceeds the max filesize";
form_set_error('webfm_uploads', t('%name can not be attached to this post, because it exceeded the maximum filesize of %maxsize.', array('%name' => $file->filename, '%maxsize' => format_size($uploadsize))));
$valid = FALSE;
}
elseif ($error['usersize'] == $user_roles) {
if($copy_err)
$err_arr[] = $file->filepath." exceeds the max disk quota";
form_set_error('webfm_uploads', t('%name can not be attached to this post, because the disk quota of %quota has been reached.', array('%name' => $file->filename, '%quota' => format_size($usersize))));
$valid = FALSE;
}
elseif (strlen($file->filename) > 255) {
if($copy_err)
$err_arr[] = $file->filepath." exceeds the max name length";
form_set_error('webfm_uploads', t('The selected file can not be attached to this post, because the filename is too long.'));
$valid = FALSE;
}
return $valid ? TRUE : FALSE;
}
/**
* Given a file path this function returns fid from the webfm file table
*
* @param string $path
* @return int $fid if one exists or FALSE if none was found
*/
function webfm_get_fid($path){
$query = "SELECT fid FROM {webfm_file} WHERE fpath = '%s'";
$result = db_query($query, $path);
if($result !== FALSE)
if($row = db_fetch_object($result))
return $row->fid;
return FALSE;
}
/**
* Given a file id or file path this function returns webfm_file table record
*
* @param int $fid
* @param string $path
* @return row object or FALSE if none was found
*/
function webfm_get_file_record($fid = '', $path = '') {
if(is_numeric($fid)) {
$query = "SELECT * FROM {webfm_file} WHERE fid = %d";
if(($result = db_query($query, $fid)) !== FALSE) {
if($row = db_fetch_object($result)) {
return $row;
}
}
} else if(is_string($path)) {
$query = "SELECT * FROM {webfm_file} WHERE fpath = '%s'";
if(($result = db_query($query, $path)) !== FALSE) {
if($row = db_fetch_object($result)) {
return $row;
}
}
}
return FALSE;
}
function webfm_putmeta($fid, $metadata, $user, &$err) {
//editable metadata columns of webfm_file table
static $metadata_key_arr = array();
if(!count($metadata_key_arr)) {
$metadata_key_arr = array( 't'=>array('field'=>'ftitle', 'size'=>255),
'd'=>array('field'=>'fdesc', 'size'=>1024),
'l'=>array('field'=>'flang', 'size'=>16),
'p'=>array('field'=>'fpublisher', 'size'=>255),
'f'=>array('field'=>'fformat', 'size'=>255));
}
if(($file = webfm_get_file_record($fid)) != false) {
if($user == 1 ||
$user == $file->uid ||
webfm_file_mod_access($file)) {
$fields = explode(',',$metadata);
$metadata = array();
foreach($fields as $field) {
// Parse webfm_file_key/metadata pairs
trim($field);
$key = substr($field, 0, 1);
$separator = substr($field, 1,1);
$value = substr($field, 2, min((strlen($field) - 2), $metadata_key_arr[$key]['size']));
if(array_key_exists($key, $metadata_key_arr) && ($separator == ":")) {
$metadata[$metadata_key_arr[$key]['field']] = strval($value);
}
}
if(count($metadata)) {
$ret = webfm_dbupdate_file($fid, '', $metadata);
if($ret) {
$err = "";
return TRUE;
} else {
$err = "webfm_dbupdate_file fail";
}
} else {
$err = "no update required";
return TRUE;
}
} else {
$err = "permission denied";
}
} else {
$err = "file not found";
}
return FALSE;
}
/**
* webfm_dbdelete_file - Deletes all database references to a file given and fid
* Calling this function will delete the file from the webfm_file table AS WELL AS the webfm_attach table
* therefore any nodes that have this file attached to them will lose that file.
*
* @param int $fid - file id of the file
* @return bool True if it worked False if it didn't
*
*/
function webfm_dbdelete_file($fid) {
if(_webfm_dbdelete_file_fid($fid)) {
//ignore err return of _webfm_dbdelete_attach_fid()
_webfm_dbdelete_attach_fid($fid);
return TRUE;
}
return FALSE;
}
/**
* Helper function that deletes db entries from the webfm_file table given an fid
* called from webfm_dbdelete_file
*
* @param int $fid
* @return bool
*/
function _webfm_dbdelete_file_fid($fid){
$query = 'DELETE FROM {webfm_file} WHERE fid = %d';
$result = db_query($query, $fid);
if($result === FALSE){
drupal_set_message(t('Query Failed: Could not delete file %fid .', array('%fid' => $fid), error));
return FALSE;
}
return TRUE;
}
/**
* webfm_dbupdate_attach - updates the files in the webfm_attach table IF the order
*
* @param int $nid
* @param array $fids - could be a comma seperated string - we need to work that out - works both ways now
* @return TRUE if records were updated - NULL if no changes were required.
*/
function webfm_dbupdate_attach($nid, $fids){
$i = 0;
if(!webfm_check_attach_order($nid, $fids)){ //the new fids are different from the old ones
$query = "DELETE FROM {webfm_attach} WHERE nid = %d";
if($result = db_query($query, $nid)){
foreach($fids as $fid){
if($fid)
webfm_dbinsert_attach($nid, $fid, $i++);
$flag = TRUE;
}
if($flag === TRUE) return TRUE;
}
}
}
/**
* webfm_check_attach_order - checks to see if the new order of the fids is the same as the old order stored in the database
*
* @param int $nid - node id
* @param array $fids - array of file ids
* @return bool - TRUE if the attach order is the same - FALSE if it has changed
*/
function webfm_check_attach_order($nid, $fids){
//check array against db result
$query = "SELECT fid FROM {webfm_attach} WHERE nid = %d ORDER BY weight";
$result = db_query($query, $nid);
$match = TRUE;
$i = 0;
while ($dbfid = db_fetch_array($result)) {
if($dbfid['fid'] != $fids[$i]) {
$match = FALSE;
break;
}
$i++;
}
if($i < count($fids)) {
$match = FALSE;
}
return($match);
}
/**
* webfm_dbinsert_attach - inserts nid, fid and weight to webfm_attach table (similar to files table)
*
* @param int $nid - node id
* @param int $fid - file id from the webfm_file table
* @param int $weight - weight value
*
* @return bool - TRUE if success - else FALSE
*/
function webfm_dbinsert_attach($nid, $fid, $weight){
$query = 'SELECT * FROM {webfm_attach} WHERE nid = %d AND fid = %d';
$result = db_query($query, $nid, $fid);
if(db_num_rows($result) !== 0) {
drupal_set_message(t('File is already attached to this node.'));
return FALSE;
} else {
//actually do the attachment if its not already attached....
$query = 'INSERT INTO {webfm_attach} (nid, fid, weight) VALUES (%d, %d, %d)';
$result = db_query($query, $nid, $fid, $weight);
if($result === FALSE) {
drupal_set_message(t('Query Failed: Could not attach files to node ') . $nid);
return FALSE;
} else {
return TRUE;
}
}
}
/**
* webfm_dbdelete_attach - deletes node file associations given a nid and fid
*
* @param int $nid - node id
* @param int $fid - file id from the webfm_file table
* @return bool - TRUE if success - else FALSE
*
*/
function webfm_dbdelete_attach($nid, $fid){
$query = 'DELETE FROM {webfm_attach} WHERE nid = %d AND fid = %d';
$result = db_query($query, $nid, $fid);
if($result === FALSE) {
drupal_set_message(t('Query Failed: Could not detach file %fid from node %nid', array('%fid' => $fid, '%nid'=>$nid)));
return FALSE;
}
return TRUE;
}
/**
* Helper function that deletes db entries from the webfm_attach table given fid
* called from webfm_dbdelete_file
*
* @param int $fid
* @return bool
*/
function _webfm_dbdelete_attach_fid($fid){
$query = 'DELETE FROM {webfm_attach} WHERE fid = %d';
$result = db_query($query, $fid);
if($result === FALSE) {
return FALSE;
}
return TRUE;
}
if(module_exists('views')){
require_once('webfm_views.inc');
}