You are here

filebrowser.module in Filebrowser 8

Validates file path input on node form

File

filebrowser.module
View source
<?php

/* This file is part of "filebrowser".
 *    Copyright 2009, arNuméral
 *    Author : Yoran Brault
 *    eMail  : yoran.brault@bad_arnumeral.fr (remove bad_ before sending an email)
 *    Site   : http://www.arnumeral.fr
 *
 * "filebrowser" is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * "filebrowser" is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public
 * License along with "filebrowser"; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
use Drupal\Drupal;
require_once "filebrowser.common.inc";
require_once "filebrowser.helpers.inc";

/**
* Implements hook_node_info().
function filebrowser_node_info()
D8: moved to /conf/node.type.dir_listing.yml
*/

/**
 * Implements hook_permission().
 */
function filebrowser_permission() {
  return array(
    FILEBROWSER_CREATE_DIRECTORY_LISTING => array(
      'title' => t('Create a directory listing'),
    ),
    FILEBROWSER_DELETE_OWN_DIRECTORY_LISTINGS => array(
      'title' => t('Delete own directory listings'),
    ),
    FILEBROWSER_DELETE_ANY_DIRECTORY_LISTINGS => array(
      'title' => t('Delete any directory listing'),
    ),
    FILEBROWSER_EDIT_OWN_DIRECTORY_LISTINGS => array(
      'title' => t('Edit own directory listings'),
    ),
    FILEBROWSER_EDIT_ANY_DIRECORY_LISTINGS => array(
      'title' => t('Edit any directory listing'),
    ),
    FILEBROWSER_VIEW_DIRECORY_LISTINGS => array(
      'title' => t('View directory listings'),
    ),
    FILEBROWSER_UPLOAD => array(
      'title' => t('Upload files'),
    ),
    FILEBROWSER_DOWNLOAD_ARCHIVE => array(
      'title' => t('Download archive'),
    ),
    FILEBROWSER_DELETE_FILE => array(
      'title' => t('Delete file'),
    ),
    FILEBROWSER_DOWNLOAD => array(
      'title' => t('Download files'),
    ),
    FILEBROWSER_CREATE_FOLDER => array(
      'title' => t('Create folders'),
    ),
    // -- Filebrowser entity
    'delete_filebrowser' => array(
      'title' => t('Delete entity content.'),
    ),
    'add_filebrowser' => array(
      'title' => t('Add entity content'),
    ),
    'view_filebrowser' => array(
      'title' => t('View entity content'),
    ),
    'edit_filebrowser' => array(
      'title' => t('Edit entity content'),
    ),
    'admin_filebrowser' => array(
      'title' => t('Administer settings'),
    ),
  );
}

/**
 * Implements hook_menu_link_defaults().
 */
function filebrowser_menu_link_defaults() {
  $links = array();
  $links['filebrowser.admin.structure.settings'] = array(
    'link_title' => 'Filebrowser Settings',
    'description' => 'Configure Filebrowser entity',
    'route_name' => 'filebrowser.settings',
    'parent' => 'system.admin.structure',
  );
  $links['filebrowser.list'] = array(
    'link_title' => 'Filebrowser Listing',
    'description' => 'List Filebrowser content',
    'route_name' => 'filebrowser.list',
  );
  return $links;
}

/**
 * Implements hook_menu().
 */

// FIXME: Do we need a admin/config for default values??
// Some site wide defaults are set now in hook_form
function filebrowser_menu() {
  $items = array();
  $items['filebrowser/download/%fid'] = array(
    'title' => 'Filebrowser',
    'description' => "",
    'route_name' => 'filebrowser.download',
    'type' => MENU_CALLBACK,
  );
  $items['filebrowser/delete/%fid'] = array(
    'route_name' => 'filebrowser.delete',
    'type' => MENU_CALLBACK,
  );
  $items['filebrowser/metadata/%fid'] = array(
    'route_name' => 'filebrowser.metadata',
    'type' => MENU_CALLBACK,
  );
  $items['filebrowser/thumbnails/%fid'] = array(
    'route_name' => 'filebrowser.thumbnails',
    'type' => MENU_CALLBACK,
  );
  return $items;
}

// TOD: Token integration f module "token" exists

/*if (\Drupal::moduleHandler()->moduleExists('token')) {
    $form['token_help'] = array(
      '#title' => t('Replacement patterns'),
      '#type' => 'fieldset',
      '#collapsible' => TRUE,
      '#collapsed' => TRUE,
    );

    $form['token_help']['help'] = array(
      '#theme' => 'token_tree',
      '#token_types' => array('node'),
    );
  }   */

/* $handlers = module_implements("filebrowser_handler_info");
  if (count($handlers)) {
    $form['file_handlers'] = array(
      '#type' => 'fieldset',
      '#tree' => TRUE,
      '#title' => 'File handlers',
      '#collapsible' => TRUE,
      '#collapsed' => TRUE,
    );
    foreach ($handlers as $module) {
      $info = module_invoke($module, "filebrowser_handler_info");
      $form['file_handlers']["$module"] = array(
        '#type' => 'fieldset',
        '#tree' => TRUE,
        '#title' => $info['description'],
        '#collapsible' => TRUE,
        '#collapsed' => TRUE,
        '#weight' => -6
      );
      $default_setting = $node->file_handlers->$module;
      if (!$default_setting) {
        $default_setting = (object)array();
      }
      $settings = module_invoke($module, "filebrowser_handler_settings", $default_setting);
      $form['file_handlers']["$module"]['enabled_thumbnailer'] = array(
        '#type' => 'checkbox',
        '#title' => t('Enabled as thumbnailer'),
        '#description' => t('Enable this file handler as thumbnailer.'),
        '#default_value' => isset($default_setting->enabled_thumbnailer) ? $default_setting->enabled_thumbnailer : FALSE
      );
      $form['file_handlers']["$module"]['enabled_metadata'] = array(
        '#type' => 'checkbox',
        '#title' => t('Enabled as metadata provider'),
        '#description' => t('Enable this file handler as metadata provider.'),
        '#default_value' => isset($default_setting->enabled_metadata) ? $default_setting->enabled_metadata : FALSE
      );
        foreach ($settings as $key => $setting) {
          $form['file_handlers']["$module"][$key] = $setting;
        }
      }
    } */

/**
 * Implements hook_node_validate().
 */

// FIXME check better way to retrieve entity's value i.s.o. getValue()
function filebrowser_node_validate(\Drupal\Core\Entity\EntityInterface $node, $form, &$form_state) {

  // debug print_r($node); exit();
  if ($node
    ->bundle() == 'dir_listing') {

    // Validate file path
    $file_path = $node->field_file_path
      ->getValue()[0]['value'];
    $encoding = $node->field_encoding
      ->getValue()[0]['value'];

    // Validate the file path entered
    $result = _fb_validate_file_path($file_path, $encoding);
    if ($result) {
      \Drupal::formBuilder()
        ->setErrorByName('field_file_path', $form_state, $result);
    }
    else {
      drupal_set_message(t('The directory %dir has been created.', array(
        '%dir' => $file_path,
      )));
    }
  }
}

/**
 * @file
 * Validates file path input on node form
 * @param $file_path String as filled in node form
 *
 * @return An error-string in case of file path error. Else NULL
 */
function _fb_validate_file_path($file_path, $encoding) {
  $encoded_path = _filebrowser_encoding_to_fs($encoding, $file_path);
  if (!is_dir($encoded_path)) {
    $success = mkdir($encoded_path, 0777, TRUE);
    if (!$success) {
      return t('Unable to create directory. It might be invalid.');
    }
    else {
      return false;
    }
  }
  else {
    if (!is_readable($encoded_path)) {
      return t('The directory %dir is not readable.', array(
        '%dir' => $file_path,
      ));
    }
  }
  return false;
}

/**
 * hook_db_rewrite_sql implementation.
 */
function filebrowser_db_rewrite_sql($query, $primary_table, $primary_field, $args) {
  global $user;
  if ($primary_table == 'n' && $primary_field == 'nid' && !user_access(FILEBROWSER_VIEW_DIRECORY_LISTINGS, $user)) {
    $return = array(
      'where' => "n.type != 'dir_listing'",
    );
    return $return;
  }
}

/**
 * Implements hook_load().
 */
function filebrowser_load($nodes) {
  $query = db_select('node_dir_listing', 'n');
  $query
    ->condition('nid', array_keys($nodes));
  $query
    ->fields('n');
  foreach ($query
    ->execute() as $data) {
    $additions = (object) unserialize($data->properties);
    $additions->folder_path = $data->folder_path;
    $additions->nid = $data->nid;
    _filebrowser_prepare_record($additions, TRUE);
    foreach ($additions as $key => $value) {
      $nodes[$data->nid]->{$key} = $value;
    }
  }
}

/**
 * Implements hook_insert().
 */
function filebrowser_insert($node) {
  _filebrowser_prepare_record($node, FALSE);
  drupal_write_record("node_dir_listing", $node);
}

/**
 * Implements hook_update().
 */
function filebrowser_update($node) {
  _filebrowser_prepare_record($node, FALSE);
  drupal_write_record("node_dir_listing", $node, 'nid');
  _filebrowser_node_content_delete($node);
}

/**
 * Implements hook_delete().
 */
function filebrowser_delete($node) {
  db_query('DELETE FROM {node_dir_listing} WHERE nid = :nid', array(
    ':nid' => $node->nid,
  ));
  _filebrowser_node_content_delete($node);
}

/**
 * Implements hook_view().
 */
function filebrowser_node_view(Node $node, EntityViewDisplayInterface $display, $view_mode, $langcode) {

  // if ($view_mode=="full") {
  //  _filebrowser_load_files($node);
  // Full node content view
  // ========================================================
  // Keep track of the current location and update breadcrumbs to reflect that.
  // todo: Set breadcrumbs D8 style: https://drupal.org/node/2026025
  // check D7 version
  // Insert file listing  content part
  //  if ($display->getComponent('mymodule_addition')) {
  $node->content['mymodule_addition'] = array(
    // '#markup' => mymodule_addition($node),
    // '#theme' => 'mymodule_my_additional_field',
    '#markup' => "<p><strong>Markup</strong></p>",
  );

  //   }

  /*
      $current_view = _filebrowser_externals('presentations', $node->folder_presentation->default_view);
      $node->content['filebrowser_content'] = array(
   '#markup' => count($node->file_listing) == 0 ? '' : theme($current_view['theme'], array('node' => $node)),
   '#weight' => 1
      );
      if ($node->folder_uploads->enabled && user_access(FILEBROWSER_UPLOAD)) {
   $node->content['filebrowser_form_upload'] = array(
     '#markup' => drupal_render(drupal_get_form('filebrowser_form_upload', $node)),
     '#weight' => 2
   );
      }
      if ($node->folder_uploads->enabled && user_access(FILEBROWSER_CREATE_FOLDER)) {
   $node->content['filebrowser_form_create_folder'] = array(
     '#markup' => drupal_render(drupal_get_form('filebrowser_form_create_folder', $node)),
     '#weight' => 3
   );
      }
      $statistics = array(
   'empty' => t('This folder is empty')
      );
      if ($node->file_listing['.']['folders_count'] > 0) {
   $statistics['folders'] = format_plural($node->file_listing['.']['folders_count'], '1 dossier', '@count dossiers');
   $statistics['empty'] = NULL;
      }
      if ($node->file_listing['.']['files_count'] > 0) {
   $statistics['files'] = format_plural($node->file_listing['.']['files_count'], '1 file', '@count files');
   $statistics['size'] = format_size($node->file_listing['.']['size']);
   $statistics['empty'] = NULL;
      }
      $node->content['filebrowser_statistics'] = array(
   '#markup' => theme('dir_listing_statistics', $statistics),
   '#weight' => 3
      );
    }
    // Insert filebrowser links
    $node-> content['links']['filebrowser'] = array('#theme' => 'links__node__blog',
      '#links' => _filebrowser_links($node),
      '#attributes' => array('class' => array('links', 'inline')),);
      /*
  *
  */

  // }
  return $node;
}

/**
 * Implements hook_init().
 */
function filebrowser_view_D7_BAK($node, $view_mode) {
  if ($view_mode == "full") {
    _filebrowser_load_files($node);

    // Full node content view
    // ========================================================
    // Keep track of the current location and update breadcrumbs to reflect that.
    $breadcrumbs = array(
      l(t('Home'), NULL),
    );
    $breadcrumb_path = "";

    //print_r($node);

    //return;
    $path_elements = explode('/', rtrim($node->file_listing['.']['relative-path'], "/"));
    for ($i = 0; $i < count($path_elements); $i++) {
      $child_dir = $path_elements[$i] == '' ? '/' : $path_elements[$i];
      $breadcrumb_path .= $child_dir;
      $fid = db_query("SELECT fid FROM {node_dir_listing_content}\n                     WHERE path = :path", array(
        ':path' => $breadcrumb_path,
      ))
        ->fetchField();
      if ($child_dir == '/') {
        $label = $node->title;
      }
      else {
        $label = $child_dir;
      }
      if ($i < count($path_elements) - 1) {
        $breadcrumbs[] = l($label, "node/{$node->nid}/{$fid}");
      }
      else {
        $breadcrumbs[] = $label;
      }
    }
    drupal_set_breadcrumb($breadcrumbs);

    // Insert file listing  content part
    $current_view = _filebrowser_externals('presentations', $node->folder_presentation->default_view);
    $node->content['filebrowser_content'] = array(
      '#markup' => count($node->file_listing) == 0 ? '' : theme($current_view['theme'], array(
        'node' => $node,
      )),
      '#weight' => 1,
    );
    if ($node->folder_uploads->enabled && user_access(FILEBROWSER_UPLOAD)) {
      $node->content['filebrowser_form_upload'] = array(
        '#markup' => drupal_render(drupal_get_form('filebrowser_form_upload', $node)),
        '#weight' => 2,
      );
    }
    if ($node->folder_uploads->enabled && user_access(FILEBROWSER_CREATE_FOLDER)) {
      $node->content['filebrowser_form_create_folder'] = array(
        '#markup' => drupal_render(drupal_get_form('filebrowser_form_create_folder', $node)),
        '#weight' => 3,
      );
    }
    $statistics = array(
      'empty' => t('This folder is empty'),
    );
    if ($node->file_listing['.']['folders_count'] > 0) {
      $statistics['folders'] = format_plural($node->file_listing['.']['folders_count'], '1 dossier', '@count dossiers');
      $statistics['empty'] = NULL;
    }
    if ($node->file_listing['.']['files_count'] > 0) {
      $statistics['files'] = format_plural($node->file_listing['.']['files_count'], '1 file', '@count files');
      $statistics['size'] = format_size($node->file_listing['.']['size']);
      $statistics['empty'] = NULL;
    }
    $node->content['filebrowser_statistics'] = array(
      '#markup' => theme('dir_listing_statistics', $statistics),
      '#weight' => 3,
    );
  }

  // Insert filebrowser links
  $node->content['links']['filebrowser'] = array(
    '#theme' => 'links__node__blog',
    '#links' => _filebrowser_links($node),
    '#attributes' => array(
      'class' => array(
        'links',
        'inline',
      ),
    ),
  );
  return $node;
}

/**
 * Implements hook_node_view().
 */
function filebrowser_node_view_bak($node, $view_mode) {
  if ($node->type == 'dir_listing' && $view_mode == 'full') {
    $links = array();
    if (_filebrowser_metadata_access($node->file_listing['.']['fid'])) {
      $links['file_browser_metadata'] = array(
        'href' => "filebrowser/metadata/{$node->file_listing['.']['fid']}",
        'title' => t("Edit Metadatas"),
        'query' => drupal_get_destination(),
      );
    }
    $thumbnailers = module_implements("filebrowser_thumbnailer_prepare");
    if (count($thumbnailers) != 0) {
      $links['file_browser_update_thumbnails'] = array(
        'href' => "filebrowser/thumbnails/{$node->file_listing['.']['fid']}",
        'title' => t("Update thumbnails"),
        'query' => drupal_get_destination(),
      );
    }
    $node->content['links']['filebrowser'] = array(
      '#theme' => 'links',
      '#links' => $links,
    );
  }
}

/**
 * upload form definition.
 */
function filebrowser_form_upload($form, &$form_state, $node) {
  $form = array();
  $form['filebrowser_uploads'] = array(
    '#type' => 'fieldset',
    '#title' => t('File Upload'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
    '#description' => t('Uploaded file will be saved to the current directory.'),
    '#prefix' => '<div class="attachments">',
    '#suffix' => '</div>',
    '#weight' => 30,
  );

  // Wrapper for fieldset contents (used by ahah.js).

  /*      $form['filebrowser_uploads']['wrapper'] = array(
          '#prefix' => '<div id="attach-wrapper">',
          '#suffix' => '</div>',
        '#type'=>'textfield'

        );*/
  $form['node'] = array(
    '#type' => 'value',
    '#value' => $node,
  );
  $form['#attributes'] = array(
    'enctype' => "multipart/form-data",
  );
  _filebrowser_load_files($node);
  $form['#submit'][] = 'filebrowser_form_upload_submit';
  $form['#validate'][] = 'filebrowser_form_upload_validate';
  $i = 1;

  // Later we can have multi-upload
  $form['filebrowser_uploads']["file_{$i}"] = array(
    '#type' => 'file',
    '#title' => t('Upload file'),
    '#size' => 40,
  );
  $form['filebrowser_uploads']["description_{$i}"] = array(
    '#type' => 'textarea',
    '#title' => t('Description'),
    '#size' => 255,
  );
  $form['filebrowser_uploads']["file_name_{$i}"] = array(
    '#type' => 'textfield',
    '#description' => t('Just put filename with NO EXTENSION here if you want to rename the file you want to upload'),
    '#title' => t('New name'),
    '#size' => 40,
  );
  $form['submitted'] = array(
    '#tree' => TRUE,
  );
  $form['filebrowser_uploads']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Upload'),
  );
  $form['#redirect'] = NULL;
  return $form;
}

/**
 * uploads validation.
 */
function filebrowser_form_upload_validate($form, &$form_state) {
  $node = $form_state['values']['node'];
  _filebrowser_load_files($node);
  $i = 1;

  // Later we can have multi-upload
  $target = _filebrowser_build_new_upload_file_name($node, $form_state, $i);
  if (!$node->folder_uploads->allow_overwrite && file_exists($target)) {
    form_error($form['filebrowser_uploads']["file_{$i}"], t("This file already exists."));
  }
  if (!empty($node->folder_uploads->accepted_uploaded_files) && !_filebrowser_match_path($target, $node->folder_uploads->accepted_uploaded_files)) {
    form_error($form['filebrowser_uploads']["file_{$i}"], t("Sorry, you can't upload this kind of file."));
  }
}

/**
 * uploads submition.
 */
function filebrowser_form_upload_submit($form, &$form_state) {
  $i = 1;

  // Later we can have multi-upload
  $node = $form_state['values']['node'];
  $target = _filebrowser_build_new_upload_file_name($node, $form_state, $i);
  $success = copy($_FILES['files']['tmp_name']["file_{$i}"], $target);
  if (!$success) {
    drupal_set_message(t("Unable to upload this file, do you have filesystem right to do that ?"), 'error');
  }
  else {
    _filebrowser_load_files($node, NULL, TRUE);

    // force listing rebuild
    if (!empty($form['filebrowser_uploads']["description_{$i}"])) {
      $file = $node->file_listing[_filebrowser_safe_basename($target)];
      module_invoke_all('filebrowser_metadata_set', $file, array(
        'description' => $form_state['values']["description_{$i}"],
      ));
    }
  }
  drupal_goto("node/{$node->nid}/{$node->file_listing['.']['fid']}", _filebrowser_url_query());
}
function filebrowser_form_create_folder($form, $form_state, $node) {
  $form = array();
  $form['filebrowser_create_folder'] = array(
    '#type' => 'fieldset',
    '#title' => t('Create a folder'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
    '#description' => t('This folder will be created within the current directory.'),
    '#weight' => 30,
  );
  $form['node'] = array(
    '#type' => 'value',
    '#value' => $node,
  );
  $form['#submit'][] = 'filebrowser_form_create_folder_submit';
  $form['#validate'][] = 'filebrowser_form_create_folder_validate';
  $form['filebrowser_create_folder']['folder_name'] = array(
    '#type' => 'textfield',
    '#title' => t('Folder Name'),
    '#size' => 40,
    '#required' => TRUE,
  );
  $form['filebrowser_create_folder']['description'] = array(
    '#type' => 'textarea',
    '#title' => t('Description'),
    '#size' => 255,
  );
  $form['submitted'] = array(
    '#tree' => TRUE,
  );
  $form['filebrowser_create_folder']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Create'),
  );
  return $form;
}

/**
 * Implements hook_validate() for creating a folder
 */
function filebrowser_form_create_folder_validate($form, $form_state) {
  $node = $form_state['values']['node'];
  _filebrowser_load_files($node);
  $target = _filebrowser_encoding_to_fs($node, "{$node->file_listing['.']['full-path']}/{$form_state['values']['folder_name']}");
  if (file_exists($target)) {
    form_error($form['filebrowser_create_folder']['folder_name'], t("This folder already exists."));
  }
}

/**
 * create folder submition.
 */
function filebrowser_form_create_folder_submit($form, &$form_state) {
  $i = 1;

  // Later we can have multi-upload
  $node = $form_state['values']['node'];
  $target = _filebrowser_encoding_to_fs($node, "{$node->file_listing['.']['full-path']}/{$form_state['values']['folder_name']}");
  $success = mkdir($target, 0777);
  if (!$success) {
    drupal_set_message(t("Unable to create this folder, do you have filesystem right to do that ?"), 'error');
  }
  else {
    _filebrowser_load_files($node, NULL, TRUE);

    // force listing rebuild
    if (!empty($form_state['values']["description"])) {
      $file = $node->file_listing[_filebrowser_safe_basename($target)];
      module_invoke_all('filebrowser_metadata_set', $file, array(
        'description' => $form_state['values']["description"],
      ));
    }
  }
  drupal_goto("node/{$node->nid}/{$node->file_listing['.']['fid']}", _filebrowser_url_query());
}
function filebrowser_form_actions($form, &$form_state, $header, $options, $actions, $node) {
  $form = array();
  $form['#node'] = $node;
  $form['table'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $options,
    '#multiple' => TRUE,
  );

  // Normally the checkboxes are created by form_process_tableselect(). They are created manually here
  // to have the checkboxes behave the way we want it for filebrowser.

  /*  foreach ($options as $key => $data) {
      $form['table'][$key] = array(
        '#type' => 'checkbox',
        '#title' => $data['fid'],
        //'#title_display' => 'invisible',
        //'#return_value' =>  'foop',
        '#default_value' => 0,
        // disable the checkbox and hide it if this item has no fid (is not a selectable item)
        '#disabled' => empty($data['fid']) ? TRUE : FALSE,
        '#attributes' => empty($data['fid']) ? array('style' => 'display:none;') : '',
        );
    }*/
  $fb_options = array(
    '' => t('choose an action'),
  );
  foreach ($actions as $action) {
    $fb_options[$action['operation']] = $action['title'];
  }
  $form['action'] = array(
    '#prefix' => '<br/><div class="container-inline">',
    '#title' => t('actions'),
    '#type' => 'select',
    '#options' => $fb_options,
  );
  $form['submit'] = array(
    '#value' => t('Process'),
    '#type' => 'submit',
    '#suffix' => '</div><br/>',
  );
  return $form;
}
function filebrowser_form_actions_submit($form, $form_state) {

  // Collect de selected checkboxes in put them in array $fid
  $fids = array();
  if (!empty($form_state['values']['action'])) {
    foreach ($form_state['values']['table'] as $key => $value) {
      if ($value) {
        $fids[] = $form['table']['#options'][$key]['fid'];
      }
    }
    $result = module_invoke_all('filebrowser_action_process', $form['#node'], $form_state['values']['action'], $fids);
    if ($result) {
      return $result;
    }
  }
  header('Location: ' . request_uri(), TRUE, 302);
  exit;
}

/**
 * File delete confirmation form
 * CHECK: $node is used but not defined in this function
 */
function filebrowser_form_delete_confirm($form, &$form_state, $fids) {
  $form['fids'] = array(
    '#type' => 'value',
    '#value' => $fids,
  );
  foreach ($fids as &$fid) {
    $file = _filebrowser_node_content_load($fid);
    $fid = _filebrowser_safe_basename($file['path']);
  }
  return confirm_form($form, t('Are you sure you want to delete following files ?'), isset($_GET['destination']) ? $_GET['destination'] : 'node/' . $node->nid, "<ul><li>" . implode("</li><li>", $fids) . "</li></ul>" . t('This action cannot be undone.'), t('Delete'), t('Cancel'));
}

/**
 * File delete confirmation form submit
 */
function filebrowser_form_delete_confirm_submit($form, &$form_state) {
  foreach ($form_state['values']['fids'] as $fid) {
    $content = _filebrowser_node_content_load($fid);
    $node = node_load($content['nid']);
    $target = _filebrowser_encoding_to_fs($node, _filebrowser_get_node_root($node) . $content['path']);
    if (is_file($target)) {
      $result = unlink($target);
      if (!$result) {
        drupal_set_message(t('Unable to delete @file', array(
          '@file' => $target,
        )), 'warning');
      }
    }
    else {
      $result = rmdir($target);
      if (!$result) {
        drupal_set_message(t('Unable to prune @file (not empty ?)', array(
          '@file' => $target,
        )), 'warning');
      }
    }
  }

  // $form_state['redirect'] = isset($_GET['destination']) ? $_GET['destination'] : '<front>';
}

/**
 * hook_node_access implementation.
 */
function filebrowser_node_access($node, $op, $account) {
  if ($op == 'view') {
    if (!user_access(FILEBROWSER_VIEW_DIRECORY_LISTINGS, $account)) {
      return FALSE;
    }
  }
  if ($op == 'create') {
    if (!user_access(FILEBROWSER_CREATE_DIRECTORY_LISTING, $account)) {
      return FALSE;
    }
  }
  if ($op == 'update') {
    if (!user_access(FILEBROWSER_EDIT_ANY_DIRECORY_LISTINGS, $account) || !(user_access(FILEBROWSER_EDIT_OWN_DIRECTORY_LISTINGS, $account) && $account->uid == $node->uid)) {
      return FALSE;
    }
  }
  if ($op == 'delete') {
    if (!user_access(FILEBROWSER_DELETE_ANY_DIRECTORY_LISTINGS, $account) || user_access(FILEBROWSER_DELETE_OWN_DIRECTORY_LISTINGS, $account) && $account->uid == $node->uid) {
      return FALSE;
    }
  }
}

/**
 * hook_filebrowser_actions_info implementation
 * @param unknown_type $node
 */
function filebrowser_filebrowser_actions_info($node) {
  $actions = array();
  if ($node->file_listing['.']['files_count'] > 0) {
    if (_filebrowser_can_download_archive($node) && function_exists('zip_open')) {
      $actions[] = array(
        'operation' => 'download',
        'title' => t("Download selected items as an ZIP archive (only files)"),
      );
    }
    if (user_access(FILEBROWSER_DELETE_FILE)) {
      $actions[] = array(
        'operation' => 'delete',
        'title' => t("Delete selected items"),
      );
    }
  }
  return $actions;
}

/**
 * hook_filebrowser_action_process implementation
 */
function filebrowser_filebrowser_action_process($node, $action, $fids) {
  switch ($action) {
    case 'download':
      $root_fid = $node->file_listing['.']['fid'];
      if (count($fids) > 0) {
        $root_fid .= ":" . implode(',', $fids);
      }
      require_once "filebrowser.pages.inc";
      filebrowser_page_download($root_fid);
      break;
    case 'delete':
      drupal_goto("filebrowser/delete/" . implode(',', $fids), array(
        'query' => drupal_get_destination(),
      ));
  }
}

/**
 * hook_filebrowser_download_manager_info implementation.
 */
function filebrowser_filebrowser_download_manager_info() {
  return array(
    'public' => array(
      'title' => t('Direct download (files are served by the web server and should be accessible by it)'),
    ),
    'private' => array(
      'title' => t('Private download (files are served by PHP/Drupal an could be everywhere)'),
    ),
  );
}

/**
 * hook_filebrowser_download_manager_process implementation.
 */
function filebrowser_filebrowser_download_manager_process($delta = NULL, $file = NULL, $filename = NULL) {
  switch ($delta) {
    case 'public':
      $web_root = getcwd();
      if (strpos($web_root, $file) === 0) {
        $target = substr($file, strlen($web_root));
      }
      else {
        $target = $file;
      }
      header("Location: " . url(trim($target, '/'), array(
        'absolute' => TRUE,
      )));
      return TRUE;
    case 'private':
      header('Content-Description: File Transfer');
      header("Cache-Control: public, must-revalidate, max-age=0");

      // HTTP/1.1
      header("Pragma: public");
      header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");

      // Date in the past
      header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
      header("Content-Type: " . file_get_mimetype($filename));
      header("Content-Transfer-Encoding: binary");
      header("Content-Length: " . filesize($file));
      if (stristr("MSIE", getenv("HTTP_USER_AGENT")) || stristr("Internet Explorer", getenv("HTTP_USER_AGENT"))) {
        header('Content-Disposition: inline; filename="' . mb_convert_encoding(_filebrowser_safe_basename($filename), "ISO-8859-2", "UTF-8") . '";');
      }
      else {
        header('Content-Disposition: inline; filename="' . _filebrowser_safe_basename($filename) . '";');
      }
      $block_size = 4096;
      $buffer = '';
      $handle = fopen($file, 'rb');
      drupal_set_time_limit(0);
      if ($handle !== FALSE) {
        while (!feof($handle)) {
          $buffer = fgets($handle, $block_size);
          echo $buffer;
          ob_flush();
          flush();
        }
        fclose($handle);
      }
      return TRUE;
  }
}

/**
 * hook_filebrowser_presentation
 */
function filebrowser_filebrowser_presentations() {
  return array(
    'list-view' => array(
      'title' => t('Present this folder as a list-view'),
      'theme' => 'dir_listing_list_view',
    ),
    'icon-view' => array(
      'title' => t('Present this folder as an icon-view'),
      'theme' => 'dir_listing_icon_view',
    ),
  );
}

/**
 * hook_filebrowser_metadata_definition implementation.
 */
function filebrowser_filebrowser_metadata_info() {
  return [
    FILEBROWSER_DATA_NAME_ICON => array(
      'title' => t('Icon'),
    ),
    FILEBROWSER_DATA_NAME_DISPLAY_NAME => array(
      'title' => t('Display name'),
      'sortable' => TRUE,
      'type' => 'string',
    ),
    FILEBROWSER_DATA_NAME_CREATED => array(
      'title' => t('created'),
      'sortable' => TRUE,
      'type' => 'integer',
    ),
    FILEBROWSER_DATA_NAME_SIZE => array(
      'title' => t('size'),
      'sortable' => TRUE,
      'type' => 'integer',
    ),
    FILEBROWSER_DATA_NAME_MODIFIED => array(
      'title' => t('modified'),
      'sortable' => TRUE,
      'type' => 'integer',
    ),
    FILEBROWSER_DATA_NAME_TYPE => array(
      'title' => t('Mime type'),
      'sortable' => TRUE,
      'type' => 'string',
    ),
    FILEBROWSER_DATA_NAME_DESCRIPTION => array(
      'title' => t('Description'),
      'writable' => TRUE,
      'sortable' => TRUE,
      'type' => 'string',
    ),
  ];
}
function filebrowser_filebrowser_metadata_get($file) {
  $full_path = $file['full-path'];
  $is_file = is_file($full_path);
  $result = array(
    'created' => 0,
    'modified' => 0,
    'size' => 0,
    'kind' => $is_file ? 0 : 1,
    'mime-type' => !$is_file ? "folder" : file_get_mimetype($full_path),
    'description' => _filebrowser_read_description($full_path),
  );
  if (($f_stats = stat($full_path)) !== FALSE) {
    if (is_file($full_path)) {
      $result['size'] = $f_stats['size'];
    }
    $result['created'] = $f_stats['ctime'];
    $result['modified'] = $f_stats['mtime'];
  }
  return $result;
}
function filebrowser_filebrowser_metadata_set($file, $metadata) {
  $base_path = _filebrowser_safe_dirname($file['full-path']);
  $data = _filebrowser_load_description_file($base_path);
  if (!isset($data['file'])) {
    $data['file'] = "{$base_path}/descript.ion";
  }
  $data['data'][$file['display-name']] = $metadata['description'];
  _filebrowser_save_description_file($data, $base_path);
  _filebrowser_load_description_file($base_path, $data);
}

/**
 * Implements hook_theme().
 */
function filebrowser_theme() {
  return array(
    'dir_listing_list_view' => array(
      'variables' => array(
        'node' => NULL,
      ),
      'file' => 'filebrowser.theme.inc',
    ),
    'dir_listing_icon' => array(
      'template' => 'dir_listing_icon',
    ),
    'dir_listing_icon_view' => array(
      'variables' => array(
        'node' => NULL,
      ),
      'file' => 'filebrowser.theme.inc',
    ),
    'dir_listing_statistics' => array(
      'variables' => array(
        'statistics' => NULL,
      ),
      'file' => 'filebrowser.theme.inc',
    ),
    'dir_listing_metadata_group' => array(
      //'variables' => array('render element' => NULL),
      'file' => 'filebrowser.theme.inc',
    ),
  );
}
function filebrowser_node_operations() {
  $operations = array(
    'filebrowser_thumbnails' => array(
      'label' => t('Update filebrowser thumbnails'),
      'callback' => 'filebrowser_node_mass_update_thumbnails',
      'callback arguments' => array(),
    ),
  );
  return $operations;
}
function filebrowser_node_mass_update_thumbnails($nodes) {
  module_load_include("pages.inc", "filebrowser");
  foreach ($nodes as $nid) {
    $node = node_load($nid);
    _filebrowser_load_files($node);
    $fids[] = $node->file_listing['.']['fid'];
  }
  filebrowser_update_thumbnails($fids);
}

/* In D6 -version this was hook_links || now moved to hook_view
 * @return array of links
 */

// CHECK IF there are more links from D6 JSJ FIXME
function _filebrowser_links($node) {
}
function filebrowser_field_default_view_options() {
  return array(
    'een' => 'Een',
    'twee' => 'Twee',
  );
}

// returns options for field download manager
function option_field_download_manager() {
  return _filebrowser_options(_filebrowser_externals('download_manager_info'));
}

// returns options for field visible columns
function options_field_visible_columns() {
  return _filebrowser_options(_filebrowser_externals('metadata_info'));
}

// returns options for field default sort
function options_default_sort() {
  $sortable = array();
  $cols = _filebrowser_externals('metadata_info');

  // TODO: we should check if it is sortable
  foreach ($cols as $name => $data) {
    $sortable[$name] = $data['title'];
  }
  return $sortable;
}

// returns options for field default view
function options_default_view() {
  return _filebrowser_options(_filebrowser_externals('presentations'));
}

Functions

Namesort descending Description
filebrowser_db_rewrite_sql hook_db_rewrite_sql implementation.
filebrowser_delete Implements hook_delete().
filebrowser_field_default_view_options
filebrowser_filebrowser_actions_info hook_filebrowser_actions_info implementation
filebrowser_filebrowser_action_process hook_filebrowser_action_process implementation
filebrowser_filebrowser_download_manager_info hook_filebrowser_download_manager_info implementation.
filebrowser_filebrowser_download_manager_process hook_filebrowser_download_manager_process implementation.
filebrowser_filebrowser_metadata_get
filebrowser_filebrowser_metadata_info hook_filebrowser_metadata_definition implementation.
filebrowser_filebrowser_metadata_set
filebrowser_filebrowser_presentations hook_filebrowser_presentation
filebrowser_form_actions
filebrowser_form_actions_submit
filebrowser_form_create_folder
filebrowser_form_create_folder_submit create folder submition.
filebrowser_form_create_folder_validate Implements hook_validate() for creating a folder
filebrowser_form_delete_confirm File delete confirmation form CHECK: $node is used but not defined in this function
filebrowser_form_delete_confirm_submit File delete confirmation form submit
filebrowser_form_upload upload form definition.
filebrowser_form_upload_submit uploads submition.
filebrowser_form_upload_validate uploads validation.
filebrowser_insert Implements hook_insert().
filebrowser_load Implements hook_load().
filebrowser_menu
filebrowser_menu_link_defaults Implements hook_menu_link_defaults().
filebrowser_node_access hook_node_access implementation.
filebrowser_node_mass_update_thumbnails
filebrowser_node_operations
filebrowser_node_validate
filebrowser_node_view Implements hook_view().
filebrowser_node_view_bak Implements hook_node_view().
filebrowser_permission Implements hook_permission().
filebrowser_theme Implements hook_theme().
filebrowser_update Implements hook_update().
filebrowser_view_D7_BAK Implements hook_init().
options_default_sort
options_default_view
options_field_visible_columns
option_field_download_manager
_fb_validate_file_path @file Validates file path input on node form
_filebrowser_links