You are here

filebrowser.module in Filebrowser 8.2

File

filebrowser.module
View source
<?php

/* This file is part of "filebrowser".
 *    Copyright 2016, YagoSoft
 *    Author : Joop Sint Jago
 *    eMail  : j.sintjago@bad_xs4all.nl (remove bad_ before sending an email)
 *    Site   : http://yagosoft.com
 *
 * "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\Core\Entity;
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\Core\Field;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Access\AccessResult;
use Drupal\node\NodeInterface;
use Drupal\filebrowser\Filebrowser;
use Drupal\filebrowser\Services\Common;

/**
 * Implements hook_theme().
 */
function filebrowser_theme() {
  return [
    'filebrowser_icon_svg' => [
      'variables' => [
        'html' => [],
        'data' => [],
      ],
    ],
    'statistics' => [
      'variables' => [
        'statistics' => [],
      ],
      'file' => 'filebrowser.theme.inc',
    ],
    'filebrowser_description' => [
      'variables' => [
        'data' => [],
      ],
      'file' => 'filebrowser.theme.inc',
    ],
    'filebrowser_grid_container' => [
      'variables' => [
        'options' => [],
      ],
    ],
    'filebrowser_grid_item' => [
      'variables' => [
        'data' => [],
      ],
    ],
    'filebrowser_container_column' => [
      'variables' => [],
      'template' => 'filebrowser-container-column',
    ],
    'filebrowser_container' => [
      'template' => 'filebrowser-container',
      'file' => 'filebrowser.theme.inc',
    ],
  ];
}

/**
 * Implements hook_entity_type_build().
 * @inheritdoc
 */
function filebrowser_entity_type_build(array &$entity_types) {

  /** @var $entity_types \Drupal\Core\Entity\EntityTypeInterface[] */
  $entity_types['node']
    ->setFormClass('filebrowser_outline', 'Drupal\\filebrowser\\FilebrowserConfigForm');
}

/**
 * Implements hook_entity_extra_field_info().
 */
function filebrowser_entity_extra_field_info() {
  $extra = [];
  $extra['node']['dir_listing']['display']['filebrowser_file_list'] = [
    'label' => t('Filebrowser file listing'),
    'description' => t('Show file listing content part.'),
    'weight' => 100,
    'visible' => TRUE,
  ];
  $extra['node']['dir_listing']['display']['filebrowser_statistics'] = [
    'label' => t('Filebrowser statistics'),
    'description' => t('Show the statistics of this listing.'),
    'weight' => 100,
    'visible' => TRUE,
  ];
  return $extra;
}

/**
 * Whe can define the filebrowser fields for node dir_listing.
 * but for the time we won't use this. We will continue to use hook_form_alter due to the
 * the complexity of updating.
 *
 * Implements hook_form_BASE_FORM_ID_alter().
 * @param $form
 * @param FormStateInterface $form_state
 * @param $form_id
 */
function filebrowser_form_node_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

  /** @var NodeInterface $node */
  $node = $form_state
    ->getFormObject()
    ->getEntity();
  if ($node
    ->bundle() == 'dir_listing') {
    $form = \Drupal::service('filebrowser.manager')
      ->addFormExtraFields($form, $form_state, $node);
    $form['#entity_builders'][] = 'filebrowser_node_builder';
  }
}

/**
 * Entity form builder to add the filebrowser information to the node.
 * @param Entity\EntityTypeBundleInfo $entity_type
 * @param NodeInterface $entity
 * @param FormStateInterface $form_state
 * @param array $form
 *
 */
function filebrowser_node_builder($entity_type, NodeInterface $entity, &$form, FormStateInterface $form_state) {
  $entity->filebrowser = new Filebrowser($form_state
    ->getValue('filebrowser'));

  // Always save a revision for non-administrators.
  if (!empty($entity->filebrowser->nid) && !\Drupal::currentUser()
    ->hasPermission('administer nodes')) {

    // $entity->setNewRevision();
  }
}

/**
 * Implements hook_ENTITY_TYPE_prepare_form() for node entities.
 *
 * We will use this hook to set the extra filebrowser fields for
 * an existing node. For a new node the node Form will supply de defaults
 * @inheritdoc
 */
function filebrowser_node_prepare_form(NodeInterface $node, $operation, FormStateInterface $form_state) {
  if ($node
    ->getType() == 'dir_listing' && $operation == 'edit') {
    $node->filebrowser = new Filebrowser($node
      ->id());
  }
}

/**
 * Implements hook_ENTITY_TYPE_load().
 * @inheritdoc
 */
function filebrowser_node_load($nodes) {

  /** @var \Drupal\node\Entity\Node $node */
  foreach ($nodes as $nid => $node) {
    if ($node
      ->bundle() == 'dir_listing') {
      $node->filebrowser = new Filebrowser($nid);
    }
  }
}

/**
 * Implements hook_ENTITY_TYPE_insert().
 * @param Drupal\node\NodeInterface $node
 */
function filebrowser_node_insert(NodeInterface $node) {
  if ($node
    ->bundle() == 'dir_listing') {
    $node->filebrowser->nid = $node
      ->id();
    $manager = \Drupal::service('filebrowser.manager');
    $manager
      ->updateFilebrowser($node->filebrowser, 'insert');
  }
}

/**
 * Implements hook_ENTITY_TYPE_update() for node entities.
 * @var Drupal\node\NodeInterface $node
 */
function filebrowser_node_update(NodeInterface $node) {

  /** @var \Drupal\filebrowser\FilebrowserManager $manager */
  if ($node
    ->bundle() == 'dir_listing') {
    $node->filebrowser->nid = $node
      ->id();
    $manager = \Drupal::service('filebrowser.manager');

    //print_r($node->filebrowser);
    $manager
      ->updateFilebrowser($node->filebrowser, 'edit');

    // invalidate the cache for this node
    \Drupal\Core\Cache\Cache::invalidateTags([
      'filebrowser:node:' . $node
        ->id(),
    ]);
  }
}

/**
 * Implements hook_ENTITY_TYPE_predelete().
 * @inheritdoc
 */
function filebrowser_node_predelete(NodeInterface $node) {

  // delete information from filebrowser tables
  \Drupal::service('filebrowser.common')
    ->nodeDelete($node
    ->id());
}

/**
 * Deletes an Metadata entity when its provider node gets deleted
 *
 * Implements hook_entity_delete().
 * @inheritdoc
 */
function filebrowser_node_delete(NodeInterface $node) {
  if ($node
    ->bundle() == 'dir_listing') {

    // get all the entities for this node
    $query = \Drupal::entityQuery('filebrowser_metadata_entity')
      ->condition('nid', $node
      ->id(), '=');
    $ids = $query
      ->execute();
    $storage = \Drupal::entityTypeManager()
      ->getStorage('filebrowser_metadata_entity');
    $entities = $storage
      ->loadMultiple($ids);
    if ($entities) {
      foreach ($entities as $entity) {
        $entity
          ->delete();
      }
    }
  }
}

/**
 * Implements hook_ENTITY_TYPE_view().
 * @var array $current_view with view_type and theme function
 * @inheritdoc
 */
function filebrowser_node_view(array &$build, NodeInterface $node, EntityViewDisplayInterface $display, $view_mode) {

  /** @var \Drupal\filebrowser\FilebrowserManager $manager */

  /** @var \Drupal\filebrowser\Filebrowser $filebrowser*/
  if ($view_mode == 'full' && $node
    ->bundle() == 'dir_listing') {
    $manager = \Drupal::service('filebrowser.manager');

    // get the argument $fid from query
    $fid = \Drupal::request()->query
      ->get('fid');
    $list = new \Drupal\filebrowser\File\DisplayFileList($node, $fid);
    $display_list = $list
      ->get();

    // Show file listing content part
    if ($display
      ->getComponent('filebrowser_file_list')) {
      $contents = $manager
        ->createPresentation($node, $display_list);
      $build['filebrowser_file_list'] = $contents;
    }

    // Show the statistics of this listing
    if ($display
      ->getComponent('filebrowser_statistics')) {
      $statistics = new \Drupal\filebrowser\Statistics($display_list);
      $build['filebrowser_statistics'] = $statistics
        ->get();
    }

    // we will not use cache
    $build['#cache']['max-age'] = 0;
    \Drupal::service('page_cache_kill_switch')
      ->trigger();
  }
}

/**
 * Implements hook_node_access.
 * @inheritdoc
 */
function filebrowser_node_access(NodeInterface $node, $op, AccountInterface $account) {
  if ($node
    ->bundle() == 'dir_listing') {
    switch ($op) {
      case 'view':
        return AccessResult::forbiddenIf(!$account
          ->hasPermission(Common::VIEW_LISTINGS));
      case 'create':
        return AccessResult::forbiddenIf(!$account
          ->hasPermission(Common::CREATE_LISTING));
      case 'update':
        $has_permission = $account
          ->hasPermission(Common::EDIT_ANY_LISTINGS) || $account
          ->hasPermission(Common::EDIT_OWN_LISTINGS) && $account
          ->id() == $node
          ->getOwnerId();
        return AccessResult::forbiddenIf(!$has_permission);
      case 'delete':
        $has_permission = $account
          ->hasPermission(Common::DELETE_ANY_LISTINGS) || $account
          ->hasPermission(Common::DELETE_OWN_LISTINGS) && $account
          ->id() == $node
          ->getOwnerId();
        return AccessResult::forbiddenIf(!$has_permission);
      default:
        return AccessResult::neutral();
    }
  }
  else {
    return AccessResult::neutral();
  }
}

// todo
function filebrowser_node_operations() {
  $operations = [
    'filebrowser_thumbnails' => [
      'label' => t('Update filebrowser thumbnails'),
      'callback' => 'filebrowser_node_mass_update_thumbnails',
      'callback arguments' => [],
    ],
  ];
  return $operations;
}
function filebrowser_node_mass_update_thumbnails($nodes) {

  //  module_load_include("pages.inc", "filebrowser");
  //  foreach ($nodes as $nid) {
  //    $node = \Drupal::entityTypeManager()->getStorage('node')->load($nid);
  //    _filebrowser_load_files($node);
  //    $fids[]=$node->file_listing['.']['fid'];
  //  }
  //  filebrowser_update_thumbnails($fids);
}

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 * @inheritdoc
 */
function filebrowser_theme_suggestions_container_alter(array &$suggestions, array $variables) {
  if ($node = \Drupal::service('filebrowser.common')
    ->getNodeFromPath()) {
    if ($node
      ->bundle() == 'dir_listing') {
      if (!empty($variables['element']['#attributes']['class'])) {
        $classes = $variables['element']['#attributes']['class'];
        if (in_array(Common::FILEBROWSER_GRID_CONTAINER_CLASS, $classes)) {
          $suggestions = [
            'filebrowser_container',
          ];
        }
        if (in_array(Common::FILEBROWSER_GRID_CONTAINER_COLUMN_CLASS, $classes)) {
          $suggestions = [
            'filebrowser_container_column',
          ];
        }
      }
    }
  }
}

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 * @inheritdoc
 */

// Not used, left here for example
function filebrowser_theme_suggestions_form_element_alter(array &$suggestions, array $variables) {
  if ($node = \Drupal::service('filebrowser.common')
    ->getNodeFromPath()) {
    if ($node
      ->bundle() == 'dir_listing') {
      if (!empty($variables['element']['#attributes']['class'])) {
        $classes = $variables['element']['#attributes']['class'];
        if (in_array(Common::FILEBROWSER_GRID_ITEM_CLASS, $classes)) {
          $suggestions = [
            'filebrowser_form_element',
          ];
        }
      }
    }
  }
}

/**
 * Prepares variables for container templates.
 *
 * Default template: container.html.twig.
 *
 * @param array $variables
 *   An associative array containing:
 *   - element: An associative array containing the properties of the element.
 *     Properties used: #id, #attributes, #children.
 */
function template_preprocess_filebrowser_container_column(&$variables) {
  $variables['has_parent'] = FALSE;
  $element = $variables['element'];

  // Ensure #attributes is set.
  $element += [
    '#attributes' => [],
  ];

  // Special handling for form elements.
  if (isset($element['#array_parents'])) {

    // Assign an html ID.
    if (!isset($element['#attributes']['id'])) {
      $element['#attributes']['id'] = $element['#id'];
    }
    $variables['has_parent'] = TRUE;
  }
  $variables['children'] = $element['#children'];
  $variables['attributes'] = $element['#attributes'];

  // filebrowser:
  $variables['width'] = $variables['element']['#attributes']['width'];
}

Functions

Namesort descending Description
filebrowser_entity_extra_field_info Implements hook_entity_extra_field_info().
filebrowser_entity_type_build Implements hook_entity_type_build(). @inheritdoc
filebrowser_form_node_form_alter Whe can define the filebrowser fields for node dir_listing. but for the time we won't use this. We will continue to use hook_form_alter due to the the complexity of updating.
filebrowser_node_access Implements hook_node_access. @inheritdoc
filebrowser_node_builder Entity form builder to add the filebrowser information to the node.
filebrowser_node_delete Deletes an Metadata entity when its provider node gets deleted
filebrowser_node_insert Implements hook_ENTITY_TYPE_insert().
filebrowser_node_load Implements hook_ENTITY_TYPE_load(). @inheritdoc
filebrowser_node_mass_update_thumbnails
filebrowser_node_operations
filebrowser_node_predelete Implements hook_ENTITY_TYPE_predelete(). @inheritdoc
filebrowser_node_prepare_form Implements hook_ENTITY_TYPE_prepare_form() for node entities.
filebrowser_node_update Implements hook_ENTITY_TYPE_update() for node entities.
filebrowser_node_view Implements hook_ENTITY_TYPE_view(). @inheritdoc
filebrowser_theme Implements hook_theme().
filebrowser_theme_suggestions_container_alter Implements hook_theme_suggestions_HOOK_alter(). @inheritdoc
filebrowser_theme_suggestions_form_element_alter
template_preprocess_filebrowser_container_column Prepares variables for container templates.