You are here

bynder.module in Bynder 7

Same filename and directory in other branches
  1. 8.3 bynder.module
  2. 8 bynder.module
  3. 8.2 bynder.module
  4. 4.0.x bynder.module

File

bynder.module
View source
<?php

require_once dirname(__FILE__) . '/includes/bynder.browser.inc';
require_once dirname(__FILE__) . '/includes/bynder_upload.inc';
require_once dirname(__FILE__) . '/includes/bynder.utils.inc';
require_once dirname(__FILE__) . '/includes/bynder.formatters.inc';
require_once dirname(__FILE__) . '/includes/bynder.admin.inc';

/**
 * Implements hook_stream_wrappers().
 */
function bynder_stream_wrappers() {
  return array(
    'bynder' => array(
      'name' => t('Bynder media'),
      'class' => 'BynderMediaStreamWrapper',
      'description' => t('Media provided by Bynder.'),
      'type' => STREAM_WRAPPERS_READ_VISIBLE | STREAM_WRAPPERS_WRITE_VISIBLE,
    ),
  );
}

/**
 * Implements hook_media_browser_plugin_info().
 */
function bynder_media_browser_plugin_info() {
  $info['bynder'] = array(
    'title' => t('Bynder'),
    'class' => 'BynderMediaBrowser',
    'weight' => -100,
  );
  $info['bynder_upload'] = array(
    'title' => t('Bynder Upload'),
    'class' => 'BynderMediaUpload',
    'weight' => -99,
  );
  return $info;
}

/**
 * Implements hook_help().
 *
 * Displays help and module information.
 */
function bynder_help($path, $arg) {
  switch ($path) {
    case "admin/advanced_help#bynder":
      return '<p>' . t("Links to Bynder configuration pages.") . '</p>';
    case "admin/help#bynder":
      return '<p>' . t("Links to Bynder configuration pages.") . '</p>';
  }
}

/**
 * Implements hook_permission().
 */
function bynder_permission() {
  return array(
    'administer media bynder' => array(
      'title' => t('Administer Media: Bynder'),
      'description' => t('Configure Bynder API connection settings.'),
    ),
  );
}

/**
 * Implements hook_menu().
 */
function bynder_menu() {
  $items = array();
  $items['admin/config/media/bynder'] = array(
    'title' => 'Bynder Settings',
    'description' => 'Configuration for media bynder module',
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'bynder_form',
    ),
    'access arguments' => array(
      'administer media bynder',
    ),
    'file' => 'includes/bynder.admin.inc',
    'type' => MENU_NORMAL_ITEM,
  );
  $items['bynder-oauth'] = array(
    'title' => 'Init oauth authentication',
    'description' => 'Init oauth authentication',
    'page callback' => 'bynder_oauth_login',
    'access arguments' => array(
      'administer media bynder',
    ),
    'type' => MENU_NORMAL_ITEM,
  );
  $items['media/add/bynder'] = array(
    'title' => 'Add media from Bynder',
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'bynder_add',
    ),
    'access arguments' => array(
      'administer media bynder',
    ),
    'type' => MENU_LOCAL_ACTION,
    'file' => 'includes/bynder.admin.inc',
  );
  $items['admin/content/media/add/bynder'] = $items['media/add/bynder'];
  $items['admin/content/media/add/bynder/upload'] = array(
    'title' => 'Upload assets to Bynder',
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'bynder_upload',
    ),
    'access arguments' => array(
      'administer media bynder',
    ),
    'type' => MENU_LOCAL_ACTION,
  );
  $items['bynder/upload/process'] = array(
    'title' => 'Process uploaded files',
    'page callback' => 'bynder_upload_process_files',
    'access arguments' => array(
      'administer media bynder',
    ),
    'type' => MENU_LOCAL_ACTION,
  );
  return $items;
}

/**
 * Implements hook_library().
 */
function bynder_library() {
  $path = drupal_get_path('module', 'bynder');
  $info = system_get_info('module', 'bynder');
  $common = array(
    'website' => 'http://www.bynder.com',
    'version' => !empty($info['version']) ? $info['version'] : '7.x-1.x',
  );

  // Powers the 'Add media from Bynder' page.
  $libraries['bynder_administration'] = array(
    'title' => 'Media: Bynder Administration',
    'js' => array(
      $path . '/js/bynder.js' => array(
        'group' => JS_LIBRARY,
        'weight' => -5,
      ),
      $path . '/js/masonry.min.js' => array(
        'group' => JS_LIBRARY,
        'weight' => -5,
      ),
      $path . '/js/imagesloaded.min.js' => array(
        'group' => JS_LIBRARY,
        'weight' => -5,
      ),
    ),
    'dependencies' => array(
      array(
        'bynder',
        'spin',
      ),
    ),
  );

  // Generates animated CSS3 loading spinners.
  $libraries['spin'] = array(
    'title' => 'Spin',
    'js' => array(
      $path . '/js/spin.min.js' => array(
        'group' => JS_DEFAULT,
      ),
    ),
  );

  // Powers the 'Add media from Bynder' page.
  $libraries['media_dropzone'] = array(
    'title' => 'Media: Upload dropzone',
    'js' => array(
      $path . '/js/bynder_dropzone.js' => array(
        'group' => JS_LIBRARY,
        'weight' => -5,
      ),
      $path . '/js/dropzone/dropzone.min.js' => array(
        'group' => JS_LIBRARY,
        'weight' => -5,
      ),
    ),
    'css' => array(
      $path . '/js/dropzone/dropzone.min.css' => array(),
    ),
  );

  // Add common information to each library.
  foreach ($libraries as &$library) {
    $library += $common;
  }
  return $libraries;
}

/**
 * Implements hook_node_insert().
 */
function bynder_node_insert($node) {
  bynder_update_media_usage($node);
}

/**
 * Implements hook_node_update().
 */
function bynder_node_update($node) {
  bynder_update_media_usage($node);
}

/**
 * Updates the media usage entry in the database with the node information.
 *
 * @param $node
 */
function bynder_update_media_usage($node) {
  $item = array(
    $node,
  );
  foreach ($item[0] as $field => $value) {
    if (is_array($value) && substr($field, 0, 5) == 'field') {
      $language = isset($node->language) ? $node->language : LANGUAGE_NONE;
      $fileEntries = $value[$language];
      $oldEntries = !$item[0]->is_new && !empty($item[0]->original->{$field}) ? $item[0]->original->{$field}[$language] : [];
      foreach ($fileEntries as $file) {
        if (isset($file['fid'])) {
          $fid = $file['fid'];
          $toUpdate = true;
          if (!$item[0]->is_new) {
            foreach ($oldEntries as $key => $oldEntry) {
              if ($fid == $oldEntry['fid']) {
                $toUpdate = false;
                unset($oldEntries[$key]);
                break;
              }
            }
          }
          if ($toUpdate) {
            $mediaUsageEntryQuery = db_select('bynder_media_usage', 'b')
              ->fields('b')
              ->condition('b.fid', $fid, '=')
              ->isNull('b.nid');
            $mediaUsageEntry = $mediaUsageEntryQuery
              ->execute()
              ->fetchAll();
            if (!empty($mediaUsageEntry)) {
              $nodeUri = drupal_get_path_alias('node/' . $node->nid);
              try {
                $usageEntryId = $mediaUsageEntry[0]->id;
                $usageUrl = url($nodeUri, [
                  'fragment' => $node->nid,
                  'absolute' => TRUE,
                ]);

                // Add asset media usage.
                $mediaUsage = BynderMediaApi::getBynderApi()
                  ->addAssetUsage($mediaUsageEntry[0]->bynder_id, $usageUrl, $node->title);
                if ($mediaUsage) {
                  db_merge('bynder_media_usage')
                    ->key([
                    'id' => $usageEntryId,
                  ])
                    ->fields([
                    'nid' => $node->nid,
                    'processed' => 1,
                    'uri' => $usageUrl,
                    'title' => $node->title,
                  ])
                    ->execute();
                }
              } catch (Exception $e) {
                drupal_set_message(t('An error ocurred when creating asset usage entry.'), 'error');
                watchdog('bynder', $e
                  ->getMessage());
              }
            }
          }
        }
      }
      if (!empty($oldEntries)) {
        foreach ($oldEntries as $oldEntry) {
          bynder_delete_asset_usage_information($oldEntry['fid'], $node->nid);
        }
      }
    }
  }
}

/**
 * Implements hook_node_delete().
 */
function bynder_node_delete($node) {
  $language = isset($node->language) ? $node->language : LANGUAGE_NONE;
  $item = array(
    $node,
  );
  foreach ($item['0'] as $field => $value) {
    if (is_array($value) && substr($field, 0, 5) == 'field') {
      foreach ($value[$language] as $newFile) {
        if (isset($newFile['fid'])) {
          bynder_delete_asset_usage_information($newFile['fid'], $node->nid);
        }
      }
    }
  }
}

/**
 * Implements hook_file_delete().
 */
function bynder_file_delete($file) {
  if ($file->type == 'image' && $file->filemime == 'image/bynder') {
    try {
      db_delete('bynder_media_entity')
        ->condition('fid', $file->fid)
        ->execute();
      bynder_delete_asset_usage_information($file->fid);
      drupal_set_message(t('Bynder Media assets linked to the deleted files were also removed from the associated pages.'), 'status', FALSE);
    } catch (Exception $e) {
      drupal_set_message(t('An error ocurred when deleting the Bynder information for file with id @file_id.', [
        '@file_id' => $file->fid,
      ]), 'error');
      watchdog('bynder', $e
        ->getMessage());
    }
  }
}

/**
 * Deletes asset usage information from Bynder.
 *
 * @param $fid
 * @param null $nid
 */
function bynder_delete_asset_usage_information($fid, $nid = null) {
  try {
    $mediaUsageEntryQuery = db_select('bynder_media_usage', 'b')
      ->fields('b')
      ->condition('b.fid', $fid, '=');
    if (isset($nid)) {
      $mediaUsageEntryQuery
        ->condition('nid', $nid);
    }
    $mediaUsageEntry = $mediaUsageEntryQuery
      ->execute()
      ->fetchAll();
    if (!empty($mediaUsageEntry)) {
      $delete_query = db_delete('bynder_media_usage')
        ->condition('fid', $fid);
      $usage_url = '';
      if (isset($nid)) {
        $usageEntryId = $mediaUsageEntry[0]->id;
        $nodeUri = drupal_get_path_alias("node/" . $nid);
        $usage_url = url($nodeUri, [
          'fragment' => $usageEntryId,
          'absolute' => true,
        ]);
        $delete_query
          ->condition('nid', $nid)
          ->condition('uri', $usage_url);
      }
      $delete_query
        ->execute();
      BynderMediaApi::getBynderApi()
        ->removeAssetUsage($mediaUsageEntry[0]->bynder_id, $usage_url);
    }
  } catch (Exception $e) {
    drupal_set_message(t('An error ocurred when deleting the asset usage entry for file with id @file_id.', [
      '@file_id' => $fid,
    ]), 'error');
    watchdog('bynder', $e
      ->getMessage());
  }
}

/**
 * Implements hook_file_update().
 */
function bynder_file_update($file) {
  if ($file->type == 'image' && isset($file->original) && $file->original->filemime == 'image/bynder') {
    try {
      db_merge('file_managed')
        ->key([
        'fid' => $file->fid,
      ])
        ->fields([
        'filemime' => 'image/bynder',
      ])
        ->execute();
      if ($file->filename !== $file->original->filename) {
        $usageEntities = db_select('bynder_media_entity', 'b')
          ->fields('b')
          ->condition('b.fid', $file->fid, '=')
          ->execute();
        foreach ($usageEntities as $usageEntity) {
          db_merge('bynder_media_entity')
            ->key([
            'id' => $usageEntity->id,
          ])
            ->fields([
            'name' => $file->filename,
          ])
            ->execute();
        }
      }
    } catch (Exception $e) {
      drupal_set_message(t("There was an error updating the Bynder file with id: @file_id", [
        '@file_id' => $file->fid,
      ]), FALSE);
      watchdog('bynder', $e
        ->getMessage());
    }
  }
}

/**
 * Auxiliary function ran during cron to update all media usage information.
 */
function bynder_update_media_usage_information() {
  $mediaUsageEntryQuery = db_select('bynder_media_usage', 'b')
    ->fields('b')
    ->isNotNull('b.nid');
  $mediaUsageEntries = $mediaUsageEntryQuery
    ->execute()
    ->fetchAll();
  if (!empty($mediaUsageEntries)) {
    foreach ($mediaUsageEntries as $media) {
      $nid = $media->nid;
      $mediaId = $media->bynder_id;
      $nodeUri = url(drupal_get_path_alias("node/{$nid}"));
      $usageUrl = url($nodeUri, [
        'fragment' => $nid,
        'absolute' => TRUE,
      ]);
      try {
        $usages = BynderMediaApi::getBynderApi()
          ->getAssetUsages($mediaId);
        foreach ($usages as $usage_info) {
          $old_usage_url = $usage_info['uri'];
          $url_parts = explode('#', $old_usage_url);
          $node_info = isset($url_parts[1]) ? $url_parts[1] : null;
          if ($node_info == $nid && $usage_info['uri'] !== $usageUrl && $usage_info['integration']['id'] && BynderMediaApi::getIntegrationId()) {
            BynderMediaApi::getBynderApi()
              ->removeAssetUsage($mediaId, $usage_info['uri']);
            BynderMediaApi::getBynderApi()
              ->addAssetUsage($mediaId, $usageUrl, $usage_info['additional'], $usage_info['timestamp']);
          }
        }
      } catch (\Exception $exception) {
        watchdog('bynder', $exception
          ->getMessage());
      }
    }
  }
}

/**
 * Implements hook_cron().
 */
function bynder_cron() {
  bynder_update_media_usage_information();
}

/**
 * Implements hook_flush_caches().
 */
function bynder_flush_caches() {
  return array(
    'cache_bynder',
  );
}

Functions

Namesort descending Description
bynder_cron Implements hook_cron().
bynder_delete_asset_usage_information Deletes asset usage information from Bynder.
bynder_file_delete Implements hook_file_delete().
bynder_file_update Implements hook_file_update().
bynder_flush_caches Implements hook_flush_caches().
bynder_help Implements hook_help().
bynder_library Implements hook_library().
bynder_media_browser_plugin_info Implements hook_media_browser_plugin_info().
bynder_menu Implements hook_menu().
bynder_node_delete Implements hook_node_delete().
bynder_node_insert Implements hook_node_insert().
bynder_node_update Implements hook_node_update().
bynder_permission Implements hook_permission().
bynder_stream_wrappers Implements hook_stream_wrappers().
bynder_update_media_usage Updates the media usage entry in the database with the node information.
bynder_update_media_usage_information Auxiliary function ran during cron to update all media usage information.