Index: webfm.module
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/webfm/webfm.module,v
retrieving revision 1.39
diff -u -r1.39 webfm.module
--- webfm.module	20 Sep 2009 00:36:48 -0000	1.39
+++ webfm.module	13 Oct 2009 23:45:53 -0000
@@ -3,12 +3,12 @@
 
 /**
  * @file
- * This module implements a user accessible heirarchical file system located
+ * This module - the Web File Manager(webfm)  Module - implements a user accessible heirarchical file system located
  * in a subdirectory of the site file system path.
  */
 
 $modulepath = drupal_get_path('module', 'webfm');
-require_once "./" . $modulepath . "/webfm_file.inc";
+require_once DRUPAL_ROOT . "/" . $modulepath . "/webfm_file.inc";
 
 define('WEBFM_FLUSH', -1);
 
@@ -32,7 +32,7 @@
 define('WEBFM_DATE_FORMAT_MONTH', 2);
 
 /**
- * Implementation of hook_help().
+ * Implement hook_help().
  */
 function webfm_help($path, $args) {
   switch ($path) {
@@ -120,61 +120,57 @@
 }
 
 /**
- * Implementation of hook_link().
+ * Implement hook_node_type_delete().
+ * 
+ * @param object $info The node type object which is being deleted.
+ * @return void
  */
-function webfm_link($type, $node = NULL, $teaser = FALSE) {
-  $links = array();
-
-  // Display a link with the number of attachments
-  if ($teaser && $type == 'node' && isset($node->webfm_files) && user_access('view webfm attachments')) {
-    if($num_files = count($node->webfm_files)) {
-    $links['webfm_attachments'] = array(
-      'title' => format_plural($num_files, '1 attachment', '@count attachments'),
-      'href' => "node/$node->nid",
-      'attributes' => array('title' => t('Read full article to view attachments.')),
-      'fragment' => 'attachments');
-    }
-  }
-  return $links;
+function webfm_node_type_delete($info) {
+  variable_del('webfm_attach_'. $info->type);
 }
 
 /**
- * Implementation of hook_node_type().
+ * Implement hook_permission().
+ * 
+ * @since 11. Oct. 2009
  */
-function webfm_node_type($op, $info) {
-  switch ($op) {
-    case 'delete':
-      variable_del('webfm_attach_'. $info->type);
-      break;
-  }
-}
+function webfm_permission() {
+	return array(
+	    'administer webfm' => array(
+                'title' => t('Administer Web File Manager'),
+                'description' => t('Administrative access to Web File Manager Settings.'),
+                ),   
+			'access webfm' => array(
+        			  'title' => t('Access the Web File Manager'),
+                'description' => t('Access and Use the Web File Manager'),
+                ),
+       'view webfm attachments' => array(
+        			  'title' => t('Download Web File Manager Attachments'),
+                'description' => t('Download and View Attachements made with the Web File Manager'),
+                ),
+                );
 
-/**
- * Implementation of hook_perm().
- */
-function webfm_perm() {
-  return array('access webfm', 'view webfm attachments', 'administer webfm', 'webfm upload');
 }
 
 /**
- * Implementation of hook_menu().
+ * Implement hook_menu().
  */
 function webfm_menu() {
   $items = array();
 
-  $items['webfm'] = array(
+  $items['admin/content/webfm'] = array(
     'title' => 'Web File Manager',
     'page callback' => 'webfm_main',
     'access callback' => 'user_access',
     'access arguments' =>  array('access webfm'),
-    'type' => MENU_NORMAL_ITEM,
+    'type' => MENU_LOCAL_TASK,
   );
-  $items['admin/settings/webfm'] = array(
+  
+  $items['admin/config/media/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'),
+    'page callback' => 'webfm_admin_settings',
     'access arguments' => array('administer webfm'),
     'type' => MENU_NORMAL_ITEM,
   );
@@ -209,25 +205,39 @@
 }
 
 /**
- * Implementation of hook_block().
- */
-function webfm_block($op = 'list', $delta = 0) {
-  if ($op == 'list') {
-    $blocks[0]['info'] = t('WebFM File Attachments');
-    return $blocks;
+ * Implement hook_block_info().
+ * 
+ * @return array
+ */
+function webfm_block_info() {
+  $blocks['webfm_main']['info'] = t('WebFM File Attachments');
+  return $blocks;
+}
 
+/**
+ * Implement hook_block_view().
+ * 
+ * @param string $delta Which block to return.
+ * @return array
+ */
+function webfm_block_view($delta = '') {
+  $block = array();
+  
+  if (user_access('access content') && user_access('view webfm attachments')) {
+    switch($delta) {
+      case 'webfm_main':
+        $block['content'] = webfm_attach_box();
+        $block['subject'] = t('Attachments');
+        break;
+    }
   }
-  else if ($op == 'view' &&
-           user_access('access content') &&
-           user_access('view webfm attachments')) {
-    $block['content'] = webfm_attach_box();
-    $block['subject'] = t('Attachments');
-    return $block;
-  }
+  
+  return $block;
 }
 
+
 /**
- * Implementation of hook_cron().
+ * Implement hook_cron().
  */
 function webfm_cron() {
   //cleanup any corrupted file records that have no physical files
@@ -235,117 +245,137 @@
   //          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']);
+    foreach($result as $f) {
+      if(!(is_file($f->fpath))) {
+        _webfm_dbdelete_file_fid($f->fid);
       }
     }
   }
 }
 
 /**
- * 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("wfm_attach_$node->type", 1) == 1 &&
-         user_access('view webfm attachments') &&
-         variable_get('webfm_attach_body', '')) {
-       // 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.
+ * Implement hook_comment_view
+ * 
+ * @param object $comment Comment the action is being performed on.
+ * @return void
+ */
+function webfm_comment_view($comment) {
+  if (variable_get("wfm_attach_$comment->node_type", 1) == 1 && user_access('view webfm attachments') && variable_get('webfm_attach_body', '')) {
+   /*
+    * This documentation is from Drupal 6, may be inaccurate:
+    * 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 'access 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;
+/**
+ * Implement hook_comment_load
+ * 
+ * @param array $comments An array of comment objects indexed by cid.
+ * @return unknown_type
+ */
+function webfm_comment_load($comments) {
+  if (!user_access('view webfm attachments')) return;
+  
+  $files = webfm_get_attachments(array_keys($comments), 'cid');
+  
+  foreach($allfiles as $cid => $webfm_files) {
+    $comments[$cid]->webfm_files = $webfm_files;
+  }
+}
 
-    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);
+/**
+ * Implement hook_comment_insert
+ * 
+ * @param object $comment
+ * @return void
+ */
+function webfm_comment_insert($comment) {
+  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++, $comment->cid);
       }
-      break;
+    }
+  }
+}
 
-    case 'delete':
-      webfm_dbdelete_attachments($cid, 'cid');
-      break;
+/**
+ * Implement hook_comment_update
+ * 
+ * @param object $comment
+ * @return void
+ */
+function webfm_comment_update($comment) {
+  if (user_access('access webfm') && array_key_exists('attachlist', $_POST)) {
+    $files = explode(',', $_POST['attachlist']);
+    webfm_dbupdate_attach(0, $files, $comment->cid);
   }
 }
 
 /**
- * Implementation of hook_nodeapi().
+ * Implement hook_comment_delete
+ * 
+ * @param object $comment Comment the action is being performed on.
+ * @return void
  */
-function webfm_nodeapi(&$node, $op, $teaser) {
-  global $user, $base_url, $base_path;
+function webfm_comment_delete($comment) {
+  webfm_dbdelete_attachments($comment->cid, 'cid');
+}
+ 
+/**
+ * Implement hook_node_load
+ * @link http://drupal.org/update/modules/6/7#remove_op
+ * @link http://api.drupal.org/api/function/hook_node_load/7
+ */
+function webfm_node_load($nodes, $types) {
+  if(!user_access('view webfm attachments')) return;
+  
+  foreach($nodes as $node) {
+    if(variable_get("wfm_attach_$node->type", 0) == 1) {
+      $nodes[$node->nid]->webfm_files =  webfm_get_attachments($node->nid);
+    }
+  } 
+}
 
-  switch ($op) {
-    case 'load':
-      if((variable_get("wfm_attach_$node->type", 1) == 1) &&
-          user_access('view webfm attachments')) {
-        $output['webfm_files'] = webfm_get_attachments($node->nid);
-        return $output;
-      }
-      break;
+/**
+ * Implement hook_node_view
+ * @link http://api.drupal.org/api/function/hook_node_view/7
+ * 
+ * @param object $node The node the action is being performed on.
+ * @param string $build_mode The $build_mode parameter from node_build().
+ * @return void
+ */
+function webfm_node_view($node,$build_mode) {
 
-    case 'view':
-      // Add the attachments list to node body if configured to appear in body.
+    
+    // Add the attachments list to node body if configured to appear in body.
       if(variable_get('webfm_attach_body', '')) {
         // We could be viewing or previewing this node.
         // Loading a node defines $node->webfm_files, possibly as empty list,
@@ -360,84 +390,122 @@
         // 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("wfm_attach_$node->type", 1) == 1)
-            && user_access('view webfm attachments')) {
+        if (!user_access('access webfm') && (variable_get("wfm_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) {
+        if (isset($node->webfm_files) && is_array($node->webfm_files)) {
+          if (count($node->webfm_files) && $build_mode == 'full') {
             $show_files = $node->webfm_files;
           }
         }
-	      // We must check for view permissions in a preview, but wfm_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) {
-        $groups = og_all_groups_options();
-        if ($groups[$node->nid]) {
-          // 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);
-        }
+      // We must check for view permissions in a preview, but wfm_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)) {   
+        drupal_add_css(drupal_get_path('module', 'webfm').'/css/webfm.css');
+        
+        $node->content['webfm_attachments'] = array(
+          '#value' => theme('webfm_attachments', $show_files),
+          '#weight' => module_exists('content') ? content_extra_field_weight($node->type, 'webfm_attachments') : 10,
+        );
+        
+        $node->content['links']['webfm']['webfm_attachments'] = array(
+          'title' => format_plural(count($show_files), '1 attachment', '@count attachments'),
+          'href' => "node/$node->nid",
+          'attributes' => array('title' => t('Read full article to view attachments.')),
+          'fragment' => 'attachments,'
+        );  
       }
-      break;
+}
+
+/**
+ * Implement hook_node_validate
+ * @link http://api.drupal.org/api/function/hook_node_validate/7
+ * 
+ * @param object $node The node the action is being performed on
+ * @param array $form The $form parameter from node_validate()
+ * @return void
+ */
+function webfm_node_validate($node,$form) {
+  $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);
+}
 
-    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')) {
-        $files = explode(',', $_POST['attachlist']);
-        webfm_dbupdate_attach($node->nid, $files);
+/**
+ * Implement hook_node_insert
+ * @link http://api.drupal.org/api/function/hook_node_insert/7
+ * @todo Organic Groups part must be reworked
+ * 
+ * @param object $node The node the action is being performed on.
+ * @return void
+ */
+function webfm_node_insert($node) {
+  // 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++);
       }
-      break;
+    }
+  }
+  /*if (module_exists('og') && variable_get('webfm_og_auto', 0) == 1) {
+    $groups = og_all_groups_options();
+    if ($groups[$node->nid]) {
+      // 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;
+  if(!file_prepare_directory($group_root_dir,FILE_CREATE_DIRECTORY)) form_set_error('root_dir_group_'.$node->nid, t('Could not create directory %directoryname.',array('%directoryname' => $group_root_dir)));
+  
+      variable_set('root_dir_group_'. $node->nid, $group_directory);
+    }
+  }*/
+}
 
-    case 'delete':
-      webfm_dbdelete_attachments($node->nid);
-      break;
+/**
+ * Implement hook_node_update
+ * @link http://api.drupal.org/api/function/hook_node_update/7
+ * 
+ * @param object $node The node the action is being performed on.
+ * @return void
+ */
+function webfm_node_update($node) {
+  // 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);
   }
 }
 
+/**
+ * Implement hook_node_delete
+ * @link http://api.drupal.org/api/function/hook_node_delete/7
+ * 
+ * @param object $node The node that is being deleted.
+ * @return void
+ */
+function webfm_node_delete($node) {
+  webfm_dbdelete_attachments($node->nid);
+}
+
+
  /**
- * Implementation of hook_content_extra_fields().
+ * Implement hook_content_extra_fields().
  */
 function webfm_content_extra_fields($type) {
   $extras['webfm_attachments'] = array(
@@ -450,7 +518,8 @@
 
 
 /**
- * Implementation of hook_form_alter().
+ * Implement hook_form_alter().
+ * @todo What about this: http://drupal.org/node/161301
  */
 function webfm_form_alter(&$form, &$form_state, $form_id) {
   global $base_url, $base_path, $user;
@@ -493,6 +562,7 @@
       $form['webfm-attach']['attach'] = array(
         '#type' => 'fieldset',
         '#title' => t('WebFM Attachments'),
+		'#group' => 'additional_settings',
         '#description' => t('Drag attachments to set order.<br />Changes made to the attachments are not permanent until you save this post.'),
         '#collapsible' => TRUE,
         '#collapsed' => TRUE,
@@ -563,7 +633,7 @@
     $help_link = '';
   }
   // Debug link - available only if enabled in settings
-  $debug_link = (drupal_to_js(variable_get('webfm_debug',''))) ? t('[<a href=# id="webfm-debug-link">debug</a>]') : '';
+  $debug_link = (drupal_json_encode(variable_get('webfm_debug',''))) ? t('[<a href=# id="webfm-debug-link">debug</a>]') : '';
 
   return $debug_link.$settings_link.$help_link;
 }
@@ -631,9 +701,9 @@
 }
 
 /**
- * Implementation of hook_theme
+ * Implement hook_theme
  */
-function webfm_theme() {
+function webfm_theme($existing, $type, $theme, $path) {
   return array(
     'webfm_browser' => array(
       'arguments' => array('links' => NULL, 'upload' => NULL),
@@ -716,7 +786,14 @@
   }
   return $icon;
 }
-
+/**
+ * @todo What is this?
+ * 
+ * @param unknown_type $rid
+ * @param unknown_type $name
+ * @param unknown_type $op
+ * @return unknown_type
+ */
 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']);{
@@ -741,7 +818,8 @@
  * maximum dimensions allowed.
  */
 function _webfm_image(&$file) {
-  $info = image_get_info($file->filepath);
+	$filepath = drupal_realpath($file->uri);
+  $info = image_get_info($filepath);
 
   if($info) {
     $res = variable_get('webfm_max_resolution', 0);
@@ -749,11 +827,11 @@
       list($width, $height) = explode('x', 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)) {
+        if(image_get_toolkit() && image_scale($filepath, $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);
+          $info = image_get_info($filepath);
           $file->filesize = $info['file_size'];
         } else {
           drupal_set_message(t('The image is too large.'));
@@ -778,7 +856,8 @@
     // Save new file uploads to tmp dir.
     if(($file = file_save_upload('webfm_upload')) != FALSE) {
       // Scale image uploads.
-      _webfm_image($file);
+      dfb($file); // DEBUG !
+
       $err_arr = array();
       if(webfm_upload_validate($file, $err_arr) === TRUE) {
         // file has been put in temp and we have a valid file object
@@ -840,7 +919,7 @@
     $json_data['html'] = webfm_reload_upload('webfm/upload');
   if($fid)
     $json_data['fid'] = $fid;
-  print drupal_to_js(array('status' => TRUE, 'data' => $json_data));
+  print drupal_json_encode(array('status' => TRUE, 'data' => $json_data));
   exit();
 }
 
@@ -905,7 +984,7 @@
                   unset($_SESSION['tree_'.$current]);
                   $trees[$key] = webfm_tree($root_dir, $current);
                 } else {
-                  $err .= ' '.$sub_root_path.t(' root dir not found.');
+                  $err .= ' '.t('Root directory(%directoryname) not found.',array('%directoryname' => $sub_root_path));
                 }
               } else {
                 $err .= t('Root directory not set for @role role ', array('@role' => $webfm_access_roles[$key]));
@@ -1052,7 +1131,7 @@
                     $ret = FALSE;
                   }
                 } else if(file_exists($source)) {
-                  $error = $source.t(' could not be deleted');
+                  $error = t('%filename could not be deleted', array('%filename' => $source));
                   $ret = FALSE;
                 }
                 webfm_json(array('status' => $ret, 'data' => $error));
@@ -1061,9 +1140,9 @@
               }
             }
           }
-          webfm_json(array('status' => FALSE, 'data' => t('permission denied')));
+          webfm_json(array('status' => FALSE, 'data' => t('Permission denied.')));
         } else {
-          webfm_json(array('status' => FALSE, 'data' => t('insufficient params')));
+          webfm_json(array('status' => FALSE, 'data' => t('Missing a parameter.')));
         }
         exit();
         break;
@@ -1087,10 +1166,10 @@
             if($ret)
               unset($_SESSION['tree_'.$webfm_root_path]);
           } else {
-            webfm_json(array('status' => FALSE, 'data' => t('insufficient params')));
+            webfm_json(array('status' => FALSE, 'data' => t('Missing a parameter.')));
           }
         } else {
-          webfm_json(array('status' => FALSE, 'data' => t('permission denied')));
+          webfm_json(array('status' => FALSE, 'data' => t('Permission denied.')));
         }
         exit();
         break;
@@ -1102,7 +1181,7 @@
           $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')));
+            webfm_json(array('status' => FALSE, 'data' => t('Permission denied.')));
             exit();
             break;
           }
@@ -1113,13 +1192,13 @@
               $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')));
+              webfm_json(array('status' => FALSE, 'data' => t('Illegal destination path.')));
             }
           } else {
-            webfm_json(array('status' => FALSE, 'data' => t('move operation not permitted')));
+            webfm_json(array('status' => FALSE, 'data' => t('Move operation not permitted.')));
           }
         } else {
-          webfm_json(array('status' => FALSE, 'data' => t('insufficient params')));
+          webfm_json(array('status' => FALSE, 'data' => t('Missing a parameter.')));
         }
         exit();
         break;
@@ -1137,10 +1216,10 @@
             $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')));
+            webfm_json(array('status' => FALSE, 'data' => t('Illegal name.')));
           }
         } else {
-          webfm_json(array('status' => FALSE, 'data' => t('insufficient params')));
+          webfm_json(array('status' => FALSE, 'data' => t('Missing a parameter.')));
         }
         exit();
         break;
@@ -1157,7 +1236,7 @@
             webfm_json(array('files' => $search->get_files()));
           }
         } else {
-          webfm_json(array('status' => FALSE, 'data' => t('insufficient params')));
+          webfm_json(array('status' => FALSE, 'data' => t('Missing a parameter.')));
         }
         exit();
         break;
@@ -1184,8 +1263,8 @@
                 }
               }
               if($file->uid > 0) {
-                $query = 'SELECT name FROM {users} WHERE uid = %d';
-                $meta['un'] = db_result(db_query($query, $file->uid));
+                $result = user_load($file->uid);
+                $meta['un'] = $result->name;
               } else {
                 $meta['un'] = t('anonymous');
               }
@@ -1210,13 +1289,13 @@
               }
               webfm_json(array('status' => TRUE, 'data' => $meta));
             } else {
-              webfm_json(array('status' => FALSE, 'data' => t('permission denied')));
+              webfm_json(array('status' => FALSE, 'data' => t('Permission denied.')));
             }
           } else {
-            webfm_json(array('status' => FALSE, 'data' => t('file record not found')));
+            webfm_json(array('status' => FALSE, 'data' => t('File record not found.')));
           }
         } else {
-          webfm_json(array('status' => FALSE, 'data' => t('insufficient params')));
+          webfm_json(array('status' => FALSE, 'data' => t('Missing a parameter.')));
         }
         exit();
         break;
@@ -1230,7 +1309,7 @@
           $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')));
+          webfm_json(array('status' => FALSE, 'data' => t('Missing a parameter.')));
         }
         exit();
         break;
@@ -1250,13 +1329,13 @@
               $perm['p'] = $file->perm;
               webfm_json(array('status' => TRUE, 'data' => $perm));
             } else {
-              webfm_json(array('status' => FALSE, 'data' => t('permission denied')));
+              webfm_json(array('status' => FALSE, 'data' => t('Permission denied.')));
             }
           } else {
-            webfm_json(array('status' => FALSE, 'data' => t('file record not found')));
+            webfm_json(array('status' => FALSE, 'data' => t('File record not found,')));
           }
         } else {
-          webfm_json(array('status' => FALSE, 'data' => t('insufficient params')));
+          webfm_json(array('status' => FALSE, 'data' => t('Missing a parameter.')));
         }
         exit();
         break;
@@ -1277,19 +1356,19 @@
               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');
+                  $msg = t('Permissions saved.');
                   $status = TRUE;
                 } else {
-                  $msg = t('webfm_dbupdate_file() fail');
+                  $msg = t('Could not updated Database. (webfm_dbupdate_file() fail)');
                 }
               } else {
-                $msg = t('invalid permission');
+                $msg = t('Invalid permission.');
               }
             } else {
-              $msg = t('permission denied');
+              $msg = t('Permission denied.');
             }
           } else {
-            $msg = t('file record not found');
+            $msg = t('File record not found.');
           }
         } else {
           $msg = t('insufficient params');
@@ -1340,7 +1419,7 @@
             }
           }
         } else {
-          webfm_json(array('status' => FALSE, 'data' => t('insufficient params')));
+          webfm_json(array('status' => FALSE, 'data' => t('Missing a parameter.')));
         }
         exit();
         break;
@@ -1360,16 +1439,16 @@
               if($file->result != FALSE) {
                 webfm_json(array('status' => TRUE, 'data' => $file, 'admin' => 'attach'));
               } else {
-                webfm_json(array('status' => FALSE, 'data' => t('file ').$fid.t(' path not found')));
+                webfm_json(array('status' => FALSE, 'data' => t('Filepath for file (%numeric_file_id) not found.',array('%numeric_file_id',$fid))));
               }
             } else {
-              webfm_json(array('status' => FALSE, 'data' => t('invalid permission')));
+              webfm_json(array('status' => FALSE, 'data' => t('Invalid permission.')));
             }
           } else {
-            webfm_json(array('status' => FALSE, 'data' => t('file ').$fid.t(' record not found')));
+            webfm_json(array('status' => FALSE, 'data' => t('Record for file (%numeric_file_id) not found.',array('%numeric_file_id',$fid))));
           }
         } else {
-          webfm_json(array('status' => FALSE, 'data' => t('insufficient params')));
+          webfm_json(array('status' => FALSE, 'data' => t('Missing a parameter.')));
         }
         exit();
         break;
@@ -1413,10 +1492,10 @@
                 break;
             }
           } else {
-            webfm_json(array('status' => FALSE, 'data' => t('insufficient params')));
+            webfm_json(array('status' => FALSE, 'data' => t('Missing a parameter.')));
           }
         } else {
-          webfm_json(array('status' => FALSE, 'data' => t('permission denied')));
+          webfm_json(array('status' => FALSE, 'data' => t('Permission denied.')));
         }
         exit();
         break;
@@ -1427,15 +1506,15 @@
           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')));
+              webfm_json(array('status' => $ret, 'data' => t('Sucessfully deleted file from database.')));
             } else {
-              webfm_json(array('status' => FALSE, 'data' => t('file not in db')));
+              webfm_json(array('status' => FALSE, 'data' => t('Could not find file in database.')));
             }
           } else {
-            webfm_json(array('status' => FALSE, 'data' => t('insufficient params')));
+            webfm_json(array('status' => FALSE, 'data' => t('Missing a parameter.')));
           }
         } else {
-          webfm_json(array('status' => FALSE, 'data' => t('permission denied')));
+          webfm_json(array('status' => FALSE, 'data' => t('Permission denied.')));
         }
         exit();
         break;
@@ -1451,10 +1530,10 @@
             $ver_data['msg'] = $msg;
             webfm_json(array('status' => $ret, 'data' => $ver_data));
           } else {
-            webfm_json(array('status' => FALSE, 'data' => t('invalid file name')));
+            webfm_json(array('status' => FALSE, 'data' => t('Invalid file name.')));
           }
         } else {
-          webfm_json(array('status' => FALSE, 'data' => t('insufficient params')));
+          webfm_json(array('status' => FALSE, 'data' => t('Missing a parameter.')));
         }
         // clear uploaded file
         unset($_SESSION['temp_upload']);
@@ -1462,7 +1541,7 @@
         break;
 
       default:
-        webfm_json(array('status' => FALSE, 'data' => t('illegal operation')));
+        webfm_json(array('status' => FALSE, 'data' => t('Illegal operation.')));
         exit();
         break;
     }
@@ -1521,8 +1600,16 @@
           //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);
+          $row = db_update('webfm_file')
+                ->fields(array(
+                				'fsize'        => $_SESSION['temp_upload']->filesize,
+                				'fcreatedate'  => $time,
+                                'fversion'     => $record->fversion + 1,
+                                'uid'          => $user->uid,
+                ))
+                ->condition('fid',$record->fid)
+                ->execute();
+
           if($row === FALSE){
             // Update of existing record failed
             // Delete new file and restore name of original file
@@ -1567,8 +1654,16 @@
           }
           //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);
+          $row = db_update('webfm_file')
+                ->fields(array(
+                				'fsize'        => $_SESSION['temp_upload']->filesize,
+                				'fcreatedate'  => $time,
+                                'fversion'     => $record->fversion + 1,
+                                'uid'          => $user->uid,
+                ))
+                ->condition('fid',$record->fid)
+                ->execute();
+
           if($row === FALSE){
             $ret = FALSE;
             $msg = t('Replace-Delete update fail');
@@ -1587,7 +1682,7 @@
         }
       } else {
         $ret = FALSE;
-        $msg = t('file_move fail');
+        $msg = t('Could not move file. (file_move failed)');
         @rename($temp_path, $path);
       }
       break;
@@ -1614,7 +1709,7 @@
       return FALSE;
     }
   } else {
-    $msg = t('file_move to ').$_SESSION['temp_upload']->dest.t(' failed');
+    $msg = t('Could not move file to %destination_directory.', array('%destination_directory' => $_SESSION['temp_upload']->dest));
     return FALSE;
   }
 }
@@ -1630,15 +1725,17 @@
  */
 function webfm_json($var = NULL) {
   // We are returning JavaScript, so tell the browser.
-  drupal_set_header('Content-Type: text/javascript; charset=utf-8');
-
+  drupal_add_http_header('Content-Type','text/javascript');
+  drupal_add_http_header('charset','utf-8');
   if (isset($var)) {
-    echo drupal_to_js($var);
+    echo drupal_json_encode($var);
   }
 }
 
 /**
  * Main file manager function
+ * 
+ * @return array
  */
 function webfm_main () {
   global $base_url, $base_path, $user;
@@ -1656,18 +1753,19 @@
   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 = array();
+  if($user->uid == 1  OR user_access('administer webfm') OR user_access('webfm upload')) {
     $upload = drupal_get_form('webfm_upload_fieldset');
   }
 
-  return theme('webfm_browser', $links, $upload);
+  return $upload;
 }
 
+
 function webfm_upload_fieldset() {
   $form = array();
+  $form['#prefix'] = '<div id="webfm">';
+  $form['#suffix'] = '</div>';
   $form['webfm_uploads'] = array(
     '#type' => 'fieldset',
     '#title' => t('File Upload'),
@@ -1700,7 +1798,7 @@
   $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'));
+  $form['wfmatt-url'] = array('#type' => 'hidden', '#value' => url($upload_url, array('absolute' => TRUE)), '#attributes' => array('class' => array('webfmupload')));
 
   return $form;
 }
@@ -1732,8 +1830,8 @@
  * 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) .';} function getBasePath(){return '. drupal_to_js($base_path) .';} function getWebfmIconDir(){return '. drupal_to_js($base_url .'/'. variable_get('webfm_icon_dir', drupal_get_path('module', 'webfm') .'/image/icon')) .';} function getWebfmCleanUrl(){return '.drupal_to_js($clean_url).'; }function getWebfmIETreeOffset(){return '.drupal_to_js(variable_get('webfm_ie_dd_tree_offset', '')).';}function getWebfmIEListOffset(){return '.drupal_to_js(variable_get('webfm_ie_dd_list_offset', '')).';} function getWebfmUid(){return '.drupal_to_js($uid).';} function getWebfmDateFormat(){return '.drupal_to_js(variable_get('webfm_date_format', WEBFM_DATE_FORMAT_DAY)).';} function getWebfmMetaName(){return '.drupal_to_js(variable_get('webfm_display_title', '')).';} function getWebfmOwnerColumn(){return '.drupal_to_js(variable_get('webfm_display_owner', '')).';}' ;
-  drupal_add_js($js, 'inline');
+  $js = 'function getBaseUrl(){return '. drupal_json_encode($base_url) .';} function getBasePath(){return '. drupal_json_encode($base_path) .';} function getWebfmIconDir(){return '. drupal_json_encode($base_url .'/'. variable_get('webfm_icon_dir', drupal_get_path('module', 'webfm') .'/image/icon')) .';} function getWebfmCleanUrl(){return '.drupal_json_encode($clean_url).'; }function getWebfmIETreeOffset(){return '.drupal_json_encode(variable_get('webfm_ie_dd_tree_offset', '')).';}function getWebfmIEListOffset(){return '.drupal_json_encode(variable_get('webfm_ie_dd_list_offset', '')).';} function getWebfmUid(){return '.drupal_json_encode($uid).';} function getWebfmDateFormat(){return '.drupal_json_encode(variable_get('webfm_date_format', WEBFM_DATE_FORMAT_DAY)).';} function getWebfmMetaName(){return '.drupal_json_encode(variable_get('webfm_display_title', '')).';} function getWebfmOwnerColumn(){return '.drupal_json_encode(variable_get('webfm_display_owner', '')).';}' ;
+  drupal_add_js($js, array('type' => 'inline'));
 }
 
 /**
@@ -1753,55 +1851,51 @@
  * Helper function to get root path of webfm
  */
 function webfm_get_root_path () {
-  static $webfm_root_path;
+  $webfm_root_path = &drupal_static(__FUNCTION__,variable_get('webfm_root_dir'));
+
+  if(!empty($webfm_root_path)) $webfm_root_path = '/'.$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
+ * 
+ * @param boolean $reset If true: reset role root directories array and refresh from database
+ * @return array
  */
-function webfm_get_access_roles($flush = FALSE) {
-  static $webfm_access_roles = array();
-
-  if($flush)
-    $webfm_access_roles = array();
+function webfm_get_access_roles($reset = FALSE) {
+  $webfm_access_roles = &drupal_static(__FUNCTION__,user_roles(0, 'access webfm'));
 
-  // 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');
+  if ($reset) {
+    drupal_static_reset(__FUNCTION__);
   }
+  
   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();
+/**
+ * 
+ * @param boolean $reset If true: reset role root directories array and refresh from database ({@see webfm_get_access_roles})
+ * @return array
+ */
+function webfm_get_root_dirs($reset = FALSE) {
+  global $user;  
+  $webfm_roots = &drupal_static(__FUNCTION__,array());
+
+  $webfm_access_roles = webfm_get_access_roles($reset);
+  // $webfm_roots = array(); //I don't know what this line does: If we use static it doesn't make any sens
+  
   foreach($user->roles as $rid => $role) {
-    if(array_key_exists($rid, $webfm_access_roles)) {
-      // Roles with 'access webfm' perm that user possesses
+    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)) {
+      
+      if (!empty($path) && !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', '');
@@ -1813,34 +1907,35 @@
   return $webfm_roots;
 }
 
- /**
+/**
  * Helper function to get array of group root directories for a user
+ * 
+ * @param boolean $reset true: Get a fresh of copy of the group root dirs from database.
+ * @return array
  */
-function webfm_get_group_root_dirs($flush = FALSE) {
+function webfm_get_group_root_dirs($reset = FALSE) {
   global $user;
-  static $webfm_roots = array();
-  static $webfm_access_groups = array();
+  $cache = &drupal_static(__FUNCTION__,array('webfm_roots' => array(), 'webfm_access_groups' => array()));
+  
   //add per group directories
-  if($flush) {
-    $webfm_access_groups = array();
+  if($reset) {
+    drupal_static_reset(__FUNCTION__);
   }
   // Roles with 'access webfm' perm
-  if(!count($webfm_access_groups)) {
-    $webfm_roots = array();
+  if(!count($cache['webfm_roots']['webfm_access_groups'])) {
+    $cache['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;
+        if(!empty($path) && !in_array($path, $cache['webfm_roots'])) {
+            $cache['webfm_roots'][$key] = '/'.$path;
           }
         }
       }
     }
-  }
-  return $webfm_roots;
+
+  return $cache['webfm_roots'];
 }
 
 /**
@@ -1918,7 +2013,7 @@
  * Helper function to get date format string
  */
 function webfm_get_date_format() {
-  static $dateformat;
+  $dateformat = &drupal_static(__FUNCTION__);
 
   if(!$dateformat) {
     $date_format_type = (variable_get('webfm_date_format', WEBFM_DATE_FORMAT_DAY));
@@ -2034,8 +2129,8 @@
                 $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));
+                $result = user_load($_file->uid);
+                $fd->un = $result->name;
               } else {
                 $fd->un = t('anonymous');
               }
@@ -2137,20 +2232,47 @@
   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) {
+/**
+ * Load attachements from database
+ * 
+ * @param int|array $ids Ids for which node or comment to get attachments
+ * @param string $selector nid for node Id|cid for comment id
+ * @return array of webfm_fdesc-objects indexed by passed ids
+ */
+function webfm_get_attachments($ids = array(), $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(!is_array($ids) and is_numeric($ids) and $ids != 0) {
+    $ids = array($ids);
+  }
+  
+  if (count($ids) == 0 OR ($selector != 'nid' AND $selector != 'cid')) {
     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_records = db_select('webfm_file','f');
+  $webfm_attach_table_alias = $file_records->join('webfm_attach','a','f.fid = a.fid');
+  
+  $condition = db_or();
+  foreach($ids as $id) {
+    if($id != 0) {
+      $condition = $condition->condition($webfm_attach_table_alias.'.'.$selector,$id);
+    }
+  }
+  
+  
+  $file_records->condition($condition)
+               ->orderBy($webfm_attach_table_alias.'.weight')
+               ->execute();
+
+  foreach($file_records as $file_record) {
     $_file = new webfm_fdesc($file_record);
-    if($_file->result == TRUE) {
-      $files[] = $_file;
+    if ($_file->result == TRUE) {
+      $files[$file_record->$selector] = $_file;
     }
   }
   return $files;
@@ -2166,8 +2288,11 @@
 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_records = db_select('webfm_file');
+  $file_records->condition('fid',$fids_arr,'IN');
+  $file_records->execute();
+
+  foreach($file_records as $file_record) {
     $_file = new webfm_fdesc($file_record);
     if($_file->result == TRUE) {
       $files[] = $_file;
@@ -2204,8 +2329,8 @@
 
               $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));
+                $result = user_load($file->uid);
+                $this->un =$result->name;
               } else {
                 $this->un = t('anonymous');
               }
@@ -2361,19 +2486,19 @@
       $match = TRUE;
     } else if($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);
+      $query = 'SELECT nid,cid FROM {webfm_attach} WHERE fid = :fid';
+      $result = db_query($query, array(':fid'=>$f->fid));
       if($result !== FALSE) {
-        while ($dbfid = db_fetch_array($result)) {
-          if ($dbfid['cid'] != 0 ) {
+        foreach($result as $dbfid) {
+          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;
+            $comment = comment_load($dbfid->cid);
+            $dbfid->nid = $comment->nid;
           }
-          $node = node_load($dbfid['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.
@@ -2388,9 +2513,7 @@
   }
 
   // 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))) {
+  if ($match == FALSE && $webfm_perm == WEBFM_USER && (webfm_file_view_access($f) || webfm_file_mod_access($f)) ) {
     $match = TRUE;
   }
 
@@ -2489,38 +2612,21 @@
   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);
-  //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);
+  $result = db_insert('webfm_file')
+            ->fields($metadata)
+            ->execute();
 
   if($result === FALSE){
-    $error = $file->filepath.t(' could not be inserted into db');
+    $error = t('File (%filepath) could not be inserted into database.', 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;
+    $fid = db_query("SELECT fid FROM {webfm_file} WHERE fpath = :fpath", array(':fpath' => $file->filepath))->fetchField();
+    if($fid !== FALSE) {
+      _webfm_file_alias("insert", $metadata, $fid);
+      return $fid;
     } else {
-      $error = $file->filepath.t(' could not be selected from db');
+      $error = t('File (%filepath) could not be selected from database.', array('%filepath' => $file->filepath));
       return FALSE;
     }
   }
@@ -2541,27 +2647,13 @@
     $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);
+  $result = db_update('webfm_file')
+            ->fields($metadata)
+            ->condition('fid',$fid)
+            ->execute();
 
   if($result === FALSE){
-    drupal_set_message(t('webfm_dbupdate_file() err: fid=%fid', array('%fid' => $fid)), 'error');
+    drupal_set_message(t('Could not update metadata for file (%fid).', array('%fid' => $fid)), 'error');
     return FALSE;
   }
   _webfm_file_alias('update', $metadata, $fid);
@@ -2584,7 +2676,7 @@
       $webfmfile = $metadata;
       $webfmfile['fid'] = $fid;
       $pathauto_path = drupal_get_path('module', 'pathauto');
-      require_once("$pathauto_path/pathauto.inc");
+      require_once(DRUPAL_ROOT ."/". $pathauto_path ."/pathauto.inc");
       $alias = pathauto_create_alias('webfm', $op, pathauto_get_placeholders('webfm', $webfmfile), 'webfm_send/'. $webfmfile['fid'], 'webfm');
       break;
   }
@@ -2594,11 +2686,11 @@
  * Reduce number of db queries for role extension whitelist + regex format
  */
 function webfm_get_extensions_regex($rid) {
-  static $role_ext_regex = array();
+  $role_ext_regex = &drupal_static(__FUNCTION__,array());
 
   if($rid == WEBFM_FLUSH) {
     //flush static array
-    $role_ext_regex = array();
+    drupal_static_reset(__FUNCTION__);
     return '';
   }
 
@@ -2653,6 +2745,9 @@
 function webfm_upload_validate($file, &$err_arr){
   global $user;
 
+
+   _webfm_image($file);
+
   if($user->uid == 1)
     return TRUE;
 
@@ -2677,19 +2772,19 @@
   $user_roles = count($user->roles);
   $valid = TRUE;
   if ($error['extension'] == $user_roles) {
-    $err_arr[] = $file->filename.t(' has an invalid extension');
+    $err_arr[] = t('File (%filename) has an invalid extension.', array('%filename' => $file->filename));
     $valid = FALSE;
   }
   if ($error['uploadsize'] == $user_roles) {
-    $err_arr[] = $file->filename.t(' exceeds the maximum filesize of ').format_size($uploadsize);
+    $err_arr[] = t('File (%filename) exceeds the maximum filesize of %filesize.', array('%filename' => $file->filename,'%filesize' => format_size($uploadsize)));
     $valid = FALSE;
   }
   if ($error['usersize'] == $user_roles) {
-    $err_arr[] = $file->filename.t(' exceeds the maximum disk quota of ').format_size($usersize);
+    $err_arr[] = $file->filename.t('File (%filename) exceeds the maximum disk quota of %quota.', array('%filename' => $file->filename,'%quota' => format_size($usersize)));
     $valid = FALSE;
   }
   if (strlen($file->filename) > 255) {
-    $err_arr[] = $file->filename.t(' exceeds the maximum name length');
+    $err_arr[] = t('File (%filename) exceeds the maximum name length.', array('%filename' => substr($file->filename,0,250).'...'));
     $valid = FALSE;
   }
   return $valid ? TRUE : FALSE;
@@ -2702,12 +2797,13 @@
  * @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;
+  $fid = db_query("SELECT fid FROM {webfm_file} WHERE fpath = :fpath", array(':fpath' => $path))->fetchField();
+  if ($fid !== FALSE) {
+    return $fid;
+  }
+  else {
+    return FALSE;
+  }
 }
 
 /**
@@ -2718,35 +2814,23 @@
  * @return row object or FALSE if none was found
  */
 function webfm_get_file_record($fid = '', $path = '') {
-  if(is_numeric($fid)) {
-    $query = "SELECT * FROM {webfm_file} WHERE fid = %d";
-    if(($result = db_query($query, $fid)) !== FALSE) {
-      if($row = db_fetch_object($result)) {
-        return $row;
-      }
-    }
-  } else if(is_string($path)) {
-    $query = "SELECT * FROM {webfm_file} WHERE fpath = '%s'";
-    if(($result = db_query($query, $path)) !== FALSE) {
-      if($row = db_fetch_object($result)) {
-        return $row;
-      }
-    }
-  }
-  return FALSE;
+  if (!is_numeric($fid) AND !is_string($path)) return FALSE;
+
+  //SELECT * FROM {webfm_file} WHERE fid = $fid OR fpath = $path
+   return db_query("SELECT * FROM  {webfm_file} WHERE fid = :fid OR fpath = :fpath",array(':fid'=>$fid,':fpath'=>$path))->fetchObject();
 }
 
 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));
-  }
+  $metadata_key_arr = &drupal_static(__FUNCTION__, 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          ||
@@ -2767,20 +2851,19 @@
               $uid_val = strval($value);
               if(is_numeric($uid_val) && (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;
+                $result = user_load($uid_val);
+                if($result !== FALSE) {
+                  $metadata[$metadata_key_arr[$key]['field']] = $result->uid;
                 } else {
-                  $err = t('user not found');
+                  $err = t('User not found.');
                   return FALSE;
                 }
               } else {
-                $err = t('invalid data');
+                $err = t('Invalid data.');
                 return FALSE;
               }
             } else {
-              $err = t('permission denied');
+              $err = t('Permission denied.');
               return FALSE;
             }
           } else {
@@ -2791,22 +2874,22 @@
       if(count($metadata)) {
         $ret = webfm_dbupdate_file($fid, '', $metadata);
         if($ret) {
-          $err = t('metadata updated');
+          $err = t('Metadata updated.');
           return TRUE;
         } else {
-          $err = t('metadata update fail');
+          $err = t('Metadata updated failed.');
         }
       } else {
         if(!strlen($err)) {
-          $err = t('no update required');
+          $err = t('No update required.');
         }
         return TRUE;
       }
     } else {
-      $err = t('permission denied');
+      $err = t('Permission denied.');
     }
   } else {
-    $err = t('file not found');
+    $err = t('File not found.');
   }
   return FALSE;
 }
@@ -2837,8 +2920,10 @@
  * @return bool
  */
 function _webfm_dbdelete_file_fid($fid){
-  $query = 'DELETE FROM {webfm_file} WHERE fid = %d';
-  $result = db_query($query, $fid);
+
+  $result = db_delete('webfm_file')
+            ->condition('fid', $fid)
+            ->execute();
   if($result === FALSE){
     drupal_set_message(t('Query Failed: Could not delete file %fid .', array('%fid' => $fid), 'error'));
     return FALSE;
@@ -2866,8 +2951,10 @@
 
   $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 %s = %d";
-    if ($result = db_query($query, $selector, $id)) {
+    $result = db_delete('webfm_attach')
+              ->condition($selector, $id)
+              ->execute();
+    if ($result) {
       foreach($fids as $fid){
         if($fid)
           webfm_dbinsert_attach($nid, $fid, $i++, $cid);
@@ -2896,13 +2983,13 @@
     $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);
+  $query = "SELECT fid FROM {webfm_attach} WHERE :selector = :id ORDER BY weight";
+  $result = db_query($query, array(':selector' => $selector, ':id' => $id));
 
   $match = TRUE;
   $i = 0;
-  while ($dbfid = db_fetch_array($result)) {
-    if($dbfid['fid'] != $fids[$i]) {
+  foreach($result as $dbfid) {
+    if($dbfid->fid != $fids[$i]) {
       $match = FALSE;
       break;
     }
@@ -2936,17 +3023,28 @@
     $id = $cid;
     $nid = 0;
   }
-  $query = "SELECT * FROM {webfm_attach} WHERE %s = %d AND fid = %d";
-  $result = db_query($query, $selector, $id, $fid);
-  $exist = FALSE;
-  while ($exist = db_fetch_object($result)){
-    drupal_set_message(t('File is already attached to this %t.', array('%t' => $type)));
-   return FALSE;
+
+  $result = db_select('webfm_attach')
+            ->condition($selector,$id)
+            ->condition('fid',$fid)
+            ->addExpression('COUNT(fid)', 'fid_count')
+            ->execute();
+
+  if ($result->fid_count > 0) {
+    drupal_set_message(t('File is already attached to this %contentype.', array('%contentype' => $type)));
+    return FALSE;
   }
-  if ($exist === FALSE) {
+  else {
     //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);
+    $result = db_insert('webfm_attach')
+              ->fields(array(
+                'nid'     => $nid,
+                'fid'     => $fid,
+                'weight'  => $weight,
+                'cid'     => $cid,
+              ))
+              ->execute();
+
     if($result === FALSE) {
       drupal_set_message(t('Query Failed:  Could not attach files to %t %n', array('%t' => $type, '%n' => $id)));
       return FALSE;
@@ -2959,21 +3057,15 @@
 /**
  * webfm_dbdelete_attachments - deletes nodes/comments file associations.
  *
- * @param int $id  - Node or comment id.
+ * @param int $id  - Node or comment ids.
  * @param selector - Tell if we handle a node or a comment.
- * @return bool    - TRUE if success - else FALSE
+ * @return void 
  *
  */
 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;
+    db_delete('webfm_attach')
+        ->condition($selector,$id)
+        ->execute();
 }
 
 /**
@@ -2984,10 +3076,12 @@
  * @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) {
+function webfm_dbdelete_attach($nid, $fid) {
+  $result = db_delete('webfm_attach')
+            ->condition('nid',$nid)
+            ->condition('fid',$fid)
+            ->execute();
+  if ($result === FALSE) {
     drupal_set_message(t('Query Failed: Could not detach file %fid from node %nid', array('%fid' => $fid, '%nid'=>$nid)));
     return FALSE;
   }
@@ -3002,8 +3096,9 @@
  * @return bool
  */
 function _webfm_dbdelete_attach_fid($fid){
-  $query = 'DELETE FROM {webfm_attach} WHERE fid = %d';
-  $result = db_query($query, $fid);
+  $result = db_delete('webfm_attach')
+            ->condition('fid',$fid)
+            ->execute();
   if($result === FALSE) {
     return FALSE;
   }
@@ -3023,7 +3118,7 @@
  * Views Module
  */
 if(module_exists('views')){
-  require_once('./'.$modulepath.'/views/webfm_views.inc');
+  require_once(DRUPAL_ROOT .'/'. $modulepath .'/views/webfm_views.inc');
 }
 
 function webfm_views_api() {
@@ -3119,12 +3214,21 @@
  * @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));
+  //$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));
+  $result = db_select("webfm_file","f")
+            ->fields("f",array("fid"));
+
+  $url_alias = $result->leftJoin("url_alias","u","CONCAT('webfm_send/', CAST(f.fid AS CHAR)) = u.src");
+
+   $result->condition('f.uid',0,'>')
+          ->isNull($url_alias.'.src')
+          ->range(0,variable_get('pathauto_max_bulk_update', 50))
+          ->execute();
 
   $count = 0;
   $placeholders = array();
-  while ($fids = db_fetch_object($result)) {
+  foreach($result as $fids) {
     $webfmfile = webfm_get_file_record($fids->fid);
     $placeholders = pathauto_get_placeholders('webfm', $webfmfile);
     $src = 'webfm_send/'. $webfmfile->fid;
@@ -3136,5 +3240,4 @@
   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.'));
-}
-
+}
\ No newline at end of file
Index: webfm.install
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/webfm/webfm.install,v
retrieving revision 1.15
diff -u -r1.15 webfm.install
--- webfm.install	19 Aug 2009 15:35:42 -0000	1.15
+++ webfm.install	13 Oct 2009 23:45:47 -0000
@@ -2,18 +2,16 @@
 // $Id: webfm.install,v 1.15 2009/08/19 15:35:42 robmilne Exp $
 
 /**
- * Implementation of hook_install().
- */
-function webfm_install(){
-  drupal_install_schema('webfm');
-}
+* @file
+* Install, uninstall and schema functions for the Web File Manager (webfm) module.
+*/
+
 
 /**
- * Implementation of hook_uninstall().
+ * Implement hook_uninstall().
  */
 function webfm_uninstall(){
-  drupal_uninstall_schema('webfm');
-    variable_del('webfm_root_dir');
+  variable_del('webfm_root_dir');
   variable_del('webfm_ftp_enable');
   variable_del('webfm_ftp_root_dir');
   variable_del('webfm_icon_dir');
@@ -43,7 +41,7 @@
     }
   }
 
-  $types = node_get_types();
+  $types = node_type_get_types();
   foreach ($types as $type) {
     if ($type->type)
       variable_del('webfm_attach_'.$type->type);
@@ -57,10 +55,11 @@
 }
 
 /**
- * Implementation of hook_schema().
+ * Implement hook_schema().
  */
 function webfm_schema(){
   $schema['webfm_file'] = array(
+    'description' => 'Stores information about the individual files (metadata).',
     'fields' => array(
       'fid' => array('type' => 'serial', 'size' => 'normal', 'unsigned' => TRUE, 'not null' => TRUE),
       'uid' => array('type' => 'int', 'size' => 'normal', 'unsigned' => TRUE, 'not null' => TRUE, 'default' => 0),
@@ -68,7 +67,7 @@
       'fsize' => array('type' => 'int', 'size' => 'normal', 'unsigned' => TRUE, 'not null' => TRUE, 'default' => 0),
       'fmime' => array('type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => ''),
       'ftitle' => array('type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => ''),
-      'fdesc' => array('type' => 'text', 'size' => 'normal', 'not null' => TRUE, 'default' => ''),
+      'fdesc' => array('type' => 'text', 'size' => 'normal', 'not null' => TRUE),
       'fcreatedate' => array('type' => 'int', 'size' => 'normal', 'not null' => TRUE, 'default' => 0),
       'flang' => array('type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => ''),
       'fpublisher' => array('type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => ''),
@@ -81,6 +80,7 @@
   );
 
   $schema['webfm_attach'] = array(
+    'description' => 'Stores the relationship of webfm files to nodes.',
     'fields' => array(
       'nid' => array('type' => 'int', 'size' => 'normal', 'not null' => TRUE, 'default' => 0),
       'fid' => array('type' => 'int', 'size' => 'normal', 'not null' => TRUE, 'default' => 0),
@@ -90,18 +90,4 @@
     'primary key' => array('nid', 'fid', 'cid' ),
   );
   return $schema;
-}
-
-/**
- * Add column for comment id in webfm_attach table.
- */
-function webfm_update_1() {
-  $ret = array();
-  // Add the new column to store a comment id.
-  db_add_field($ret, 'webfm_attach', 'cid', array('type' => 'int', 'not null' => TRUE, 'default' => '0'));
-
-  // Make it a primary key.
-  db_drop_primary_key($ret, 'webfm_attach');
-  db_add_primary_key($ret, 'webfm_attach', array('nid', 'cid', 'fid'));
-  return $ret;
-}
+}
\ No newline at end of file
Index: webfm-browser.tpl.php
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/webfm/webfm-browser.tpl.php,v
retrieving revision 1.1
diff -u -r1.1 webfm-browser.tpl.php
--- webfm-browser.tpl.php	26 Jul 2009 19:50:49 -0000	1.1
+++ webfm-browser.tpl.php	13 Oct 2009 23:45:44 -0000
@@ -2,7 +2,7 @@
 // $Id: webfm-browser.tpl.php,v 1.1 2009/07/26 19:50:49 robmilne Exp $
 
 /**
- * @file webfm_browser.tpl.php
+ * @file webfm-browser.tpl.php
  * Display the webfm browser.
  *
  * Variables:
Index: webfm.info
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/webfm/webfm.info,v
retrieving revision 1.7
diff -u -r1.7 webfm.info
--- webfm.info	8 Apr 2008 06:28:14 -0000	1.7
+++ webfm.info	13 Oct 2009 23:45:47 -0000
@@ -2,4 +2,8 @@
 name = Web File Manager
 description = Hierarchical AJAX file system manager
 package = WebFM
-core = 6.x
\ No newline at end of file
+core = 7.x
+files[] = webfm.admin.inc
+files[] = webfm_file.inc
+files[] = webfm_theme.inc
+files[] = webfm-browser.tpl.php
\ No newline at end of file
Index: webfm_theme.inc
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/webfm/webfm_theme.inc,v
retrieving revision 1.4
diff -u -r1.4 webfm_theme.inc
--- webfm_theme.inc	8 Feb 2009 06:30:30 -0000	1.4
+++ webfm_theme.inc	13 Oct 2009 23:45:57 -0000
@@ -1,5 +1,11 @@
 <?php
 // $Id: webfm_theme.inc,v 1.4 2009/02/08 06:30:30 robmilne Exp $
+
+/**
+ * @file
+ * This file provides a themeing function to webfm.
+ */
+
 /**
  * Displays file attachments in table
  */
@@ -26,14 +32,14 @@
         'data' => l('<img src="'.$icon_path.'" alt="[file]" title="Download '.$filename .'"/> ', 'webfm_send/'.$file->id.'/1',
         array('attributes' => array('title' => 'Download '.$filename,'target' => '_blank'), 'html' => TRUE))
         .l($filename, 'webfm_send/'.$file->id, array('attributes' => array('title' => 'Open '.$filename, 'target' => '_blank')))
-        .$description, 'class' => 'att-title'
+        .$description, 'class' => array('att-title'),
       );
     } else {
       $href = array(
         'data' => l('<img src="'.$icon_path.'" alt="[file]" title="Download '.$filename .'"/> ', 'webfm_send/'.$file->id.'/1',
         array('attributes' => array('title' => 'Download '.$filename), 'html' => TRUE))
         .l($filename, 'webfm_send/'.$file->id, array('attributes' => array('title' => 'Open '.$filename)))
-        .$description, 'class' => 'att-title'
+        .$description, 'class' => array('att-title'),
       );
     }
 
@@ -41,14 +47,14 @@
     array_push($row, $href);
     if($enable_date) {
       $time = $file->fcreatedate ? date(webfm_get_date_format(), $file->fcreatedate) : date(webfm_get_date_format(),  @filemtime($file->p . '/'. $file->n));
-      array_push($row, array('data' => $time, 'class' => 'att-time'));
+      array_push($row, array('data' => $time, 'class' => array('att-time')));
     }
     if($enable_size) {
-      array_push($row, array('data' => format_size($file->s), 'class' => 'att-size'));
+      array_push($row, array('data' => format_size($file->s), 'class' => array('att-size')));
     }
     array_push($rows, $row);
   }
   if (count($rows)) {
-    return theme('table', $header, $rows, array('class' => 'webfm-attach-list'));
+    return theme('table', $header, $rows, array('class' => array('webfm-attach-list')));
   }
-}
+}
\ No newline at end of file
Index: webfm.admin.inc
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/webfm/webfm.admin.inc,v
retrieving revision 1.4
diff -u -r1.4 webfm.admin.inc
--- webfm.admin.inc	19 Aug 2009 15:33:48 -0000	1.4
+++ webfm.admin.inc	13 Oct 2009 23:45:47 -0000
@@ -7,7 +7,7 @@
  */
 
 /**
- * Implementation of hook_settings().
+ * Implement hook_settings().
  */
 function webfm_admin_settings() {
   global $user;
@@ -306,7 +306,8 @@
       form_set_error('webfm_root_dir'. $rid, t('The webfm root directory name is not valid.'));
     } else {
       $webfm_root_dir = file_directory_path()."/".$webfm_root_dir_name;
-      $valid_webfm_root = file_check_directory($webfm_root_dir, FILE_CREATE_DIRECTORY, 'webfm_root_dir');
+      $valid_webfm_root = file_prepare_directory($webfm_root_dir,FILE_CREATE_DIRECTORY);
+	  if(!$valid_webfm_root) form_set_error('webfm_root_dir', t('Could not create directory %directoryname.',array('%directoryname' => $webfm_root_dir)));
     }
   }
 
@@ -332,7 +333,7 @@
           form_set_error('root_dir_'. $rid, t('The %role root directory name is not valid.', array('%role' => $role)));
         } else {
           $role_root_dir = $webfm_root_dir."/".$role_root_dir_name;
-          file_check_directory($role_root_dir, FILE_CREATE_DIRECTORY, 'root_dir_'.$rid);
+		  if(!file_prepare_directory($role_root_dir, FILE_CREATE_DIRECTORY)) form_set_error('root_dir_'.$rid, t('Could not create directory %directoryname.',array('%directoryname' => $role_root_dir)));
         }
       } else {
         form_set_error('root_dir_'. $rid, t('The WebFM root directory must be valid for the %role root directory name to be valid.', array('%role' => $role)));
@@ -365,7 +366,7 @@
             form_set_error('root_dir_group_'. $gid, t('The %group root directory name is not valid.', array('%group' => $group)));
           } else {
             $group_root_dir = $webfm_root_dir ."/". $group_root_dir_name;
-            file_check_directory($group_root_dir, FILE_CREATE_DIRECTORY, 'root_dir_group_'.$gid);
+            if(!file_prepare_directory($group_root_dir, FILE_CREATE_DIRECTORY)) form_set_error('root_dir_group_'.$gid, t('Could not create directory %directoryname.',array('%directoryname' => $group_root_dir)));
           }
         } else {
           form_set_error('root_dir_group_'. $gid, t('The WebFM root directory must be valid for the %group root directory name to be valid.', array('%group' => $group)));
Index: webfm_file.inc
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/webfm/webfm_file.inc,v
retrieving revision 1.12
diff -u -r1.12 webfm_file.inc
--- webfm_file.inc	19 Aug 2009 15:37:09 -0000	1.12
+++ webfm_file.inc	13 Oct 2009 23:45:54 -0000
@@ -2,6 +2,12 @@
 /* $Id: webfm_file.inc,v 1.12 2009/08/19 15:37:09 robmilne Exp $ */
 
 /**
+ * @file 
+ * This file provides file helper functions to the webfm-module
+ */
+
+
+/**
  * webfm_mkdir -called from the ajax action - switch case 'mkdir':
  *
  * @param string $source - the source directory path
@@ -16,7 +22,7 @@
     if(@mkdir($mkdir_path)) {
       chmod($mkdir_path, 0775);
       if (!is_writable($mkdir_path))
-        $error = t('The directory ').$mkdir_path.t(' is not writable');
+        $error = t('The directory %directoryname is not writable.', array( '%directoryname' => $mkdir_path));
       else
         return $mkdir_path;
     }
@@ -28,14 +34,14 @@
     if(@mkdir($munge_path)) {
       chmod($munge_path, 0775);
       if (!is_writable($munge_path))
-        $error = t('The directory ').$munge_path.t(' is not writable');
+        $error = t('The directory %directoryname is not writable.', array( '%directoryname' => $munge_path));
       else
         return $munge_path;
     } else {
-      $error = t('mkdir for ').$munge_path.t(' failed');
+      $error = t('mkdir for %directoryname failed.', array( '%directoryname' => $munge_path));
     }
   } else {
-    $error = t('The directory ').$mkdir_path.t(' already exists');
+    $error = t('The directory %directoryname already exists.', array( '%directoryname' => $mkdir_path));
   }
   return FALSE;
 }
@@ -75,15 +81,15 @@
       if(@rename($source, $dest_temp)) {
         if(!@rename($dest_temp, $dest)) {
           @rename($dest_temp, $source);
-          $err_arr[] = t('rename ').basename($source).t(' fail');
+          $err_arr[] = t('Renaming %sourcefile_filename failed.',array('%sourcefile_filename' => basename($source)));
           return FALSE;
         }
       } else {
-        $err_arr[] = basename($source).t(' read-only');
+        $err_arr[] = t('%sourcefile_filename is read-only.',array('%sourcefile_filename' => basename($source)));
         return FALSE;
       }
     } else {
-      $err_arr[] = t('permission denied');
+      $err_arr[] = t('Permission denied.');
       return FALSE;
     }
     return(webfm_rename_db_file($source, $dest, $err_arr));
@@ -100,8 +106,8 @@
         @rename($source, $dest_temp);
         @rename($dest_temp, $dest);
       } else {
-        $err_arr[] = t('webfm_rename_db_dir_recur error - db may be corrupted');
-        drupal_set_message(t('webfm_rename_db_dir_recur error - db may be corrupted'), 'error');
+        $err_arr[] = t('Could not recursively rename database files. Database may be corrupted. (webfm_rename_db_dir_recur failed)');
+        drupal_set_message(t('Could not recursively rename database files. Database may be corrupted. (webfm_rename_db_dir_recur failed)'), 'error');
         return FALSE;
       }
       return TRUE;
@@ -119,7 +125,7 @@
 function webfm_rename_db_file($source, $dest, &$err_arr) {
   if($fid = webfm_get_fid($source)) {
     if(!webfm_dbupdate_file($fid, $dest)) {
-      $err_arr[] = t('webfm_dbupdate_file error - fid: ').$fid;
+      $err_arr[] = t('Could not rename file %numeric_file_id in database. (webfm_dbupdate_file error)',array('%numeric_file_id in database' => $fid));
       return FALSE;
     }
   }
@@ -171,11 +177,11 @@
     }
     closedir($handle);
   } else {
-    $err_arr[] = t('Unable to opendir ').$source;
+    $err_arr[] = t('Unable to open directory %directoryname. ',array('%directoryname' => $source));
     return FALSE;
   }
   if(($retn = rmdir($source)) == FALSE)
-    $err_arr[] = t('Unable to rmdir ').$source;
+    $err_arr[] = t('Unable to remove directory %directoryname. ',array('%directoryname' => $source));
   return ($retn == TRUE && $ret == TRUE);
 }
 
@@ -183,11 +189,11 @@
   $file = webfm_get_file_record('', $source);
   if(@unlink($source)) {
     if($file && (!webfm_dbdelete_file($file->fid))) {
-      $error = t('webfm_dbdelete_file() fail for ').$source;
+      $error = t('Deleting file from database failed for %filename. (webfm_dbdelete_file() fail)',array('%filename' => $source));
       return FALSE;
     }
   } else if(file_exists($source)) {
-    $error = $source.t(' could not be deleted');
+    $error = t('%filename could not be deleted.',array('%filename' => $source));
     return FALSE;
   }
   return TRUE;
@@ -228,7 +234,7 @@
       return $ret;
     }
   } else {
-    $err_arr[] = $path .t(' already in db');
+    $err_arr[] = t('%filepath already is already stored in database.',array('%filepath'=>$path));
   }
   return FALSE;
 }
@@ -267,8 +273,7 @@
     }
     closedir($handle);
   } else {
-    $err_arr[] = t('Cannot open dir ').$path;
+    $err_arr[] = t('Cannot open diretory %directoryname ',array('%directoryname' => $path));
   }
   return $result;
-}
-?>
+}
\ No newline at end of file
Index: js/webfm.js
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/webfm/js/webfm.js,v
retrieving revision 1.32
diff -u -r1.32 webfm.js
--- js/webfm.js	17 Sep 2009 23:30:48 -0000	1.32
+++ js/webfm.js	13 Oct 2009 23:46:02 -0000
@@ -1,8 +1,11 @@
 /* $Id: webfm.js,v 1.32 2009/09/17 23:30:48 cweagans Exp $ */
 
 /* namespace */
+(function ($) {
 function Webfm() {}
 
+
+
 /*
 ** Global variables
 */
@@ -163,10 +166,10 @@
 
 /*
 ** Functions
+*
 */
-if (Drupal.jsEnabled) {
-  $(window).load(webfmLayout);
-}
+$(window).load(webfmLayout);
+
 
  /**
  * Remember last used textarea for inserting file hrefs.
@@ -4098,3 +4101,4 @@
 Drupal.mousePosition = function(e) {
   return { x: e.clientX + document.documentElement.scrollLeft, y: e.clientY + document.documentElement.scrollTop };
 };
+})(jQuery);
