'.t('Webfm is a hierarchical file system manager. Webfm does not use a flat file system (a single directory indexed by a database). Webfm allows users to arrange files on the server in the same way they do on their local storage drives. This ability to heirarchically arrange files greatly enhances the managability of large collections of data.').'

'. '

'.t('Note that webfm uses includes/file.inc which manages the file system path. The Root Directory and Ftp root directory paths are relative to this file system path and must be prefaced with a "/".', array('%admin-file' => url('admin/settings'), '%admin-webfm' => url('admin/settings/webfm'))).'

'. '

'.t('Webfm uses ajax and javascript extensively to provide application intensive functionality such as file/dir move and ordering of attachments via drag-and-drop. The context menuing provided by the right mouse button click provides context sensitive menus for user selection. Javascript must be enabled for webfm to function.').'

'. '

'.t('Webfm presents two left hand blocks to represent directory trees and a right hand block to list the contents of the current directory. The upper left block represents the directory structure of file data enumerated in the database and available to the site for attachment to content. The lower left block is the directory structure of the "ftp" directory. This tree is outside the region accessible to drupal content and its purpose is as a bulk upload area. For sites with large sets of documents, ftp is an good method of bulk transfer, especially if secure shell access does not exist (ie: inexpensive hosting). A hierarchical structure can be constructed in this area to be instantly copied and enumerated in the database with a single drag operation.').'

'; return $output; case 'admin/modules#description': return t('Enable the Web Networks File Browser.'); } } /** * Implementation of hook_settings(). */ function webfm_admin_settings() { $form['webfm_root_dir'] = array('#type' => 'textfield', '#title' => t('Root directory'), '#default_value' => variable_get('webfm_root_dir', '/webfm'), '#maxlength' => '100', '#size' => '70', '#description' => t('Root directory used to present the filebrowser interface. Users will not be able to go up from this folder.

This path is relative to "File system path" set in admin/settings and must be preceeded with a slash.') ); $form['webfm_ftp_root_dir'] = array('#type' => 'textfield', '#title' => t('FTP root directory'), '#default_value' => variable_get('webfm_ftp_root_dir', '/ftp'), '#maxlength' => '100', '#size' => '70', '#description' => t('WebFM allows you to move files from a specified FTP folder to the file manager thereby making those files available to your drupal site. The benefit of this feature is to allow you to do bulk uploads of files via FTP and then let webFM make your site aware of them via drag and drop.

This path is relative to "File system path" set in admin/settings and must be preceeded with a slash.') ); $form['webfm_icon_dir'] = array('#type' => 'textfield', '#title' => t('Icon directory'), '#default_value' => variable_get('webfm_icon_dir', 'modules/webfm/image/icon'), '#maxlength' => '100', '#size' => '70', '#description' => t('Name of directory where file type icons are stored (relative to base url).') ); $form['webfm_attach_body'] = array('#type' => 'checkbox', '#title' => t('Append file links to Node Body'), '#default_value' => variable_get('webfm_attach_body', ''), '#description' => t('Check this box to append downloadable attachments to the node body.
This setting does not affect the attachment block.') ); $form['webfm_debug'] = array('#type' => 'checkbox', '#title' => t('Webfm javascript debug'), '#default_value' => variable_get('webfm_debug', ''), '#description' => t('Check this box for javascript debug messaging.') ); $form['webfm_frbdn'] = array('#type' => 'textarea', '#title' => t('Forbidden'), '#default_value' => variable_get('webfm_frbdn', '.,..,.svn,index.php,index.phps,upgrade.php,upgrade.phps,config.php,favicon.ico,.htaccess,.ftpquota,recycled,systemvolumeinformation,icon'), '#description' => t('Forbidden file types (use comma delimited with no spaces)') ); $roles = user_roles(1, 'access webfm'); foreach ($roles as $rid => $role) { $form["settings_role_".$rid] = array('#type' => 'fieldset', '#title' => t('Settings for @role', array('@role' => $role)), '#collapsible' => TRUE, '#collapsed' => TRUE ); $form["settings_role_".$rid]["webfm_extensions_".$rid] = array('#type' => 'textfield', '#title' => t('Permitted file extensions'), '#default_value' => variable_get("webfm_extensions_".$rid, "jpg jpeg gif png txt html htm doc xls pdf ppt pps"), '#maxlength' => 255, '#description' => t('Extensions that users in this role can upload. Separate extensions with a space and do not include the leading dot.') ); $form["settings_role_".$rid]["webfm_uploadsize_".$rid] = array('#type' => 'textfield', '#title' => t('Maximum file size per upload'), '#default_value' => variable_get("webfm_uploadsize_".$rid, 1), '#size' => 5, '#maxlength' => 5, '#description' => t('The maximum size of a file a user can upload (in megabytes).') ); $form["settings_role_".$rid]["webfm_usersize_".$rid] = array('#type' => 'textfield', '#title' => t('Total file size per user'), '#default_value' => variable_get("webfm_usersize_".$rid, 10), '#size' => 5, '#maxlength' => 5, '#description' => t('The maximum size of all files a user can have on the site (in megabytes).') ); } return system_settings_form($form); } /** * Implementation of hook_perm(). */ function webfm_perm() { return array('access webfm', 'attach WebFM files', 'see webfm_attachments'); } /** * Implementation of hook_menu(). */ function webfm_menu($maycache) { $items = array(); if ($maycache) { $items[] = array( 'title' => t('Web File Manager'), 'path' => 'admin/webfm', 'access' => user_access('access webfm'), 'callback' => 'webfm_main'); $items[] = array( 'title' => t('Web File Manager'), 'path' => 'webfm_js', 'access' => user_access('access webfm'), 'callback' => 'webfm_ajax', 'type' => MENU_CALLBACK); $items[] = array( 'title' => t('Web File Manager'), 'path' => 'admin/webfm/upload', 'access' => user_access('access webfm'), 'callback' => 'webfm_upload', 'type' => MENU_CALLBACK); $items[] = array( 'title' => t('File Not Found'), 'path' => 'webfm_send', 'access' => user_access('see webfm_attachments'), 'callback' => 'webfm_send_file', 'type' => MENU_CALLBACK); $items[] = array('path' => 'admin/settings/webfm', 'title' => t('Webfm Settings'), 'description' => t('Configure WebFM.'), 'callback' => 'drupal_get_form', 'callback arguments' => array('webfm_admin_settings'), 'access' => user_access('administer site configuration'), 'type' => MENU_NORMAL_ITEM); } return $items; } /** * Implementation of hook_block(). */ function webfm_block($op = 'list', $delta = 0) { if ($op == 'list') { $blocks[0]['info'] = t('Webfm File Attachments'); return $blocks; } else if ($op == 'view' && user_access('access content') && user_access('see webfm_attachments')) { $block['content'] = webfm_attach_box(); $block['subject'] = t('Attachments'); return $block; } } function webfm_attach_box() { if (arg(0) == 'node' && is_numeric(arg(1)) && !arg(2)) { $node = node_load(arg(1)); } $files = webfm_get_attachments($node->nid); return theme('webfm_attachments', $files); } /** * Implementation of hook_nodeapi(). */ function webfm_nodeapi(&$node, $op, $teaser) { switch ($op) { case 'load': if ((variable_get("wfm_attach_$node->type", 1) == 1) && user_access('see webfm_attachments')) { $output['webfm_files'] = webfm_get_attachments($node->nid); } return $output; break; case 'view': // Add the attachments list to node body if configured to appear in body if (is_array($node->webfm_files) && variable_get('webfm_attach_body', '')) { if (count($node->webfm_files) && !$teaser) { $node->content['webfm_attachments'] = array( '#value' => theme('webfm_attachments', $node->webfm_files), '#weight' => 10, ); } } break; case 'insert': if($_POST['attachlist']) { $files = explode(',', $_POST['attachlist']); $i = 0; foreach($files as $fid) { if($fid) // weight argument determined by position in csv webfm_dbinsert_attach($node->nid, $fid, $i++); } } break; case 'update': $files = explode(',', $_POST['attachlist']); webfm_dbupdate_attach($node->nid, $files); break; } } /** * Displays file attachments in table */ function theme_webfm_attachments($files) { global $base_url; $header = array(t('Attachment'), t('Size')); $rows = array(); foreach ($files as $file) { // 0 =inline : 1 = attach $icon_path = $base_url.'/'.variable_get('webfm_icon_dir', 'modules/webfm/image/icon').'/f.gif'; $href = array('data' => l('[file] ', 'webfm_send/'.$file->id.'/1', '', '' , '' , '', TRUE).l(check_plain($file->ftitle ? $file->ftitle : $file->n), 'webfm_send/'.$file->id)); $rows[] = array($href, format_size($file->s)); } if (count($rows)) { return theme('table', $header, $rows, array('id' => 'webfm-attach-list')); } } /** * Implementation of hook_form_alter(). */ function webfm_form_alter($form_id, &$form) { global $base_url; if (isset($form['type'])) { if ($form['type']['#value'] .'_node_settings' == $form_id) { $form['workflow']['wfm_attach_'. $form['type']['#value']] = array( '#type' => 'radios', '#title' => t('Webfm Attachments'), '#default_value' => variable_get('wfm_attach_'. $form['type']['#value'], 1), '#options' => array(t('Disabled'), t('Enabled')), ); } $node = $form['#node']; if (user_access('attach WebFM files') && $form['type']['#value'] .'_node_form' == $form_id && variable_get("wfm_attach_$node->type", TRUE)) { $modulepath = drupal_get_path('module', 'webfm'); drupal_add_js($modulepath.'/js/webfm.js'); drupal_add_js($modulepath.'/js/webfm_upload.js'); drupal_add_js('misc/progress.js'); drupal_add_css($modulepath.'/css/webfm.css'); if(is_null($inline_js)) { $clean_url = variable_get('clean_url', 0); $clean = (($clean_url == 0) || ($clean_url == '0')) ? FALSE : TRUE; $inline_js = webfm_inline_js($base_url, $clean); } // Attachments fieldset $form['#theme'] = 'webfm_upload_form'; $form['webfm-attach']['attached'] = array( '#type' => 'fieldset', '#title' => t('Attached files'), '#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']['attached']['attachedfiles'] = array( '#prefix' => '
', '#suffix' => '
', ); $form['webfm-attach']['attached']['attachedfiles'] += webfm_attach_attached_form($node); $form['browser']['browser'] = array( '#type' => 'fieldset', '#title' => t('File Browser'), '#collapsible' => TRUE, '#collapsed' => TRUE, '#weight' => 30); // Wrapper for fieldset contents (used by upload JS). $form['browser']['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['browser']['browser']['wrapper']['wrapper'] = array( '#prefix' => '
', '#suffix' => '
'); $form['browser']['browser']['wrapper']['wrapper'] += webfm_upload_form(); $form['#attributes']['enctype'] = 'multipart/form-data'; } } } 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 $form['new']['attachlist'] = array( '#type' => 'hidden', '#value' => ''); 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; } function webfm_upload () { $root_path = file_directory_path().variable_get('webfm_root_dir', ''); //Get the destination path from the edit-webfmuploadpath hidden field in the upload form if($_POST['webfmuploadpath']) { // Check that webfm root is at start of destination path if($dest = wfm_check_path($_POST['webfmuploadpath'], $root_path)) { // Save new file uploads to tmp dir. if(($file = file_check_upload('webfm_upload')) != FALSE) { if(webfm_upload_validate($file) === TRUE) { // file has been put in temp and we have a valid file object if($file_uploaded = file_move($file, $dest)) { // file was moved to its final destination if($file_in_db = webfm_dbinsert_file($file, $dest)) { // file was inserted into the database drupal_set_message('Upload success'); } else { file_delete($file->filepath); drupal_set_message('webfm_dbinsert_file() failed', error); } } else { drupal_set_message(t('file_move to %path failed', array('%path' => $dest)), error); } } else { drupal_set_message('webfm_upload_validate() failed', error); } } else { drupal_set_message('file_check_upload() failed', error); } } else{ drupal_set_message(t('Invalid destination path: %dest', array('%dest' => $dest)), error); } } else { drupal_set_message(t('Invalid upload path'), error); } $form = webfm_upload_form(); $form = form_builder('upload_js', $form); $output = theme('status_messages') . drupal_render($form); // We send the updated file attachments form. print drupal_to_js(array('status' => TRUE, 'data' => $output)); exit(); } function webfm_ajax () { if(isset($_POST["action"])) { $root_path = file_directory_path().variable_get('webfm_root_dir', ''); $ftp_path = file_directory_path().variable_get('webfm_ftp_root_dir', ''); switch(trim(strtolower($_POST["action"]))) { //Get context menu items case "delete": if(isset($_POST["param0"])) { if($source = wfm_check_path(trim(rawurldecode($_POST["param0"])), $root_path)) $db_check = TRUE; else if($source = wfm_check_path(trim(rawurldecode($_POST["param0"])), $ftp_path)) $db_check = FALSE; // prevent any ../ shenanigans if($source && !ereg('\.\.', $source)) { print drupal_to_js(array('status' => webfm_delete($source, $db_check))); } } exit(); break; //Create new directory case "mkdir": if(isset($_POST["param0"])) { if(($source = wfm_check_path(trim(rawurldecode($_POST["param0"])), $root_path)) || ($source = wfm_check_path(trim(rawurldecode($_POST["param0"])), $ftp_path))) { $dest = t("New_Folder"); print drupal_to_js(array('status' => webfm_mkdir($source, $dest))); } } exit(); break; //Move a file or directory (drag and drop) case "move": if(isset($_POST["param0"]) && isset($_POST["param1"])) { // Source must be either under webfm_root or ftp_root if($source = wfm_check_path(trim(rawurldecode($_POST["param0"])), $root_path)) $db_check = TRUE; else if ($source = wfm_check_path(trim(rawurldecode($_POST["param0"])), $ftp_path)) $db_check = FALSE; // Destination path must be under webfm_root if($source && ($dest = wfm_check_path(trim(rawurldecode($_POST["param1"])), $root_path)) && ($source != $dest)) { print drupal_to_js(array('status' => webfm_move($source, $dest, $db_check))); } } exit(); break; //Rename an existing file or directory case "rename": if(isset($_POST["param0"]) && isset($_POST["param1"])) { $db_check = FALSE; if($source = wfm_check_path(trim(rawurldecode($_POST["param0"])), $root_path)) $db_check = TRUE; if($source || ($source = wfm_check_path(trim(rawurldecode($_POST["param0"])), $ftp_path))) { $dest = trim(rawurldecode($_POST["param1"])); // prevent any ../ shenanigans if(!ereg('\.\.', $dest)) { print drupal_to_js(array('status' => webfm_rename($source, $dest, $db_check))); } else { print drupal_to_js(array('status' => FALSE)); } } else { print drupal_to_js(array('status' => FALSE)); } } exit(); break; //Read directory tree case "readtree": //Build directory tree $tree = new build_dir_tree($root_path, false); print drupal_to_js(array('status' => TRUE, 'tree' => $tree->get_dirtree(), 'current' => $root_path)); exit(); break; //Read ftp directory tree case "readftptree": //Build directory tree $tree = new build_dir_tree($ftp_path, false); print drupal_to_js(array('status' => TRUE, 'tree' => $tree->get_dirtree(), 'current' => $root_path)); exit(); break; //Read directory set in $_POST["param0"] case "read": if(isset($_SESSION['directory'])) { $read_dir = $_SESSION['directory']; unset($_SESSION['directory']); } else if(isset($_POST["param0"])) $read_dir = rawurldecode($_POST["param0"]); if(!is_dir($read_dir)) $read_dir = $root_path; $rootpath_var = ''; if($source = wfm_check_path(trim($read_dir), $root_path)) $rootpath_var = 'webfm_root_dir'; else if($source = wfm_check_path(trim($read_dir), $ftp_path)) $rootpath_var = 'webfm_ftp_root_dir'; if($rootpath_var) { if(!is_dir($source) || ereg('\.\.', $source)) exit(); //Build current directory listings $dirlist = new build_dir_list($source, $rootpath_var); if($dirlist->get_breadcrumb()) print drupal_to_js(array('status' => TRUE, 'current' => $source, 'bcrumb' => $dirlist->get_breadcrumb(), 'dirs' => $dirlist->get_dir_listing(), 'files' => $dirlist->get_file_listing())); else //invalid directory print drupal_to_js(array('status' => FALSE)); } 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 = ''; $maxlevel = 0; @clearstatcache(); $search = new searchFiles($source, $searchpattern, $maxlevel, $regexpsearch); print drupal_to_js(array('files' => $search->get_files())); } } exit(); break; //Get file metadata case "getmeta": if(isset($_POST["param0"])) { $fid = rawurldecode($_POST["param0"]); if(is_numeric($fid) && (($meta = webfm_getmeta($fid)) !== FALSE)) { print drupal_to_js(array('status' => TRUE, 'meta' => $meta)); } else { print drupal_to_js(array('status' => FALSE)); } } exit(); break; //Change file metadata case "putmeta": if(isset($_POST["param0"]) && isset($_POST["param1"])) { print drupal_to_js(array('status' => webfm_putmeta(rawurldecode($_POST["param0"]), rawurldecode($_POST["param1"])))); } exit(); break; //Get attached items case "attach": // TO DO: improve this method of getting the node number $node_str = trim(strtolower(rawurldecode($_POST["param0"]))); // the 'node' var passed via AJAX is the action attribute of id=node-form if (($node_num = strstr($node_str, 'node/')) !== FALSE) { $node_arr = explode("/", $node_num); print drupal_to_js(array('status' => TRUE, 'attach' => webfm_get_attachments($node_arr[1]))); } else { print drupal_to_js(array('status' => FALSE)); } exit(); break; //Get file info by fid for attachment case "attachfile": $fid = rawurldecode($_POST["param0"]); $query = "SELECT * FROM {webfm_file} WHERE fid = '%s'"; if($_file = db_fetch_object(db_query($query, $fid))) { $file = new fdesc($_file); print drupal_to_js(array('status' => TRUE, 'attach' => $file)); } else { print drupal_to_js(array('status' => FALSE)); } exit(); break; default: exit(); break; } exit(); } } /** * Main file manager function */ function webfm_main () { global $base_url; $modulepath = drupal_get_path('module', 'webfm'); drupal_add_js($modulepath.'/js/webfm.js'); drupal_add_js($modulepath.'/js/webfm_upload.js'); drupal_add_js('misc/progress.js'); drupal_add_js('misc/collapse.js'); drupal_add_css($modulepath.'/css/webfm.css'); if(is_null($inline_js)) { $clean_url = variable_get('clean_url', 0); $clean = (($clean_url == 0) || ($clean_url == '0')) ? FALSE : TRUE; $inline_js = webfm_inline_js($base_url, $clean); } $output = ''."\n"; $output .= '
'."\n"; $output .= drupal_get_form('webfm_upload_fieldset'); $output .= '
'."\n"; return $output; } function webfm_upload_fieldset() { $form = array(); $form['webfm_uploads'] = array( '#type' => 'fieldset', '#title' => t('File Upload'), '#collapsible' => TRUE, '#collapsed' => TRUE, '#description' => t('Uploaded file will be saved to the current directory.'), '#prefix' => '
', '#suffix' => '
', '#weight' => 30); // Wrapper for fieldset contents (used by upload JS). // NOTE: upload.js requires six char prefix on wrapper/button names $form['webfm_uploads']['wrapper'] = array( '#prefix' => '
', '#suffix' => '
'); $form['webfm_uploads']['wrapper'] += webfm_upload_form(); $form['#attributes']['enctype'] = 'multipart/form-data'; return $form; } function webfm_upload_form() { $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('admin/webfm/upload', NULL, NULL, TRUE), '#attributes' => array('class' => 'webfmupload')); return $form; } /** * Theme the attachment form. * Note: required to output prefix/suffix. */ function theme_webfm_upload_form($form) { $output = drupal_render($form); return $output; } /** * Inline javascript * Function to pass base_url, icon directory, debug and cleanurl flags */ function webfm_inline_js($base_url, $clean_url) { $js = ''; drupal_set_html_head($js); return $js; } /** * Helper function to check for root path at base of input path */ function wfm_check_path($path, $root) { return strpos($path, $root) === 0 ? $path : ''; } /** * Class to build the directory, file and breadcrumb listings * ..for the directory at $path for javascript Load_dirlist() */ class build_dir_list { var $dirs = array(); var $files = array(); var $breadcrumb = array(); //Constructor function build_dir_list($path, $rootpath_var) { $bl = array('.', '..', '.svn', '.htaccess'); $_dirs = array(); $_files = array(); if (is_dir($path)) { chdir($path); if($handle = opendir('.')) { if(variable_get('webfm_root_dir', '')) { $root_path = trim(file_directory_path().variable_get($rootpath_var, ''),"/"); $root_arr = explode('/', $root_path); // Hide root path elements except for last directory for($i = 0; $i < count($root_arr) - 1; $i++) $this->breadcrumb[] = array("h", $root_arr[$i]); $this->breadcrumb[] = array("v", $root_arr[$i]); if($non_root_path = trim(substr($path, strlen($root_path)),"/")) { $non_root_arr = explode('/', $non_root_path); foreach($non_root_arr as $piece) $this->breadcrumb[] = array("v", $piece); } } while(false !== ($readdir = readdir($handle))) { // check that directory element is readable and not in black list if(!in_array(strtolower($readdir), $bl)) { if(is_dir($readdir)) $_dirs[] = $readdir; if(is_file($readdir)) $_files[] = $readdir; } } closedir($handle); } if(is_array($_dirs)) { foreach($_dirs as $dir) { $dd = new stdClass(); $dd->n = $dir; $dd->p = $path."/".$dir; $dd->m = (filemtime($dir)) ? date('Y-m-d H:i:s', @filemtime($dir)) : ""; $this->dirs[] = $dd; } } if(is_array($_files)) { foreach($_files as $file) { $fd = new stdClass(); $fd->n = $file; $fd->p = $path; $fd->id = webfm_get_fid($path."/".$file); $fd->m = (filemtime($file)) ? date('Y-m-d H:i:s', @filemtime($file)) : ""; $fd->s = @filesize($file); if($i = @getimagesize($file)) { if(($i[0] != 0) && ($i[1] != 0)) $fd->i = $i[2]; } else $fd->i = 0; if(strpos($file, ".") === false) { $fd->e = ""; } else { $fd->e = strtolower(substr($file, strrpos($file, ".") + 1)); } $this->files[] = $fd; } } } } function get_dir_listing() { return $this->dirs; } function get_file_listing() { return $this->files; } function get_breadcrumb() { return $this->breadcrumb; } } /** * Class to read the directory tree */ class build_dir_tree { var $js_arr = array(); // Constructor function build_dir_tree($root, $full = false) { $dirtree = array(); $root = rtrim($root, "/"); $dirtree[$root] = $this->recurse_build_tree($root, $full); $this->js_arr[] = $dirtree; } // Function to recursively read the complete directory tree function recurse_build_tree($dir, $full) { $bl = array('.', '..', '.svn', '.htaccess'); if ($handle = opendir($dir)) { while (false !== ($readdir = readdir($handle))) { if(!in_array(strtolower($readdir), $bl)) { $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] = $this->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 get_dirtree() { return $this->js_arr; } } function webfm_get_attachments($nid) { $files = array(); $file_result = db_query('SELECT * FROM {webfm_file} f INNER JOIN {webfm_attach} a ON f.fid = a.fid WHERE a.nid = %d ORDER BY a.weight', $nid); while($file_record = db_fetch_object($file_result)) { $_file = new fdesc($file_record); if($_file->result == TRUE) { // drupal_set_message(printf('$_file= %s', print_r($_file))); $files[] = $_file; } } return $files; } // File description class // TO DO: remove spurious record if anything fails! class fdesc { var $result; // Constructor: function fdesc($file) { $cwd = getcwd(); $this->result = FALSE; $dir = dirname($file->fpath); //assume the object $file record path has a directory before the file name if (is_dir($dir)) { if(chdir($dir)) { if($handle = opendir('.')) { while(($readdir = readdir($handle)) !== false) { if(is_dir($readdir)) continue; if(is_file($readdir) && ($readdir == basename($file->fpath))) { $this->id = $file->fid; $this->n = $file->fname; $this->p = $dir; $this->e = $file->fmime; $this->s = $file->fsize; $this->uid = $file->uid; /* rename fields for expected js variables $this->fid = $file->fid; $this->fpath = $file->fpath; $this->fname = $file->fname; $this->fsize = $file->fsize; $this->fmime = $file->fmime; */ $this->ftitle = $file->ftitle; $this->fdesc = $file->fdesc; $this->fcreatedate = $file->fcreatedate; $this->flang = $file->flang; $this->fpublisher = $file->fpublisher; $this->fformat = $file->fformat; $this->fversion = $file->fversion; $this->m = (filemtime($readdir)) ? date('Y-m-d H:i:s', @filemtime($readdir)) : ""; if($i = @getimagesize($readdir)) { $this->w = (int) $i[0]; $this->h = (int) $i[1]; $this->i = $i[2]; if(($i[0] == 0) || ($i[1] == 0)) $this->i = 0; } else $this->i = 0; $this->result = TRUE; break; } } closedir($handle); } // Restore current working directory chdir($cwd); } } } } // Function to sanitize long filenames function webfm_sanlen($x) { if(strlen($x) > 80) return substr($x, 0, 40)."...".substr($x, -40, 40); return $x; } /** * Class to search for files matching a regexp pattern */ class searchFiles { var $count = 0; var $level = 0; var $max_levels = 0; var $files = array(); var $hidefilepattern; //Constructor function searchFiles($dir, $searchpattern, $searchmaxlevels, $regexpsearch = FALSE) { $this->hidefilepattern = "^(CVS|\..*)$"; /* if(!$regexpsearch) { $searchpattern = "^".str_replace("*", ".*", str_replace("?", ".", str_replace(".", "\.", $searchpattern)))."$"; } */ if($searchmaxlevels) $this->max_levels = $searchmaxlevels; $this->count = $this->searchFilesRecur($dir, $searchpattern); } function get_files() { return $this->files; } function get_count() { return $this->count; } function searchFilesRecur($dir, $searchpattern) { $count = 0; if(($this->max_levels == 0) || ($this->level < $this->max_levels)) { $dir = rtrim($dir, '/'); $handle = @opendir($dir); while (($file = @readdir($handle))) { if(@is_dir($dir."/".$file) && ($file != ".") && ($file != "..")) { $this->level++; $count += $this->searchFilesRecur($dir."/".$file, $searchpattern); } else if (ereg(strtolower($searchpattern), strtolower($file)) && !ereg($this->hidefilepattern, $file)) { $sfd = new stdClass(); $sfd->n = $file; $sfd->p = $dir; $sfd->id = webfm_get_fid($dir."/".$file); $this->files[] = $sfd; $count++; } else { } } @closedir($handle); } return $count; } } /** * webfm_send_file - streams a file privately for download * * @param object $fid - file id * @param bool $attach - 1 = attach / 0 = inline */ function webfm_send_file($fid, $attach = false) { $query = "SELECT * FROM {webfm_file} WHERE fid = '%s'"; if($f = db_fetch_object(db_query($query, $fid))) { // Put file path into session var so back button can return to this dir $path = dirname($f->fpath); //temporary storage of download directory for back button navigation $_SESSION['directory'] = $path; $name=basename($f->fpath); //filenames in IE containing dots will screw up the //filename unless we add this if(strstr($_SERVER['HTTP_USER_AGENT'], "MSIE")) $name = preg_replace('/\./', '%2e', $name, substr_count($name, '.') - 1); // Get file extension $ext = explode('.', $name); $extension = $ext[count($ext)-1]; // Try and find appropriate type switch(strtolower($extension)) { case 'txt': $type = 'text/plain'; break; case "pdf": $type = 'application/pdf'; break; case "exe": $type = 'application/octet-stream'; break; case "zip": $type = 'application/zip'; break; case "doc": $type = 'application/msword'; break; case "xls": $type = 'application/vnd.ms-excel'; break; case "ppt": $type = 'application/vnd.ms-powerpoint'; break; case "gif": $type = 'image/gif'; break; case "png": $type = 'image/png'; break; case "jpg": $type = 'image/jpg'; break; case "jpeg": $type = 'image/jpg'; break; case "html": $type = 'text/html'; break; default: $type = 'application/force-download'; } //download headers: $header = array(); if($attach === '1') { // prompt for download file or view $header[] = 'Pragma: no-cache'; $header[] = 'Cache-Control: no-cache, must-revalidate'; $header[] = 'Content-Disposition: attachment; filename='.$name.';' ; } 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.';' ; } $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); } else { //Print theme + page title for webfm_send path print theme('page', ""); } } /** * webfm_dbinsert_file - inserts a file object into the webfm_file table * * @param object $file - complete file object * @param string $path - a string containing the path relative to drupal root * @param array $metadata - an array of key => value pairs, where key matches a field in the webfm_file table * * @return bool - TRUE if query executed successfully, otherwise FALSE */ function webfm_dbinsert_file($file, $path = 'files', $metadata = array()){ //we need our user global $user; //add additional values to $metadata $metadata['uid'] = $user->uid; $metadata['fpath'] = $file->filepath; //$path; //if we decide we don't want the filename in the path - use $path variable instead. $metadata['fname'] = strrev(substr(strrev($file->filepath), 0, strpos(strrev($file->filepath), '/')));//$file->filepath; //$metadata['fname'] = $file->filename; $metadata['fsize'] = $file->filesize; $metadata['fmime'] = $file->filemime; //create a string of fields for the query $fields = implode(', ', array_keys($metadata)); //build printf style list of values foreach($metadata as $key => $value){ if(is_numeric($value)){ $printfvalues[] = '%d'; } else{ $printfvalues[] = "'%s'"; } } //create a srting of printf style values $printfvalues = implode(', ', $printfvalues); //create an array of just the values for the db_query $values = array_values($metadata); //make a db_query friendly query with prinf stuff $query = "INSERT INTO {webfm_file} ($fields) VALUES ($printfvalues)"; $result = db_query($query, $values); if($result === FALSE){ drupal_set_message(t('Query Failed: Could not insert file into the database')); return FALSE; } else{ return TRUE; } } /** * webfm_dbupdate_file - updates information about a file (most likely during a move operation) * * @param int $fid - file id of the file to record to be altered * @param object $file - optional a file object * @param string $path string containing the destination path relative to drupal root * @param array $metadata - an array of key => value pairs, where key matches a field in the webfm_file table * * @return bool - TRUE if success - else FALSE */ function webfm_dbupdate_file($fid, $path = FALSE, $metadata = array()){ if($path){ //add additional values to $metadata $metadata['fpath'] = $path; } //create a string of field value items in printf format foreach($metadata as $key => $value){ if(is_numeric($value)){ $printfvalues[] = $key .'=%d'; } else{ $printfvalues[] = $key ."='%s'"; } } $printfvalues = implode(', ', $printfvalues); $values = array_values($metadata); $values[] = $fid; //tack on the fid at the end for the last param for the update query - i.e. WHERE fid = %d //make a db_query friendly query with prinf stuff $query = "UPDATE {webfm_file} SET $printfvalues WHERE fid = %d"; $result = db_query($query, $values); if($result === FALSE){ drupal_set_message(t('webfm_dbupdate_file() err: fid=%fid', array('%fid' => $fid)), error); return FALSE; } return TRUE; } /** * webfm_upload_validate * * * @param object $file * @return bool - returns TRUE if there are no errors othewise FALSE */ function webfm_upload_validate($file){ global $user; foreach ($user->roles as $rid => $name) { $extensions = variable_get("webfm_extensions_".$rid, 'jpg jpeg gif png txt html htm doc xls pdf ppt pps'); $uploadsize = variable_get("webfm_uploadsize_".$rid, 1) * 1024 * 1024; $usersize = variable_get("webfm_usersize_".$rid, 1) * 1024 * 1024; $regex = '/\.('. ereg_replace(' +', '|', preg_quote($extensions)) .')$/i'; 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) { form_set_error('upload', t('The selected file %name can not be attached to this post, because it is only possible to attach files with the following extensions: %files-allowed.', array('%name' => theme('placeholder', $file->filename), '%files-allowed' => theme('placeholder', $extensions)))); $valid = FALSE; } elseif ($error['uploadsize'] == $user_roles) { form_set_error('upload', t('The selected file %name can not be attached to this post, because it exceeded the maximum filesize of %maxsize.', array('%name' => theme('placeholder', $file->filename), '%maxsize' => theme('placeholder', format_size($uploadsize))))); $valid = FALSE; } elseif ($error['usersize'] == $user_roles) { form_set_error('upload', t('The selected file %name can not be attached to this post, because the disk quota of %quota has been reached.', array('%name' => theme('placeholder', $file->filename), '%quota' => theme('placeholder', format_size($usersize))))); $valid = FALSE; } elseif (strlen($file->filename) > 255) { form_set_error('upload', t('The selected file %name can not be attached to this post, because the filename is too long.', array('%name' => theme('placeholder', $munged_filename)))); $valid = FALSE; } if (!$valid) { drupal_set_message(t("FILE %s NOT VALID", array('%s' => $file->filename)), error); return FALSE; } else{ return TRUE; } } /** * Given a file path this functions 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; } function webfm_getmeta($fid) { $query = "SELECT * FROM {webfm_file} WHERE fid = %d"; if(($result = db_query($query, $fid)) !== FALSE) { if($row = db_fetch_object($result)) { return $row; } } return FALSE; } function webfm_putmeta($fid, $metadata) { if(is_numeric($fid)) { $fields = explode(',',$metadata); $metadata = array(); foreach($fields as $field) { // Parse webfm_file_key/metadata pairs // Format: "#".key."=".value if((strpos($field, '#') === 0) && (strpos($field, '=') !== FALSE)) { $metadata[substr($field, 1, strpos($field, '=') - 1)] = substr($field, strpos($field, '=') + 1); } } if(isset($metadata)) { return webfm_dbupdate_file($fid, '', $metadata); } else return TRUE; } 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)) { if(module_exists('webfm_attachment') && _webfm_dbdelete_attach_fid($fid)) { return TRUE; } else return TRUE; } return FALSE; } /** * Helper function that deletes db entries from the webfm_file table given an fid * called from webfm_dbdelete_file * * @param int $fid * @return bool */ function _webfm_dbdelete_file_fid($fid){ $query = 'DELETE FROM {webfm_file} WHERE fid = %d'; $result = db_query($query, $fid); if($result === FALSE){ drupal_set_message(t('Query Failed: Could not delete file %fid .', array('%fid' => $fid), error)); return FALSE; } return TRUE; } /** * webfm_dbupdate_attach - updates the files in the webfm_attach table IF the order * * @param int $nid * @param array $fids - could be a comma seperated string - we need to work that out - works both ways now * @return TRUE if records were updated - NULL if no changes were required. */ function webfm_dbupdate_attach($nid, $fids){ // drupal_set_message(t('fidcount= %fid', array('%fid' => count($fids)))); $i = 0; if(!webfm_check_attach_order($nid, $fids)){ //the new fids are different from the old ones $query = "DELETE FROM {webfm_attach} WHERE nid = %d"; if($result = db_query($query, $nid)){ foreach($fids as $fid){ drupal_set_message(t('fid= %fid', array('%fid' => $fid))); if($fid) webfm_dbinsert_attach($nid, $fid, $i++); $flag = TRUE; } if($flag === TRUE) return TRUE; } } } /** * webfm_checkattachorder - checks to see if the new order of the fids is the same as the old order stored in the database * * @param int $nid - node id * @param array $fids - array of file ids * @return bool - TRUE if the attach order is the same - FALSE if it has changed */ function webfm_check_attach_order($nid, $fids){ //check array against db result $query = "SELECT fid FROM {webfm_attach} WHERE nid = %d ORDER BY weight"; $result = db_query($query, $nid); if($dbfids = db_fetch_array($result)){ if(count($dbfids) <= count($fids)){ return false; } for($i == 0; $i<=count($fids); $i++){ if($dbfids[$i] == $fids[$i]){ $match = TRUE; } else { return FALSE; } } } if($match) return TRUE; } /** * webfm_dbinsert_attach - inserts nid, fid and weight to webfm_attach table (similar to files table) * * @param int $nid - node id * @param int $fid - file id from the webfm_file table * @param int $weight - weight value * * @return bool - TRUE if success - else FALSE */ function webfm_dbinsert_attach($nid, $fid, $weight){ // drupal_set_message('DBG: SELECT * FROM {webfm_attach} WHERE nid = '. $nid .' AND fid = '.$fid); $query = 'SELECT * FROM {webfm_attach} WHERE nid = %d AND fid = %d'; $result = db_query($query, $nid, $fid); if(!mysql_num_rows($result) == 0) { drupal_set_message(t('File is already attached to this node.')); return FALSE; } else { //actually do the attacment if its not already attached.... $query = 'INSERT INTO {webfm_attach} (nid, fid, weight) VALUES (%d, %d, %s)'; $result = db_query($query, $nid, $fid, $weight); if($result === FALSE) { drupal_set_message(t('Query Failed: Could not attach files to node ') . $nid); return FALSE; } else { return TRUE; } } } /** * webfm_dbdelete_attach - deletes node file associations given a nid and fid * * @param int $nid - node id * @param int $fid - file id from the webfm_file table * @return bool - TRUE if success - else FALSE * */ function webfm_dbdelete_attach($nid, $fid){ $query = 'DELETE FROM {webfm_attach} WHERE nid = %d AND fid = %d'; $result = db_query($query, $nid, $fid); if($result === FALSE) { drupal_set_message(t('Query Failed: Could not detach file %fid from node %nid', array('%fid' => $fid, '%nid'=>$nid))); return FALSE; } return TRUE; } /** * Helper function that deletes db entries from the webfm_attach table given fid * called from webfm_dbdelete_file * * @param int $fid * @return bool */ function _webfm_dbdelete_attach_fid($fid){ $query = 'DELETE FROM {webfm_attach} WHERE fid = %d'; $result = db_query($query, $fid); if($result === FALSE) { drupal_set_message(t('Query Failed: Could not detach file %fid from nodes.', array('%fid' => $fid))); return FALSE; } return TRUE; }