Web File Manager (WebFM) implements a hierarchical filesystem unlike the traditional flat filesystem used to date by Drupal. WebFM allows administrators to arrange files on the server in the same way they do on their local storage drives which greatly enhances the manageability of large collections of documents. Directory access is set by role and file access is controllable by file owners or module administrators.

WebFM uses Ajax to provide application intensive functionality such as drag-and-drop and context-sensitive menuing. JavaScript must be enabled for WebFM to function - functionality will not gracefully degrade for clients that have JavaScript disabled.

Installation & Configuration

File Access Setup & Examples

There are many ways to setup a file system hierarchy. The rules of any given system must be applied carefully if security of data is important.

The basic rules for users in a role with \'access webfm\' rights:

Roles with \'access webfm\' rights can be subsets of other roles with \'access webfm\' rights or they can be exclusive. Users can be members of multiple roles and will consequently have a separate left-hand tree for each unique root directory (roles can even share the same root directory). It is difficult to foresee how diverse users of the module will choose to set up their systems but the following simple examples are typical arrangements. Both examples presume that the drupal file-system directory is set to \'files\', the WebFM module is installed and the \'WebFM root directory\' is set to \'webfm\'.

Example 1

The site requires 1 class of privileged users (A) to administer the file system and 2 classes of WebFM users (B & C) with access to file resources. Both roles will be able to upload files. Some WebFM users are members of both B & C while others are members of only one. Uploaded files are by default only accessible by the file owner and admins.

Example 2

The site requires 1 class of privileged users (A) to administer the file system and 2 classes of users (B & C) with access to file resources. C is determined to be a subset of B such that B can access it\'s own files as well as those of C. C will not be able to upload files to the browser but will only be able to view/download or attach files to nodes. B will be able to upload files.

In the above examples the site administrator may simply create the roles/access rules and then let an A user configure WebFM for B & C.

Uninstall

  1. Disable the module on the /admin/build/modules page
  2. Click on the uninstall tab and select the module for removal. This will automatically drop the webfm_file and webfm_attach tables as well as all configuration variables. NOTE: This action will permanently discard all attachment and metedata information and cannot be undone. Execute the first step only if you wish to restore WebFM later without loss of data.
', array('!permissionslink' => l('admin/user/permissions', 'admin/user/permissions'))); 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 && variable_get('webfm_attach_body', FALSE) && $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; } /** * Implementation of hook_node_type(). */ function webfm_node_type($op, $info) { switch ($op) { case 'delete': variable_del('webfm_attach_'. $info->type); break; } } /** * 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() { $items = array(); $items['webfm'] = array( 'title' => 'Web File Manager', 'page callback' => 'webfm_main', 'access callback' => 'user_access', 'access arguments' => array('access webfm'), 'type' => MENU_NORMAL_ITEM, ); $items['admin/settings/webfm'] = array( 'title' => 'Web File Manager', 'description' => 'Configure root directories, default file permissions for uploads, upload size limits, attachments, permitted file extensions and formatting.', 'file' => 'webfm.admin.inc', 'page callback' => 'drupal_get_form', 'page arguments' => array('webfm_admin_settings'), 'access arguments' => array('administer webfm'), 'type' => MENU_NORMAL_ITEM, ); $items['webfm_js'] = array( 'title' => 'Web File Manager', 'page callback' => 'webfm_ajax', 'access callback' => 'user_access', 'access arguments' => array('access webfm'), 'type' => MENU_CALLBACK, ); $items['webfm/upload'] = array( 'title' => 'Web File Manager', 'page callback' => 'webfm_upload', 'access callback' => 'user_access', 'access arguments' => array('access webfm'), 'type' => MENU_CALLBACK, ); $items['webfm_send'] = array( 'title' => 'File Not Found', 'page callback' => 'webfm_send_file', 'access callback' => TRUE, 'type' => MENU_CALLBACK, ); 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; } elseif ($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']); } } } if (variable_get("webfm_cron_insert", '')) { $err_arr[] = array(); $root_dir = file_directory_path() . webfm_get_root_path(); $result = webfm_insert_dir($root_dir, TRUE, $err_arr); if ($result->errcnt) watchdog('cron', 'WebFM file insertion errors.', $err_arr, WATCHDOG_ERROR); if ($result->cnt) watchdog('cron', 'WebFM inserted %num files.', array('%num' => $result->cnt), WATCHDOG_NOTICE); } } /** * Implementation of hook_comment(). * * Similar to webfm_nodeapi, but for comments instead of nodes. * Note: Enabling webfm in the edit form is done in form_alter. Keeping the * attachments while preview or a failing form_validate is done by form_alter * and webfm_ajax. * webfm_comment is only needed to save the attachments to the table and * for viewing and previewing comments. * We don't need to initialize js in 'validate' here because a failing form * validation re-initializes the whole node, including js. */ function webfm_comment(&$comment, $op) { if (is_object($comment)) { $cid = $comment->cid; $nid = $comment->nid; } else { $cid = $comment['cid']; $nid = $comment['nid']; } // We need the parent node for checking its permission to view attachments etc. $node = node_load($nid); switch ($op) { case 'view': if (variable_get("webfm_attach_$node->type", 1) == 1 && user_access('view webfm attachments') && variable_get('webfm_attach_body', FALSE)) { // If we preview a comment, $comment->preview is defined because the preview button // for comments is added with $form['preview']. Thus we know that $_POST['attachlist' // is ours. If we are previewing another comment and just "view" this one, // the preview flag is not set and $_POST['attachlist'] belongs to someone else. // This happens when previewing or editing a comment and the node and/or // other comments might be shown, too. // If we preview without 'acces webfm' permissions, we fetch from database, // cf. nodeapi below. if ($comment->preview && user_access('access webfm')) { if ($_POST['attachlist']) { $show_files = webfm_get_temp_attachments($_POST['attachlist']); } } else { // Normal view. Try to load attachments. There is no 'load' op for hook_comment. if (!isset($comment->webfm_files)) { $comment->webfm_files = webfm_get_attachments($cid, 'cid'); } if (is_array($comment->webfm_files) && count($comment->webfm_files)) { $show_files = $comment->webfm_files; } } if ($show_files) { $comment->comment .= theme('webfm_attachments', $show_files); 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(0, $fid, $i++, $cid); } } break; case 'update': // If the user cannot access webfm, $_POST['attachlist'] is always empty // and therefore will delete existing attachments from the node. if (user_access('access webfm') && array_key_exists('attachlist', $_POST)) { $files = explode(',', $_POST['attachlist']); webfm_dbupdate_attach(0, $files, $cid); } break; case 'delete': webfm_dbdelete_attachments($cid, 'cid'); break; } } /** * Implementation of hook_nodeapi(). */ function webfm_nodeapi(&$node, $op, $teaser) { global $user, $base_url, $base_path; switch ($op) { case 'load': if ((variable_get("webfm_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 (variable_get('webfm_attach_body', FALSE)) { // We could be viewing or previewing this node. // Loading a node defines $node->webfm_files, possibly as empty list, // but loading an edit form unsets $node->webfm_files again. Thus, if // $node->webfm is not set, we are previewing this node. // Two cases then: // 1) The user has no webfm access rights, so he can't change anything // and $_POST['attachlist'] is empty. Simulate the 'load' operation // to get the files from the database to show them in the preview. // 2) If user has webfm access, all attachments (saved/unsaved) // are in $_POST['attachlist']. But $_POST['attachlist'] is also set if // we preview e.g. a comment where this node is shown, too, but then // the attachlist is not ours. So we check for webfm_files *before* // checking for $_POST to get around this. if (!user_access('access webfm') && (variable_get("webfm_attach_$node->type", 1) == 1) && user_access('view webfm attachments')) { $node->webfm_files = webfm_get_attachments($node->nid); } if (isset($node->webfm_files) && is_array($node->webfm_files)) { if (count($node->webfm_files) && !$teaser) { $show_files = $node->webfm_files; } } // We must check for view permissions in a preview, but webfm_attach__$node->type // is TRUE if we already have attachments here. elseif (isset($_POST['attachlist']) && user_access('view webfm attachments')) { $show_files = webfm_get_temp_attachments($_POST['attachlist']); } if (isset($show_files) && is_array($show_files)) { $node->content['webfm_attachments'] = array( '#value' => theme('webfm_attachments', $show_files), '#weight' => module_exists('content') ? content_extra_field_weight($node->type, 'webfm_attachments') : 10, ); drupal_add_css(drupal_get_path('module', 'webfm') . '/css/webfm.css'); } } break; case 'validate': // When form_validate fails for preview or save, we must reinitialize // javascript, otherwise webfm doesn't work anymore. $modulepath = drupal_get_path('module', 'webfm'); drupal_add_js($modulepath .'/js/webfm.js'); drupal_add_css($modulepath .'/css/webfm.css'); // Output drupal config data as inline javascript $clean_url = variable_get('clean_url', 0); $clean = (($clean_url == 0) || ($clean_url == '0')) ? FALSE : TRUE; webfm_inline_js($base_url, $base_path, $clean, $user->uid); break; case 'insert': // We saved the attachment list for preview. Remove before saving. unset($node->attachlist); 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++); } } if (module_exists('og') && variable_get('webfm_og_auto', 0) == 1) { if (og_is_group_type($node->type)) { // make the node title into a suitable directory name $group_directory = webfm_get_group_directory($node); $group_root_dir = file_directory_path() . webfm_get_root_path() . '/' . $group_directory; file_check_directory($group_root_dir, FILE_CREATE_DIRECTORY, 'root_dir_group_' . $node->nid); variable_set('root_dir_group_' . $node->nid, $group_directory); } } break; case 'update': // If the user cannot access webfm, $_POST['attachlist'] is always empty // and therefore will delete existing attachments from the node. if (user_access('access webfm') && array_key_exists('attachlist', $_POST)) { $files = explode(',', $_POST['attachlist']); webfm_dbupdate_attach($node->nid, $files); } break; case 'delete': webfm_dbdelete_attachments($node->nid); break; } } /** * Implementation of hook_content_extra_fields(). */ function webfm_content_extra_fields($type) { $extras['webfm-attach'] = array( 'label' => t('Webfm Attachments'), 'description' => t('Displays the attachments as table'), 'weight' => 10, ); return $extras; } /** * Implementation of hook_form_alter(). */ function webfm_form_alter(&$form, &$form_state, $form_id) { global $base_url, $base_path, $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']) || $form_id == 'comment_form') { // For a comment form, the webfm permissions are inherited from the comments node. if ($form_id == 'comment_form') { $node = node_load($form['nid']['#value']); $formcheck = TRUE; } else { $node = $form['#node']; $formcheck = ($form['type']['#value'] . '_node_form' == $form_id); } if ($access && $formcheck && 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'); // Output drupal config data as inline javascript $clean_url = variable_get('clean_url', 0); $clean = (($clean_url == 0) || ($clean_url == '0')) ? FALSE : TRUE; webfm_inline_js($base_url, $base_path, $clean, $user->uid); $msg_webfm_attach_attach_browser = t('Use this file browser to attach files to the current node. Files that you choose to be attached will be shown in the list of attached files above this field.'); if (variable_get('webfm_attach_body', FALSE)) { $msg_webfm_attach_attach_browser .= ' ' . t('Once this post is saved the chosen files will be shown attached to the node body.'); } // Attachments fieldset $form['webfm-attach']['#theme'] = 'webfm_upload_form'; $form['webfm-attach']['#weight'] = module_exists('content') ? content_extra_field_weight($node->type, 'webfm_attachments') : 10; $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' => '
', '#suffix' => '
', ); $form['webfm-attach']['attach']['attachedfiles'] += webfm_attach_attached_form($node); $form['webfm-attach']['attach']['browser'] = array( '#type' => 'fieldset', '#title' => t('File Browser'), '#collapsible' => TRUE, '#collapsed' => TRUE, '#description' => $msg_webfm_attach_attach_browser, ); if ($user->uid == 1 || user_access('administer webfm')) { $form['webfm-attach']['attach']['browser'] += webfm_links(); } if ($user->uid == 1 || user_access('administer webfm') || user_access('webfm upload')) { $form['webfm-attach']['attach']['browser']['wrapper'] = array( '#type' => 'fieldset', '#title' => t('File Upload'), '#collapsible' => TRUE, '#collapsed' => TRUE, '#description' => t('Uploaded file will be saved to the current directory.'), '#prefix' => '
', '#suffix' => '
' ); $form['webfm-attach']['attach']['browser']['wrapper']['wrapper'] = array( '#prefix' => '
', '#suffix' => '
'); $form['webfm-attach']['attach']['browser']['wrapper']['wrapper'] += webfm_upload_form('webfm/upload'); $form['#attributes']['enctype'] = 'multipart/form-data'; } else { // Disable upload $form['webfm-attach']['attach']['browser']['wrapper'] = array( '#type' => 'fieldset', '#collapsible' => TRUE, '#collapsed' => TRUE, '#prefix' => '
', '#suffix' => '
' ); } } } } function webfm_get_group_directory($node) { $group_directory = drupal_strtolower(trim($node->title)); $group_directory = str_replace(array(' ', '-'), '_', $group_directory); return preg_replace('/[^a-z0-9_]/', '', $group_directory); } function webfm_link_output() { global $user; $msg = ''; $msg .= '

'; $msg .= t('Right-click (Opera: Alt+Left) on files or folders opens the context menu.'); $msg .= '
'; if ($user->uid == 1 || user_access('administer webfm')) { // Settings link - accessible only #1 user or module administrator $settings_link = t('[settings...]', array('@link' => url("admin/settings/webfm"))); // Admin Help link - available only if help module enabled $help_link = module_hook('help', 'help') ? t('[more help...]', array('@link' => url("admin/help/webfm"))) : ''; } else { $settings_link = ''; $help_link = ''; } // Debug link - available only if enabled in settings $debug_link = (drupal_to_js(variable_get('webfm_debug', ''))) ? t('[debug]') : ''; return $msg . $debug_link . $settings_link . $help_link; } function webfm_links() { $form['#theme'] = 'webfm_attach_attached_form'; $output = webfm_link_output(); if ($output) { $form['links'] = array( '#prefix' => '' ); $form['links']['content'] = array( '#type' => 'markup', '#value' => $output ); } return $form; } function webfm_attach_attached_form($node) { $form['#theme'] = 'webfm_attach_attached_form'; // This form input (id = edit-attachlist) will hold the comma-separated // ordered list of attached fids. We need to store the attachments (which // might not yet been saved to the database) in two cases: // 1) A form_validate fails when trying to save/preview. The form is not // rebuild by form_alter, but form values are refilled. #value => '' would // delete the attachlist collected so far, so use #default_value => '' instead. $form['new']['attachlist'] = array( '#type' => 'hidden', '#default_value' => ''); // 2) If form_validate didn't fail, the form is rebuild with form_alter // and the value is reset. But we have the list in the POST parameters. // Use default_value here, too, so that it can still be changed if we get // a form_validate error *after* a successful preview. if ($_POST['attachlist']) { $form['new']['attachlist']['#default_value'] = $_POST['attachlist']; } return $form; } /** * Theme the attachment form. * Note: required to output prefix/suffix. */ function theme_webfm_attach_attached_form($form) { $output = drupal_render($form); return $output; } /** * Get and theme node attachments */ function webfm_attach_box() { if ($node = menu_get_object()) { $files = webfm_get_attachments($node->nid); return theme('webfm_attachments', $files); } } /** * Implementation of hook_theme(). * * @return array */ function webfm_theme() { return array( 'webfm_browser' => array( 'arguments' => array('links' => NULL, 'upload' => NULL), 'template' => 'webfm-browser', ), 'webfm_attachments' => array( 'file' => 'webfm_theme.inc', 'arguments' => array('files'), ), ); } /** * Helper func to associate the listing icon with the mime type */ function _webfm_get_icon($ext) { // Try and find appropriate type switch (drupal_strtolower($ext)) { case 'image/gif': case 'image/png': case 'image/jpg': case 'image/jpeg': case 'image/bmp': case 'image/tiff': case 'jpg': case 'gif': case 'png': case 'jpeg': case 'bmp': case 'tiff': $icon = 'i.gif'; break; case 'video/mpeg': case 'video/x-msvideo': case 'avi': $icon = 'avi.gif'; break; case 'video/quicktime': case 'mov': $icon = 'qt.gif'; break; case 'audio/mpeg': case 'mpeg': case 'mp3': $icon = 'mp3.gif'; break; case 'application/pdf': case 'pdf': $icon = 'pdf.gif'; break; case 'application/zip': case 'application/x-zip': case 'application/x-gzip': case 'zip': $icon = 'zip.gif'; break; case 'application/msword': case 'doc': case 'odt': $icon = 'doc.gif'; break; case 'application/vnd.ms-excel': case 'xls': case 'ods': $icon = 'xls.gif'; break; case 'application/vnd.ms-powerpoint': case 'pps': case 'ppt': case 'odp': $icon = 'pps.gif'; break; default: $icon = 'f.gif'; break; } return $icon; } function webfm_roles_alter($rid, $name, $op) { if ($op == t('Save role')) { // db_query("UPDATE {role} SET name = '%s' WHERE rid = %d", $form_values['name'], $form_values['rid']);{ drupal_set_message(t('The webfm role has been renamed.')); } elseif ($op == t('Delete role')) { // db_query('DELETE FROM {role} WHERE rid = %d', $form_values['rid']); // db_query('DELETE FROM {permission} WHERE rid = %d', $form_values['rid']); // Update the users who have this role set: // db_query('DELETE FROM {users_roles} WHERE rid = %d', $form_values['rid']);{ drupal_set_message(t('The webfm role has been deleted.')); } elseif ($op == t('Add role')) { // db_query("INSERT INTO {role} (name) VALUES ('%s')", $form_values['name']); drupal_set_message(t('The webfm role has been added.')); } } /** * Check an upload, if it is an image, make sure it fits within the * maximum dimensions allowed. */ function _webfm_image(&$file) { $info = image_get_info($file->filepath); if ($info) { $res = variable_get('webfm_max_resolution', 0); if ($res != 0) { list($width, $height) = explode('x', drupal_strtolower($res)); if ($info['width'] > $width || $info['height'] > $height) { // Try to resize the image to fit the dimensions. if (image_get_toolkit() && image_scale($file->filepath, $file->filepath, $width, $height)) { drupal_set_message(t('The image was resized to fit within the maximum allowed resolution of %resolution pixels.', array('%resolution' => variable_get('webfm_max_resolution', 0)))); // Clear the cached filesize and refresh the image information. clearstatcache(); $info = image_get_info($file->filepath); $file->filesize = $info['file_size']; } else { drupal_set_message(t('The image is too large.')); } } } } } /** * Called by upload form submit */ function webfm_upload() { global $user; //Get the destination path from the edit-webfmuploadpath hidden field in the upload form $json_data = array(); $fid = ''; if (isset($_POST['webfmuploadpath'])) { $root_dir = (($user->uid == 1) || user_access('administer webfm'))? file_directory_path() : file_directory_path() . webfm_get_root_path(); $dest = $root_dir . $_POST['webfmuploadpath']; // Save new file uploads to tmp dir. if (($file = file_save_upload('webfm_upload')) != FALSE) { // Scale image uploads. _webfm_image($file); $err_arr = array(); if (webfm_upload_validate($file, $err_arr) === TRUE) { // file has been put in temp and we have a valid file object // Cache filepath as $_SESSION var for ajax confirm when name conflict // positive response will swap fid and munged name $upload_path = $dest . '/' . $file->filename; if (is_file($upload_path)) { $file->in_db = ($webfm_file_row = webfm_get_file_record('', $upload_path)) ? TRUE : FALSE; $file->dest = $dest; $_SESSION['temp_upload'] = $file; $json_data['file'] = $file->filename; if ($file->in_db) { // Overwrite of an existing file that is in the database // Only admins, file owners or files marked as modifiable by role can be overwritten if (($webfm_file_row->uid == $user->uid) || user_access('administer webfm') || webfm_file_mod_access($webfm_file_row)) { $json_data['html'] = webfm_reload_upload('webfm/upload', webfm_version_form($file->filename)); } else { drupal_set_message(t('Permission denied to overwrite existing file'), 'error'); } } else { // Overwrite of an existing file that is not in the database $msg = ''; if (($fid = webfm_version_upload(WEBFM_REPLACE_RENAME, $msg)) !== FALSE) { // file was inserted into the database drupal_set_message($msg); } else { drupal_set_message($msg, 'error'); } } } elseif (file_move($file, $dest)) { // file was moved to its final destination // Insert file into database if (($fid = webfm_dbinsert_file($file, $db_err)) !== FALSE) { drupal_set_message(t('Upload Success')); } else { file_delete($file->filepath); drupal_set_message($db_err, 'error'); } } else { drupal_set_message(t('file_move to %path failed', array('%path' => $dest)), 'error'); } } else { if (is_file($file->filepath)) { file_delete($file->filepath); } foreach ($err_arr as $err) { drupal_set_message($err, 'error'); } } } else { if (!isset($_FILES['files']) || $_FILES['files']['name']['webfm_upload'] == '') { drupal_set_message(t('Please click "Browse" and select a file to upload before clicking the upload button.'), 'error'); } } } else { drupal_set_message(t('Invalid upload path'), 'error'); } if (!isset($json_data['html'])) $json_data['html'] = webfm_reload_upload('webfm/upload'); if ($fid) $json_data['fid'] = $fid; print drupal_to_js(array('status' => TRUE, 'data' => $json_data)); exit(); } /** * Rebuild upload form for upload iframe */ function webfm_reload_upload($url, $confirm_form = '') { $form = array(); if ($confirm_form) { array_push($form, $confirm_form); } array_push($form, webfm_upload_form($url)); $form = form_builder('upload_js', $form, $form_state); $output = theme('status_messages') . drupal_render($form); return $output; } /** * Ajax post requests */ function webfm_ajax() { global $user, $node; //3 possible outcomes - the user is either an admin, user or prohibited if (($user->uid == 1) || user_access('administer webfm')) { // Admins have total access $webfm_perm = WEBFM_ADMIN; } elseif (user_access('access webfm')) { $webfm_perm = WEBFM_USER; } else { //no feedback exit(); } $webfm_root_path = webfm_get_root_path(); if ($webfm_root_path == NULL) { //WebFM root dir must exist webfm_json(array('status' => FALSE, 'err' => t('WebFM root not set'))); exit(); } $root_dir = ($webfm_perm == WEBFM_ADMIN) ? file_directory_path() : file_directory_path() . $webfm_root_path; if (isset($_POST["action"])) { switch (trim(drupal_strtolower($_POST["action"]))) { //Read directory trees case "readtrees": $trees = array(); $err = ''; if ($webfm_perm == WEBFM_ADMIN) { //Build webfm directory tree unset($_SESSION['tree_'. $webfm_root_path]); $trees[0] = webfm_tree($root_dir, $webfm_root_path); } else { //clear static array of roles with webfm access ($webfm_roots cached only for 'read' op) $webfm_roots = webfm_get_root_dirs(TRUE); if (count($webfm_roots)) { foreach ($webfm_roots as $key => $sub_root) { //Build webfm directory tree(s) for WEBFM_USER if (!empty($sub_root)) { $sub_root_path = $root_dir . $sub_root; if (is_dir($sub_root_path)) { $current = $sub_root; unset($_SESSION['tree_'. $current]); $trees[$key] = webfm_tree($root_dir, $current); } else { $err .= ' '. t('%directorypath root dir not found.', array('%directorypath' => $sub_root_path)); } } else { $err .= t('Root directory not set for the role: %role.', array('%role' => $webfm_access_roles[$key])); } } } else { $err = t('No root directory set in WebFM settings for this role.'); } if (module_exists('og')) { //clear static array of groups with directories ($webfm_roots cached only for 'read' op) $webfm_group_roots = webfm_get_group_root_dirs(TRUE); if (count($webfm_group_roots)) { foreach ($webfm_group_roots as $key => $sub_root) { //Build webfm directory tree(s) for WEBFM_USER if (!empty($sub_root)) { $sub_root_path = $root_dir . $sub_root; if (is_dir($sub_root_path)) { $current = $sub_root; unset($_SESSION['tree_'. $current]); $trees[$key] = webfm_tree($root_dir, $current); } } } } else { $err = t('No root directory set in WebFM settings for this group'); } } } if (count($trees)) { webfm_json(array('status' => TRUE, 'tree' => $trees, 'current' => $webfm_root_path, 'admin' => $webfm_perm == WEBFM_ADMIN, 'err' => $err)); } else { webfm_json(array('status' => FALSE, 'err' => t('No trees found'))); } exit(); break; //Read directory tree case "readtree": $tree = ''; unset($current); if ($webfm_perm == WEBFM_ADMIN) { //Build webfm directory tree $current = $webfm_root_path; } elseif (isset($_POST["param0"])) { //role root must exist and this user must be a member of that role $webfm_roots = webfm_get_root_dirs(); $root_role = trim(rawurldecode($_POST["param0"])); if (($root = variable_get("root_dir_". $root_role, '')) && (array_key_exists($root_role, $webfm_roots))) { $current = "/". $root; } if (module_exists('og')) { $webfm_group_roots = webfm_get_group_root_dirs(); $root_group = trim(rawurldecode($_POST["param0"])); if (($root = variable_get("root_dir_group_". $root_group, '')) && (array_key_exists($root_group, $webfm_group_roots))) { $current = "/". $root; } } } if (!isset($current)) { webfm_json(array('status' => FALSE, 'data' => t('unknown tree'))); exit(); break; } if (isset($_POST["param1"])) unset($_SESSION['tree_'. $current]); if (!is_dir($root_dir . $current)) { webfm_json(array('status' => FALSE, 'data' => t('unknown role'))); } else { $tree = webfm_tree($root_dir, $current); webfm_json(array('status' => isset($tree) ? TRUE : FALSE, 'tree' => $tree, 'current' => $current, 'admin' => $webfm_perm == WEBFM_ADMIN)); } exit(); break; //Read directory set in $_POST["param0"] case "read": if (isset($_POST["param0"])) { $param0 = trim(rawurldecode($_POST["param0"])); if (ereg('\.\.', $param0)) { webfm_json(array('status' => FALSE, 'data' => t('illegal read dir'))); exit(); } if (!is_dir($root_dir . $param0)) { webfm_json(array('status' => FALSE, 'data' => t('%path path does not exist - refresh required', array('%path' => $root_dir . $param0)))); exit(); } //Build current directory listings $dirlist = new webfm_build_dir_list($param0, $webfm_perm); if ($dirlist->get_breadcrumb()) { webfm_json(array('status' => TRUE, 'current' => $param0, 'bcrumb' => $dirlist->get_breadcrumb(), 'dirs' => $dirlist->get_dir_listing(), 'files' => $dirlist->get_file_listing(), 'user' => $user->uid, 'admin' => $webfm_perm == WEBFM_ADMIN)); } else { //invalid directory webfm_json(array('status' => FALSE, 'data' => t('invalid dir'))); } } else { webfm_json(array('status' => FALSE, 'data' => t('insufficient params'))); } exit(); break; case "delete": // Get path of object to be deleted if (isset($_POST["param0"])) { $param0 = trim(rawurldecode($_POST["param0"])); // prevent any .. shenanigans if ($param0 && !ereg('\.\.', $param0)) { $source = $root_dir . $param0; if (is_dir($source)) { //Only admins can delete directories (and contained files) if ($webfm_perm == WEBFM_ADMIN) { $err_arr[] = array(); $ret = webfm_delete_dir_recur($source, TRUE, $err_arr); webfm_json(array('status' => $ret, 'data' => $err_arr)); exit(); break; } } elseif (is_file($source)) { $permit = FALSE; $file = webfm_get_file_record('', $source); if ($webfm_perm == WEBFM_ADMIN) { // Admins can delete files $permit = TRUE; } elseif ($file) { if ($user->uid == $file->uid || webfm_file_mod_access($file)) { // File owner can delete the file // Files marked as modifiable by role can be deleted $permit = TRUE; } } if ($permit) { // Delete file and file record if in db $error = ""; $ret = TRUE; if (@unlink($source)) { if ($file && !webfm_dbdelete_file($file->fid)) { $error = t('File record %file could not be deleted from the database.', array('%file' => $source)); $ret = FALSE; } } elseif (file_exists($source)) { $error = t('%file could not be deleted', array('%file' => $source)); $ret = FALSE; } webfm_json(array('status' => $ret, 'data' => $error)); exit(); break; } } } webfm_json(array('status' => FALSE, 'data' => t('permission denied'))); } else { webfm_json(array('status' => FALSE, 'data' => t('insufficient params'))); } exit(); break; //Create new directory case "mkdir": //Only admins can create directories if ($webfm_perm == WEBFM_ADMIN) { if (isset($_POST["param0"])) { $source = $root_dir . trim(rawurldecode($_POST["param0"])); $dest = t("New_Folder"); $err_arr[] = array(); // third param is right to rename if a dir of same name already // exixts in current folder if (($ret = webfm_mkdir($source, $dest, TRUE, $err_arr))!== FALSE) { $ret = ltrim($ret, $root_dir); webfm_json(array('status' => TRUE, 'data' => $ret)); } else { webfm_json(array('status' => FALSE, 'data' => $err_arr)); } if ($ret) unset($_SESSION['tree_'. $webfm_root_path]); } else { webfm_json(array('status' => FALSE, 'data' => t('insufficient params'))); } } else { webfm_json(array('status' => FALSE, 'data' => t('Permission denied'))); } exit(); break; //Move a file or directory (drag and drop) case "move": if (isset($_POST["param0"]) && isset($_POST["param1"])) { $source = $root_dir . trim(rawurldecode($_POST["param0"])); $dest = $root_dir . trim(rawurldecode($_POST["param1"])); if (is_dir($source) && ($webfm_perm != WEBFM_ADMIN)) { //Only admins can manipulate directories webfm_json(array('status' => FALSE, 'data' => t('Permission denied'))); exit(); break; } if ($source != $dest) { // prevent any ../ shenanigans if (!ereg('\.\.', $dest)) { $err_arr[] = array(); $ret = webfm_move($source, $dest, ($webfm_perm == WEBFM_USER) ? $user->uid : 1, $err_arr); webfm_json(array('status' => $ret, 'data' => $err_arr)); } else { webfm_json(array('status' => FALSE, 'data' => t('Illegal destination path'))); } } else { webfm_json(array('status' => FALSE, 'data' => t('move operation not permitted'))); } } else { webfm_json(array('status' => FALSE, 'data' => t('insufficient params'))); } exit(); break; //Rename an existing file or directory case "rename": if (isset($_POST["param0"]) && isset($_POST["param1"])) { $source = $root_dir . trim(rawurldecode($_POST["param0"])); $dest = $root_dir . trim(rawurldecode($_POST["param1"])); // prevent any ../ shenanigans if (!ereg('\.\.', $dest) && dirname(rawurldecode($_POST["param0"])) == dirname(rawurldecode($_POST["param1"]))) { $err_arr[] = array(); //rename permissions inside webfm_rename $ret = webfm_rename($source, $dest, ($webfm_perm == WEBFM_USER) ? $user->uid : 1, $err_arr); webfm_json(array('status' => $ret, 'data' => $err_arr)); } else { webfm_json(array('status' => FALSE, 'data' => t('illegal name'))); } } else { webfm_json(array('status' => FALSE, 'data' => t('insufficient params'))); } exit(); break; //Search current directory for filename case "search": if (isset($_POST["param0"]) && isset($_POST["param1"])) { $source = trim(rawurldecode($_POST["param0"])); $searchpattern = trim(rawurldecode($_POST["param1"])); if ($searchpattern != "") { $regexpsearch = ''; @clearstatcache(); $search = new webfm_searchFiles($root_dir, $source, $searchpattern, $regexpsearch, ($webfm_perm == WEBFM_USER) ? $user->uid : 1); webfm_json(array('files' => $search->get_files())); } } else { webfm_json(array('status' => FALSE, 'data' => t('insufficient params'))); } exit(); break; //Get file metadata case "getmeta": if (isset($_POST["param0"])) { $fid = rawurldecode($_POST["param0"]); if (($file = webfm_get_file_record($fid)) !== FALSE) { //presence of fid used to grant js metadata access if ($webfm_perm == WEBFM_ADMIN || $user->uid == $file->uid || webfm_file_mod_access($file) || webfm_file_view_access($file)) { $meta = array(); //presence of fid used to grant js metadata access if ($webfm_perm == WEBFM_ADMIN || $user->uid == $file->uid || webfm_file_mod_access($file)) { $meta['id'] = $file->fid; if ($webfm_perm == WEBFM_ADMIN) { // Only admins get uid $meta['u'] = $file->uid; } } if ($file->uid > 0) { $query = 'SELECT name FROM {users} WHERE uid = %d'; $meta['un'] = db_result(db_query($query, $file->uid)); } else { $meta['un'] = t('Anonymous'); } $meta['n'] = strrev(drupal_substr(strrev($file->fpath), 0, strpos(strrev($file->fpath), '/'))); $meta['t'] = $file->ftitle; $meta['d'] = $file->fdesc; $meta['l'] = $file->flang; $meta['p'] = $file->fpublisher; $meta['f'] = $file->fformat; $meta['c'] = $file->dl_cnt; if ((list($width, $height, $type, $attr) = @getimagesize($file->fpath)) !== FALSE) { if (($width != 0) && ($height != 0)) { $meta['i'] = $type; $meta['w'] = $width; $meta['h'] = $height; } } if ($file->perm & WEBFM_FILE_ACCESS_PUBLIC_VIEW) { //permissions allow file to be linked for public view global $base_url; $meta['lk'] = ''. $meta['n'] .''; } webfm_json(array('status' => TRUE, 'data' => $meta)); } else { webfm_json(array('status' => FALSE, 'data' => t('permission denied'))); } } else { webfm_json(array('status' => FALSE, 'data' => t('file record not found'))); } } else { webfm_json(array('status' => FALSE, 'data' => t('insufficient params'))); } exit(); break; //Change file metadata //TODO: update changes in UI case "putmeta": if (isset($_POST["param0"]) && isset($_POST["param1"])) { //permission check in webfm_putmeta so single access to webfm_file table //Set WEBFM_ADMIN to uid=1 for purpose of file ownership $ret = webfm_putmeta(rawurldecode($_POST["param0"]), rawurldecode($_POST["param1"]), ($webfm_perm == WEBFM_ADMIN)?1:$user->uid, $err); webfm_json(array('status' => $ret, 'data' => $err)); } else { webfm_json(array('status' => FALSE, 'data' => t('insufficient params'))); } exit(); break; //Get file permissions case "getperm": if (isset($_POST["param0"])) { $fid = rawurldecode($_POST["param0"]); if (($file = webfm_get_file_record($fid)) !== FALSE) { if ($webfm_perm == WEBFM_ADMIN || $user->uid == $file->uid || webfm_file_mod_access($file)) { $perm = array(); $perm['id'] = $file->fid; $perm['u'] = $file->uid; $perm['n'] = strrev(drupal_substr(strrev($file->fpath), 0, strpos(strrev($file->fpath), '/'))); $perm['p'] = $file->perm; webfm_json(array('status' => TRUE, 'data' => $perm)); } else { webfm_json(array('status' => FALSE, 'data' => t('permission denied'))); } } else { webfm_json(array('status' => FALSE, 'data' => t('file record not found'))); } } else { webfm_json(array('status' => FALSE, 'data' => t('insufficient params'))); } exit(); break; //Change file permissions case "putperm": if (isset($_POST["param0"]) && isset($_POST["param1"])) { $fid = rawurldecode($_POST["param0"]); if (($file = webfm_get_file_record($fid)) !== FALSE) { if ($webfm_perm == WEBFM_ADMIN || $user->uid == $file->uid || webfm_file_mod_access($file)) { $perm = array(); $msg = ''; $perm['perm'] = (int)rawurldecode($_POST["param1"]); $status = FALSE; // Validate permission value if ($perm['perm'] >= 0 && $perm['perm'] <= WEBFM_MAX_FILE_ACCESS) { if (webfm_dbupdate_file($fid, '', $perm)) { // Send back permissions to confirm value for form reset $msg = t('Permissions saved'); $status = TRUE; } else { $msg = t('webfm_dbupdate_file() fail'); } } else { $msg = t('invalid permission'); } } else { $msg = t('permission denied'); } } else { $msg = t('file record not found'); } } else { $msg = t('insufficient params'); } webfm_json(array('status' => $status, 'data' => $perm, 'msg' => $msg)); exit(); break; //Get attached items case "attach": if (isset($_POST["param0"])) { // If $_POST["param1"] is set, we are in a preview or validation failure // and have fids stored in the edit-attachments form, those that we fetched // from the database before and those which are not yet attached (during // a preview). Those fids are transfered through param1. if (isset($_POST["param1"])) { $fids = trim(drupal_strtolower(rawurldecode($_POST["param1"]))); webfm_json(array('status' => TRUE, 'data' => webfm_get_temp_attachments($fids), 'admin' => 'attach')); exit(); break; } // Here we are in the edit form for the first time. // For comments, the URL is "comment/edit/$cid" instead of node/$nid/edit. // Unify those. We must distinguish between new and existing nodes/comments, // because for new nodes webfm passed a string instead of a nid which was // interpreted as nid=0. But now with comments, we *have* entries with nid=0 // in the table, so avoid fetching those. // For new nodes and comments we can't get attachments from the database. $node_str = trim(drupal_strtolower(rawurldecode($_POST["param0"]))); // We edit an existing node: Fetch from database. if (strpos($node_str, '/edit')) { $node_str = str_replace('/edit', '', $node_str); $selector = 'nid'; // The 'node' var passed via AJAX is the action attribute of id=node-form. if (($node_num = strstr($node_str, 'node/')) == FALSE) { $node_num = strstr($node_str, 'comment/'); $selector = 'cid'; } if ($node_num) { $node_arr = explode("/", $node_num); // 'admin' is TRUE (allow drag&drop) since only owners of a node can edit it. webfm_json(array('status' => TRUE, 'data' => webfm_get_attachments($node_arr[1], $selector), 'admin' => 'attach')); } else { webfm_json(array('status' => FALSE, 'data' => 'illegal path')); exit(); break; } } else { // Return empty array for new nodes. webfm_json(array('status' => TRUE, 'data' => array(), 'admin' => 'attach')); } } else { webfm_json(array('status' => FALSE, 'data' => t('insufficient parameters'))); } exit(); break; //Get file for attachment to node case "attachfile": if (isset($_POST["param0"])) { // param0 = fid $fid = rawurldecode($_POST["param0"]); if (($_file = webfm_get_file_record($fid)) !== FALSE) { if ($webfm_perm == WEBFM_ADMIN || $user->uid == $_file->uid || webfm_file_mod_access($_file)|| webfm_file_att_access($_file)) { $file = new webfm_fdesc($_file); if ($file->result != FALSE) { webfm_json(array('status' => TRUE, 'data' => $file, 'admin' => 'attach')); } else { webfm_json(array('status' => FALSE, 'data' => t('File (%file) path not found', array('%file' => $fid)))); } } else { webfm_json(array('status' => FALSE, 'data' => t('Invalid permission.'))); } } else { webfm_json(array('status' => FALSE, 'data' => t('File (%file) record not found', array('%file' => $fid)))); } } else { webfm_json(array('status' => FALSE, 'data' => t('Insufficient parameters.'))); } exit(); break; case "insert": //Only admins can insert files into database if ($webfm_perm == WEBFM_ADMIN) { if (isset($_POST["param0"]) && isset($_POST["param1"])) { $source = $root_dir . trim(rawurldecode($_POST["param0"])); $err_arr[] = array(); $result = FALSE; switch (trim(rawurldecode($_POST["param1"]))) { case "file": //dir insert methods already return class object $ret = webfm_insert_file($source, $err_arr); $result = new stdClass(); $result->cnt = 0; $result->errcnt = 0; $result->err = ''; if (!$ret) { $result->errcnt = 1; $result->err = $err_arr; webfm_json(array('status' => FALSE, 'data' => $result)); } else { $result->cnt = 1; webfm_json(array('status' => TRUE, 'data' => $result)); } break; case "dir": $result = webfm_insert_dir($source, FALSE, $err_arr); if ($result->errcnt) $result->err = $err_arr; webfm_json(array('status' => (($result->cnt) > 0), 'data' => $result)); break; case "recur": $result = webfm_insert_dir($source, TRUE, $err_arr); if ($result->errcnt) $result->err = $err_arr; webfm_json(array('status' => (($result->cnt) > 0), 'data' => $result)); break; } } else { webfm_json(array('status' => FALSE, 'data' => t('insufficient params'))); } } else { webfm_json(array('status' => FALSE, 'data' => t('permission denied'))); } exit(); break; case "dbrem": //Only admins can remove files from database if ($webfm_perm == WEBFM_ADMIN) { if (isset($_POST["param0"])) { if ($ret = trim(rawurldecode($_POST["param0"]))) { $ret = webfm_dbdelete_file($ret); webfm_json(array('status' => $ret, 'data' => t('webfm_dbdelete_file() success'))); } else { webfm_json(array('status' => FALSE, 'data' => t('file not in db'))); } } else { webfm_json(array('status' => FALSE, 'data' => t('insufficient params'))); } } else { webfm_json(array('status' => FALSE, 'data' => t('permission denied'))); } exit(); break; case "version": if (isset($_POST["param0"]) && isset($_POST["param1"])) { $op = trim(rawurldecode($_POST["param0"])); $filename = trim(rawurldecode($_POST["param1"])); if (strcmp($_SESSION['temp_upload']->filename, $filename) === 0) { $ver_data = array(); if (($ret = webfm_version_upload($op, $msg)) != FALSE) $ver_data['fid'] = $ret; $ver_data['msg'] = $msg; webfm_json(array('status' => $ret, 'data' => $ver_data)); } else { webfm_json(array('status' => FALSE, 'data' => t('invalid file name'))); } } else { webfm_json(array('status' => FALSE, 'data' => t('insufficient params'))); } // clear uploaded file unset($_SESSION['temp_upload']); exit(); break; default: webfm_json(array('status' => FALSE, 'data' => t('illegal operation'))); exit(); break; } exit(); } exit(); } /** * Version uploaded file that overwrites existing file * NOTE: uploaded file is already stored in $_SESSION['temp_upload'] via iframe. * Feedback in ajax since drupal_set_message points back into main page (not refreshed). */ function webfm_version_upload($op, &$msg) { global $user; $ret = TRUE; switch ($op) { case WEBFM_CANCEL: //Cancel button - must be FALSE since non-FALSE return used as fid $ret = FALSE; $msg = t('Upload Cancelled'); break; case WEBFM_RENAME_NEW: $ret = webfm_upload_new($msg); break; case WEBFM_REPLACE_RENAME: // Retrieve file record for original file // Rename (munge) original file // Move new file to destination // Update existing original record with data from new file // Create new db record for original file // Restore original file if error $path = $_SESSION['temp_upload']->dest .'/'. $_SESSION['temp_upload']->filename; if ($pos = strrpos($path, '.')) { $name = drupal_substr($path, 0, $pos); $ext = drupal_substr($path, $pos); } else { $name = $basename; } $counter = 0; do { $temp_path = $name .'_'. $counter++ . $ext; } while (file_exists($temp_path)); @rename($path, $temp_path); if (file_move($_SESSION['temp_upload'], $_SESSION['temp_upload']->dest)) { // file was moved to its final destination if ($_SESSION['temp_upload']->in_db == TRUE) { if (($record = webfm_get_file_record('', $path)) === FALSE) { $ret = FALSE; $msg = t('Replace-Delete webfm_get_file_record fail'); break; } //Insert file into database if under webfm_root $time = @filemtime($_SESSION['temp_upload']->filepath); $query = "UPDATE {webfm_file} SET fsize = %d, fcreatedate = %d, fversion = %d, uid = %d WHERE fid = %d"; $row = db_query($query, $_SESSION['temp_upload']->filesize, $time, $record->fversion + 1, $user->uid, $record->fid); if ($row === FALSE) { // Update of existing record failed // Delete new file and restore name of original file $ret = FALSE; $msg = t('Replace-Delete update fail'); file_delete($path); @rename($temp_path, $path); } else { // Create new record for existing file using old record $newfile = new stdClass(); $newfile->filepath = $temp_path; if (($ret = webfm_dbinsert_file($newfile, $msg, (array)$record)) !== FALSE) $msg = t('Upload success'); } } else { // No ajax returned since called by upload directly without version options $ret = webfm_upload_new($msg); } } else { $ret = FALSE; $msg = t('file_move fail'); @rename($temp_path, $path); } break; case WEBFM_REPLACE_DELETE: // Retrieve db record for original file & rename file // Move new file to destination // Update existing original record with data from new file // Restore original file if error, else delete $path = $_SESSION['temp_upload']->dest .'/'. $_SESSION['temp_upload']->filename; //use temp for rollback on error $temp_path = $path .'~'; @rename($path, $temp_path); if (file_move($_SESSION['temp_upload'], $_SESSION['temp_upload']->dest)) { // file was moved to its final destination if ($_SESSION['temp_upload']->in_db == TRUE) { if (($record = webfm_get_file_record('', $path)) === FALSE) { $ret = FALSE; $msg = t('Replace-Delete webfm_get_file_record fail'); break; } //Insert file into database if under webfm_root $time = @filemtime($_SESSION['temp_upload']->filepath); $query = "UPDATE {webfm_file} SET fsize = %d, fcreatedate = %d, fversion = %d, uid = %d WHERE fid = %d"; $row = db_query($query, $_SESSION['temp_upload']->filesize, $time, $record->fversion + 1, $user->uid, $record->fid); if ($row === FALSE) { $ret = FALSE; $msg = t('Replace-Delete update fail'); // Delete new file and restore name of original file file_delete($path); @rename($temp_path, $path); } else { $ret = $record->fid; $msg = t('Upload success'); file_delete($temp_path); } } else { file_delete($temp_path); $ret = TRUE; $msg = t('Upload success'); } } else { $ret = FALSE; $msg = t('file_move fail'); @rename($temp_path, $path); } break; default: $ret = FALSE; $msg = ''; break; } return $ret; } function webfm_upload_new(&$msg) { // Insert new file into database with munged name & auto-incremented fid if (file_move($_SESSION['temp_upload'], $_SESSION['temp_upload']->dest)) { // file was moved to its final destination //Insert file into database if under webfm_root if (($ret = webfm_dbinsert_file($_SESSION['temp_upload'], $msg)) !== FALSE) { // file was inserted into the database $msg = t('Upload success'); return $ret; } else { file_delete($_SESSION['temp_upload']->filepath); return FALSE; } } else { $msg = t('Moving File to %destination failed.', array('%destination' => $_SESSION['temp_upload']->dest)); return FALSE; } } /** * Return data in JSON format. * * This function should be used for JavaScript callback functions returning * data in JSON format. It sets the header for JavaScript output. * * @param $var * (optional) If set, the variable will be converted to JSON and output. */ function webfm_json($var = NULL) { // We are returning JavaScript, so tell the browser. drupal_set_header('Content-Type: text/javascript; charset=utf-8'); if (isset($var)) { echo drupal_to_js($var); } } /** * Main file manager function */ function webfm_main() { global $base_url, $base_path, $user; $modulepath = drupal_get_path('module', 'webfm'); drupal_add_js($modulepath .'/js/webfm.js'); drupal_add_js('misc/collapse.js'); drupal_add_css($modulepath .'/css/webfm.css'); module_invoke_all('webfm_extend_js'); // Output drupal config data as inline javascript $clean_url = variable_get('clean_url', 0); $clean = (($clean_url == 0) || ($clean_url == '0')) ? FALSE : TRUE; webfm_inline_js($base_url, $base_path, $clean, $user->uid); $links = webfm_link_output(); $upload = ''; if ($user->uid == 1 || user_access('administer webfm') || user_access('webfm upload')) { $upload = drupal_get_form('webfm_upload_fieldset'); } return theme('webfm_browser', $links, $upload); } 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, array('absolute' => TRUE)), '#attributes' => array('class' => 'webfmupload')); return $form; } function webfm_version_form($filename) { $filearg = array( '%filename' => $filename, ); $form['select'] = array( '#prefix' => '
', '#suffix' => '
', '#type' => 'radios', '#title' => t('Select File Versioning Option'), '#description' => t('A file with the same name has already been uploaded. Please select one of the options in order to proceed.'), '#options' => array(t('Replace and rename original copy of %filename', $filearg), t('Replace and delete original copy of %filename', $filearg), t('Rename new copy of %filename', $filearg), t('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, $base_path, $clean_url, $uid) { $js = 'function getBaseUrl(){return '. drupal_to_js($base_url) .';} '; $js .= 'function getWebfmIconDir(){return '; $js .= drupal_to_js($base_url .'/'. variable_get('webfm_icon_dir', drupal_get_path('module', 'webfm') -'/image/icon')); $js .= ';} '; $js .= 'function getWebfmCleanUrl(){return '; $js .= drupal_to_js($clean_url); $js .= '; } '; $js .= 'function getWebfmIETreeOffset(){return '; $js .= drupal_to_js(variable_get('webfm_ie_dd_tree_offset', '')); $js .= ';} '; $js .= 'function getWebfmIEListOffset(){return '; $js .= drupal_to_js(variable_get('webfm_ie_dd_list_offset', '')); $js .= ';} '; $js .= 'function getWebfmUid(){return '. drupal_to_js($uid) .';} '; $js .= 'function getWebfmDateFormat(){return '; $js .= drupal_to_js(variable_get('webfm_date_format', WEBFM_DATE_FORMAT_DAY)); $js .= ';} '; $js .= 'function getWebfmMetaName(){return '; $js .= drupal_to_js(variable_get('webfm_display_title', '')); $js .= ';} '; $js .= 'function getWebfmOwnerColumn(){return '. drupal_to_js(variable_get('webfm_display_owner', '')) .';}'; drupal_add_js($js, 'inline'); } /** * Helper function to check for root path at base of input path */ function webfm_check_path($path, $root) { if (strncmp($path, $root, drupal_strlen($root)) == 0) { if ((drupal_strlen($path) == drupal_strlen($root)) || (drupal_substr($path, drupal_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_access_roles($flush = FALSE) { static $webfm_access_roles = 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(0, 'access webfm'); } return $webfm_access_roles; } function webfm_get_root_dirs($flush = FALSE) { global $user; static $webfm_roots = array(); $webfm_access_roles = webfm_get_access_roles($flush); $webfm_roots = array(); foreach ($user->roles as $rid => $role) { if (array_key_exists($rid, $webfm_access_roles)) { // Roles with 'access webfm' perm that user possesses $path = variable_get('root_dir_'. $rid, ''); if (!empty($path)) { // Prevent redundant trees for roles with common root dir if (!in_array($path, $webfm_roots)) { $webfm_roots[$rid] = '/'. $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 get array of group root directories for a user */ function webfm_get_group_root_dirs($flush = FALSE) { global $user; static $webfm_roots = array(); static $webfm_access_groups = array(); //add per group directories if ($flush) { $webfm_access_groups = array(); } // Roles with 'access webfm' perm if (!count($webfm_access_groups)) { $webfm_roots = array(); foreach ($user->og_groups as $key => $group) { if ($group['is_active']) { // Groups with directories that user is active in $path = variable_get('root_dir_group_' . $key, ''); if (!empty($path)) { // Prevent redundant trees for groups with common root dir if (!in_array($path, $webfm_roots)) { $webfm_roots[$key] = '/' . $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; } /** * Helper function to determine if a webfm_file record is attachable by a * user with 'access webfm' */ 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; } } //alternatively the read path may be in a legitimate group root dir for this user if (module_exists('og')) { $webfm_group_roots = webfm_get_group_root_dirs(); foreach ($webfm_group_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($path, $perm) { global $user; $bl = array('.', '..', '.htaccess'); $_dirs = array(); $_fils = array(); // Admins do not have webfm root hidden $root = ($perm == WEBFM_ADMIN)? file_directory_path() : file_directory_path() . webfm_get_root_path(); if (drupal_substr($path, 0, 1) != '/') { $path = '/'. $path; } $full_path = $root . $path; if (is_dir($full_path)) { // Test access rights $perm_flag = FALSE; if ($perm == WEBFM_ADMIN) { // WEBFM_ADMIN always has access if (webfm_check_path($path, $webfm_root_path)) { $perm_flag = TRUE; } } else { // If WEBFM_USER, test that read path is inside a legit root dir $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 ($sub_root && webfm_check_path($path, $sub_root)) { $perm_flag = TRUE; break; } } } if (!$perm_flag && module_exists('og')) { $webfm_group_roots = webfm_get_group_root_dirs(); foreach ($webfm_group_roots as $key => $sub_root) { // The read path must be contained within a legitimate group root dir for this user if ($sub_root && webfm_check_path($path, $sub_root)) { $perm_flag = TRUE; break; } } } if ($perm_flag && $handle = opendir($full_path)) { // 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(drupal_strtolower($readdir), $bl)) { if (is_dir($full_path . '/' . $readdir)) { $_dirs[] = $readdir; } elseif (is_file($full_path . '/' . $readdir)) { $_fils[] = $readdir; } } } closedir($handle); } if (is_array($_dirs)) { foreach ($_dirs as $dir) { $dd = new stdClass(); $dd->n = $dir; $dd->p = $path . "/" . $dir; $dd->m = (filemtime($full_path . '/'. $dir)) ? @filemtime($full_path . '/' . $dir) : ""; $this->dirs[] = $dd; } } if (is_array($_fils)) { foreach ($_fils as $filename) { $file = $full_path . '/' . $filename; if ($_file = webfm_get_file_record('', $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; } if ($_file->uid > 0) { $_query = 'SELECT name FROM {users} WHERE uid = %d'; $fd->un = db_result(db_query($_query, $_file->uid)); } else { $fd->un = t('Anonymous'); } $fd->m = @filemtime($file); $fd->s = @filesize($file); } else { // permission denied to view this file continue; } } elseif ($perm == WEBFM_ADMIN) { $fd = new stdClass(); $fd->id = 0; //invalid fid signals no db entry $fd->u = ''; //file has no owner $fd->un = ''; $fd->m = @filemtime($file); $fd->s = @filesize($file); } else { // permission denied to view this file continue; } if (variable_get('webfm_display_title', '') && $_file->ftitle) { $fd->ftitle = urldecode($_file->ftitle); } $fd->n = $filename; $fd->p = $path; $fd->i = 0; if (strpos($filename, ".") === FALSE) { $fd->e = ""; } else { $fd->e = array_pop(explode('.', $filename)); $mime_type = file_get_mimetype($file); if (preg_match('/^image/', $mime_type)) { if (!function_exists('exif_imagetype')) { if ((list($width, $height, $type, $attr) = @getimagesize($file)) !== FALSE) { //if valid width/height... if (($width != 0) && ($height != 0)) { //return type $fd->i = $type; } } } elseif ($i = @exif_imagetype($file)) { $fd->i = $i; } } } $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, $selector = 'nid') { // If anything but a existing nid/cid is passed, it is equivalent to 0. This // happened in webfm_ajax in the past. Although we fixed it there, make sure // that we never run into this, because now there are entries with nid/cid=0. if ($nid == 0) { return array(); } $files = array(); $file_result = db_query("SELECT * FROM {webfm_file} f INNER JOIN {webfm_attach} a ON f.fid = a.fid WHERE a.%s = %d ORDER BY a.weight", $selector, $nid); while ($file_record = db_fetch_object($file_result)) { $_file = new webfm_fdesc($file_record); if ($_file->result == TRUE) { $files[] = $_file; } } return $files; } /** * Return file descriptors for an attachment that have not yet been saved. * This happens on previewing posts. * * @param array $fids - a comma separated list of fids. * @return array of file descriptors. */ function webfm_get_temp_attachments($fids) { $files = array(); $fids_arr = split(',', $fids); $file_result = db_query('SELECT * FROM {webfm_file} WHERE fid in ('. db_placeholders($fids_arr) .')', $fids_arr); 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 ($handle = opendir($dir)) { while (($readdir = readdir($handle)) !== FALSE) { if (is_dir($dir . DIRECTORY_SEPARATOR . $readdir)) { continue; } if (is_file($dir . DIRECTORY_SEPARATOR . $readdir) && ($readdir == _webfm_basename($file->fpath))) { $this->id = $file->fid; $this->n = strrev(drupal_substr(strrev($file->fpath), 0, strpos(strrev($file->fpath), '/'))); $this->p = $dir; $this->e = array_pop(explode('.', $this->n)); $this->s = $file->fsize; $this->uid = $file->uid; if ($file->uid > 0) { $_query = 'SELECT name FROM {users} WHERE uid = %d'; $this->un = db_result(db_query($_query, $file->uid)); } else { $this->un = t('anonymous'); } // 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($dir . DIRECTORY_SEPARATOR . $readdir)) ? @filemtime($dir . DIRECTORY_SEPARATOR . $readdir) : ""; $this->result = TRUE; break; } } closedir($handle); } } } } /** * Function to sanitize long filenames */ function webfm_sanlen($x) { if (drupal_strlen($x) > 80) return drupal_substr($x, 0, 40) ."...". drupal_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); } elseif (ereg(drupal_strtolower($searchpattern), drupal_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); } elseif ($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 int $fid - file id * @param bool $download - TRUE=download / FALSE=stream * @param bool $bypass_invoke TRUE=do no invoke webfm_send hook / FALSE=invoke */ function webfm_send_file($fid, $download = FALSE, $bypass_invoke = 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; } elseif (user_access('access webfm')) { $webfm_perm = WEBFM_USER; } elseif (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) { return drupal_not_found(); } else { if ($f->uid == $user->uid) // Even if file has been moved to an inaccessible dir this works $match = TRUE; } } elseif ($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))) { return drupal_not_found(); } else { $match = TRUE; } } else { return drupal_not_found(); } // Files that have been attached are always considered public to whoever can // access that node/comment (nodeaccess/commentaccess security). if ($match == FALSE && $webfm_perm != WEBFM_ADMIN) { if ($f->perm & WEBFM_FILE_ACCESS_PUBLIC_VIEW) { $match = TRUE; } elseif ($webfm_perm == WEBFM_USER || $webfm_perm == WEBFM_ATTACH_VIEW) { //Check if the file is attached to a node or comment. $query = 'SELECT nid,cid FROM {webfm_attach} WHERE fid = %d'; $result = db_query($query, $f->fid); if ($result !== FALSE) { while ($dbfid = db_fetch_array($result)) { if ($dbfid['cid'] != 0 ) { // For a comment, a user must be able to view the parent node and have "access_comments". if (!user_access('access comments')) { continue; } $comment = _comment_load($dbfid['cid']); $dbfid['nid'] = $comment->nid; } $node = node_load($dbfid['nid']); if (node_access('view', $node)) { $match = TRUE; // Modules might use their own method of node restriction, other than node_access. drupal_alter('webfm_file_access', $match, $node, $f->$fid); if ($match) { 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) { drupal_access_denied(); return; } // Hook to allow alternative file streaming // Bypass allows 2nd pass of file through this function after work done // in module using this hook if ($bypass_invoke === FALSE) { $ret = module_invoke_all('webfm_send', $f); if (array_key_exists('sent', $ret)) { return; } } $name=_webfm_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 $type = file_get_mimetype($name); //download headers: $header = array(); if ($download === '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 &$error - reference to error string * @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; if (!isset($file->filepath)) { $error = t('No file path supplied'); return FALSE; } else { $metadata['fpath'] = $file->filepath; } // always a new record unset($metadata['fid']); // fill $metadata values not supplied in 3rd arg if (!isset($metadata['uid'])) $metadata['uid'] = $user->uid; if (!isset($metadata['fsize'])) $metadata['fsize'] = @filesize($file->filepath); if (!isset($metadata['fcreatedate'])) $metadata['fcreatedate'] = @filemtime($file->filepath); if (!isset($metadata['perm'])) $metadata['perm'] = webfm_default_file_perm(); if (!isset($metadata['fmime'])) $metadata['fmime'] = file_get_mimetype($file->filepath); if (!isset($metadata['fdesc'])) $metadata['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); $query = "INSERT INTO {webfm_file} (". $fields .") VALUES (". $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 $result = db_query($query, $values); if ($result === FALSE) { $error = t('%filepath could not be inserted into db', array('%filepath' => $file->filepath)); return FALSE; } else { // return fid to calling routine $query = "SELECT fid FROM {webfm_file} WHERE fpath = '%s'"; $result = db_query($query, $file->filepath); if (($result !== FALSE) && ($row = db_fetch_object($result))) { _webfm_file_alias("insert", $metadata, $row->fid); return $row->fid; } else { $error = t('%filepath could not be selected from db', array('%filepath' => $file->filepath)); return FALSE; } } } /** * 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; } $pieces = array(); //create a string of field value items in printf format foreach ($metadata as $key => $value) { if (is_numeric($value)) { $pieces[] = $key . " = %d "; } else { $pieces[] .= $key . " = '%s' "; } } $pieces = implode(', ', $pieces); $query = "UPDATE {webfm_file} SET ". $pieces; $query .= " WHERE fid = %d"; $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 $result = db_query($query, $values); if ($result === FALSE) { drupal_set_message(t('webfm_dbupdate_file() err: fid=%fid', array('%fid' => $fid)), 'error'); return FALSE; } _webfm_file_alias('update', $metadata, $fid); return TRUE; } /** * Call the Pathauto-Module to create or update a filepath alias * * @param $op insert|update Wether to update or insert an alias * @param $metadata File Metadata * @param $fid File ID * @return NULL */ function _webfm_file_alias($op, $metadata, $fid) { if (!module_exists('pathauto')) return NULL; switch ($op) { case "insert": case "update": $webfmfile = $metadata; $webfmfile['fid'] = $fid; $pathauto_path = drupal_get_path('module', 'pathauto'); require_once("$pathauto_path/pathauto.inc"); $alias = pathauto_create_alias('webfm', $op, pathauto_get_placeholders('webfm', $webfmfile), 'webfm_send/'. $webfmfile['fid'], 'webfm'); break; } } /** * Reduce number of db queries for role extension whitelist + regex format * * @param int $rid Role ID * @return array $array[$role_id] = regular expression for allowed extensions */ 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 against whitelist. * * @param object $file * @param array $err_msg Error Messages that occured. * * @return bool true if file extension is okay */ function webfm_enum_validate($file, &$err_msg) { global $user; if(empty($file->filename)) { $file->filename = strrev(drupal_substr(strrev($file->filepath), 0, strpos(strrev($file->filepath), '/'))); } if (drupal_strlen($file->filename) > 255) { $err_msg[] = t('%filename exceeds the maximum name length', array('%filename' => drupal_substr($file->filename, 0, 252) .'...')); return FALSE; } if (user_access('administer webfm')) { return TRUE; } //Check for possible imagefile exploit //Trying to determine the files mimetype with php //Later we compare the determined mimetype to the one drupal determines. //Drupal (file_get_mimetype) determines the mimetype by mapping the file extension. $mimetype = ""; //mimetype string $extension_error = FALSE; if (extension_loaded('fileinfo')) { //use Fileinfo extension static $finfo = FALSE; if ($finfo || $finfo = @finfo_open(FILEINFO_MIME_TYPE)) { $mimetype = $finfo->file($file->filepath); } } else { $mimetype = mime_content_type($file->filepath); } if (strpos($mimetype,'image') !== FALSE AND strpos(file_get_mimetype($file->filepath),'image') !== FALSE) { //both our $mimetype-check and drupal report this to be an image //we double check with getimagesize if (!@getimagesize($file->filepath)) { $extension_error = TRUE; } } elseif (strpos($mimetype,'image') !== FALSE OR strpos(file_get_mimetype($file->filepath),'image') !== FALSE) { //only one of the checks thinks this is an image. //this covers both cases: // * javascript/text-file with a wrong extension // * image file with a wrong, e.g. "txt" extension $extension_error = TRUE; } $webfm_access_roles = webfm_get_access_roles();//load all existing roles foreach ($user->roles as $rid => $name) { if (array_key_exists($rid, $webfm_access_roles)) { $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 OR $extension_error === TRUE) { $err_msg[] = t('%filename has an invalid extension', array('%filename' => $file->filename)); $valid = FALSE; } if ($error['uploadsize'] == $user_roles) { $err_msg[] = t('%filename exceeds the maximum filesize of %maxfilesize', array('%filename' => $file->filename, '%maxfilesize' => format_size($uploadsize))); $valid = FALSE; } if ($error['usersize'] == $user_roles) { $err_msg[] = t('%filename exceeds the maximum disk quota of %quota', array('%filename' => $file->filename, '%quota' => format_size($usersize))); $valid = FALSE; } return $valid ? TRUE : FALSE; } /** * webfm_upload_validate * * * @param object $file - file object * @param array &$err_msg - ref to error array for client feedback * * @return bool - returns TRUE if there are no errors otherwise FALSE */ function webfm_upload_validate($file, &$err_msg) { $valid = webfm_enum_validate($file, $err_msg); 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; } } } elseif (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), 'u' => array('field' => 'uid', 'size' => 10)); } $err = ""; 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 = rawurldecode(drupal_substr($field, 0, 1)); $separator = drupal_substr($field, 1, 1); $value = rawurldecode(drupal_substr($field, 2, min((drupal_strlen($field) - 2), $metadata_key_arr[$key]['size']))); if (array_key_exists($key, $metadata_key_arr) && ($separator == ":")) { if ($key == 'u') { // Special handling for uid changes (admins only) if ($user == 1) { $uid_val = strval($value); if (is_numeric($uid_val) && (drupal_strlen($uid_val) << 11)) { // Check that requested uid exists $query = "SELECT uid FROM {users} WHERE uid = %d"; $result = db_result(db_query($query, $uid_val)); if ($result != NULL) { $metadata[$metadata_key_arr[$key]['field']] = $result; } else { $err = t('User not found.'); return FALSE; } } else { $err = t('Invalid data'); return FALSE; } } else { $err = t('Permission denied'); return FALSE; } } else { $metadata[$metadata_key_arr[$key]['field']] = strval($value); } } } if (count($metadata)) { $ret = webfm_dbupdate_file($fid, '', $metadata); if ($ret) { $err = t('Update successful.'); return TRUE; } else { $err = t('Update failed.'); } } else { if (!drupal_strlen($err)) { $err = t('Update not necessary.'); } return TRUE; } } else { $err = t('Permission denied.'); } } else { $err = t('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 * @param int $cid - Optional, comment id. * @return TRUE if records were updated - NULL if no changes were required. */ function webfm_dbupdate_attach($nid, $fids, $cid = 0 ) { $i = 0; if (!webfm_check_attach_order($nid, $fids, $cid)) { //the new fids are different from the old ones $query = 'DELETE FROM {webfm_attach} WHERE '; if ($cid == 0 ) { $id = $nid; $query .= 'nid = %d'; } else { $id = $cid; $query .= 'cid = %d'; } if ($result = db_query($query, $id)) { foreach ($fids as $fid) { if ($fid) webfm_dbinsert_attach($nid, $fid, $i++, $cid); $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 * @param int $cid - Optional, comment id. * @return bool - TRUE if the attach order is the same - FALSE if it has changed */ function webfm_check_attach_order($nid, $fids, $cid = 0) { if ($cid == 0 ) { $id = $nid; $selector = 'nid'; } else { $id = $cid; $selector = 'cid'; } //check array against db result $query = "SELECT fid FROM {webfm_attach} WHERE '%s' = %d ORDER BY weight"; $result = db_query($query, $selector, $id); $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 * @param int $cid - Optional, comment id. If given, $nid is set to 0 because * an attachment is stored either for a node OR a comment. * @return bool - TRUE if success - else FALSE */ function webfm_dbinsert_attach($nid, $fid, $weight, $cid = 0) { $query = 'SELECT * FROM {webfm_attach} WHERE '; if ($cid == 0 ) { $query .= 'nid = %d'; $type = 'node'; $id = $nid; } else { $query .= 'cid = %d'; $type = 'comment'; $id = $cid; $nid = 0; } $query .= ' AND fid = %d'; $result = db_query($query, $id, $fid); $exist = FALSE; while ($exist = db_fetch_object($result)) { drupal_set_message(t('File is already attached to this %t.', array('%t' => $type)),'warning'); return FALSE; } if ($exist === FALSE) { //actually do the attachment if its not already attached.... $query = 'INSERT INTO {webfm_attach} (nid, fid, weight, cid) VALUES (%d, %d, %d, %d)'; $result = db_query($query, $nid, $fid, $weight, $cid); if ($result === FALSE) { drupal_set_message(t('Query Failed: Could not attach files to %t %n', array('%t' => $type, '%n' => $id)),'error'); return FALSE; } else { return TRUE; } } } /** * webfm_dbdelete_attachments - deletes nodes/comments file associations. * * @param int $id - Node or comment id. * @param selector - Tell if we handle a node or a comment. * @return bool - TRUE if success - else FALSE * */ function webfm_dbdelete_attachments($id, $selector = 'nid') { $type = ($selector == 'nid') ? 'node' : 'comment'; $query = "DELETE FROM {webfm_attach} WHERE '%s' = %d"; $result = db_query($query, $selector, $id); if ($result === FALSE) { drupal_set_message(t('Failed to remove file attachments for deleted %type %id', array('%type' => $type, '%id' => $id))); return FALSE; } 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; } /** * Implement Views Module * Implement hook_views_api */ function webfm_views_api() { return array( 'api' => 2, 'path' => drupal_get_path('module', 'webfm') . '/views', ); } /** * Implementation hook_token_list(). * * @link http://api.drupal-contrib.org/api/function/token_token_list/token * * @param $type * @return Keyed Array of substitution tokens. */ function webfm_token_list($type = 'all') { if ($type == 'webfm' || $type == 'all') { $tokens['webfm']['filename'] = t("Filename"); $tokens['webfm']['webfmid'] = t("File Id"); $tokens['webfm']['webfmfolder-path-raw'] = t("Full folder Path as seen in webfm"); return $tokens; } } /** * Implementation hook_token_values(). * * @link http://drupalcontrib.org/api/function/token_token_values/6 * * @param $type * @param $object * @param $options * @return Array with token values */ function webfm_token_values($type, $object = NULL) { $values = array(); switch ($type) { case 'webfm': if (!empty($object)) { $webfmfile = (object)$object; $values['webfmid'] = $webfmfile->fid; $values['filename'] = _webfm_basename($webfmfile->fpath); if (variable_get('webfm_root_dir', NULL)) { $reldir = trim(str_replace(file_directory_path(), "", dirname($webfmfile->fpath)), '/\\'); //find root path down to webfm-root $webfmfile->frelativedir = trim(str_replace(variable_get('webfm_root_dir', NULL), "", $reldir), '/\\'); //delete drupal-root-file-path and trim trailing slash } else { $webfmfile->frelativedir = ''; } $values['webfmfolder-path-raw'] = $webfmfile->frelativedir; } break; } return $values; } /** * hook_pathauto * @link http://api.drupal-contrib.org/api/function/node_pathauto/pathauto * * @param $op * @return object */ function webfm_pathauto($op) { switch ($op) { case 'settings': $settings = array(); $settings['module'] = 'webfm'; $settings['token_type'] = 'webfm'; $settings['groupheader'] = t('Web File Manager path settings'); $settings['patterndescr'] = t('Pattern for webfm files paths'); $settings['patterndefault'] = t('webfm_send/[webfmid]'); $patterns = token_get_list('webfm'); foreach ($patterns['webfm'] as $pattern => $description) { $settings['placeholders']['['. $pattern .']'] = $description; } $settings['bulkname'] = t('Bulk generate aliases for webfm files that are not aliased'); $settings['bulkdescr'] = t('Generate aliases for all existing webfm files which do not already have aliases.'); return (object) $settings; } } /** * Implementation hook_pathauto_bulkupdate(). * * @link http://api.drupal-contrib.org/api/function/node_pathauto_bulkupdate/pathauto * * @return NULL */ function webfm_pathauto_bulkupdate() { $query = "SELECT fid FROM {webfm_file} LEFT JOIN {url_alias} ON CONCAT('webfm_send/', CAST(fid AS CHAR)) = src WHERE uid > 0 AND src IS NULL"; $result = db_query_range($query, 0, variable_get('pathauto_max_bulk_update', 50)); $count = 0; $placeholders = array(); while ($fids = db_fetch_object($result)) { $webfmfile = webfm_get_file_record($fids->fid); $placeholders = pathauto_get_placeholders('webfm', $webfmfile); $src = 'webfm_send/'. $webfmfile->fid; if ($alias = pathauto_create_alias('webfm', 'bulkupdate', $placeholders, $src, 'webfm')) { $count++; } } drupal_set_message(format_plural($count, 'Bulk generation of webfm file path completed, one alias generated.', 'Bulk generation of webfm file paths completed, @count aliases generated.')); }