You are here

bynder.utils.inc in Bynder 7

utility functions for the bynder module

File

includes/bynder.utils.inc
View source
<?php

/**
 * @file
 * utility functions for the bynder module
 */

/**
 * Create the embed url for a fragment.
 *
 * @param string $fragment_id idHash of entity.
 * @param string $type web, mini, thul
 * @param array $type effect
 * @todo add support for type and effect
 */
function bynder_embed_url($idHash, $filename, $imageStyle = false) {
  $bynderEntity = db_select('bynder_media_entity', 'b')
    ->fields('b')
    ->condition('b.bynder_hash_id', $idHash, '=')
    ->execute()
    ->fetchAll();
  if (!empty($bynderEntity)) {
    $bynderStyles = unserialize(variable_get('bynder_derivatives'));
    $imageDerivatives = unserialize($bynderEntity[0]->derivatives);
    $styleName = str_replace('bynder_', '', $imageStyle);

    // Process custom Bynder derivatives
    if (in_array($styleName, $bynderStyles)) {
      if (isset($imageDerivatives[$styleName])) {
        return $imageDerivatives[$styleName];
      }
    }
    else {
      $imageStyles = image_styles();
      $effects = isset($imageStyles[$imageStyle]['effects']) ? $imageStyles[$imageStyle]['effects'] : false;
      if ($effects) {
        foreach ($effects as $effect) {

          // We return straightaway because we only support one at the time.
          if ($effect['effect callback'] == 'bynder_custom_resolution_effect') {
            $derivativeUrl = customResolutionUrl($idHash, $effect);
            if ($derivativeUrl != 'pending' && $derivativeUrl !== false) {
              return $derivativeUrl;
            }
            elseif (user_access('administer media bynder')) {
              if ($derivativeUrl == 'pending') {
                drupal_set_message(t('The image style: @imageStyle for image @filename is being
                                    generated. The next time you refresh the page it should return the correct image style.', array(
                  '@imageStyle' => $imageStyles[$imageStyle]['label'],
                  '@filename' => $filename,
                )), 'warning');
              }
              else {
                drupal_set_message(t('Unable to generate image style: @imageStyle for image @filename.
                                    Make sure this asset is set to "Public" and the custom derivative is properly set up in your Bynder portal
                                    and try again.', array(
                  '@imageStyle' => $imageStyles[$imageStyle]['label'],
                  '@filename' => $filename,
                )), 'warning');
              }
            }
          }
        }
      }
    }

    // Check if we have the webimage default derivative for that image.
    if (isset($imageDerivatives['webimage'])) {
      drupal_set_message(t('No valid image style found for image @filename, it has been defaulted to the original image style.', array(
        '@filename' => $filename,
      )), 'warning');
      return $imageDerivatives['webimage'];
    }
  }
  drupal_set_message(t('No valid image style found for image @filename, please check your configuration.', array(
    '@filename' => $filename,
  )), 'warning');

  // If everything else fails we default to image not found.
  return $GLOBALS['base_url'] . '/' . drupal_get_path('module', 'bynder') . '/assets/no-image.png';
}
function sync_old_bynder_media($adminForm = false) {
  try {
    if (BynderMediaApi::hasSettings() || $adminForm) {
      $bynderFiles = load_files_by_filemime('image/bynder');
      foreach ($bynderFiles as $key => $file) {
        preg_match('/bynder:\\/\\/f\\/([^:\\/\\s]+)\\/i\\/(.*)?(#[\\w\\-]+)?$/', $file->uri, $matches);
        $id = $matches[1];
        $idHash = $matches[2];
        $selectedMedia = BynderMediaApi::getBynderApi()
          ->getObjectById($id);
        if ($selectedMedia) {
          bynder_create_media_entry($selectedMedia, $idHash, $file->fid);
        }
        else {
          drupal_set_message(t('Couldn\'t sync file @uri', array(
            '@uri' => $file->filename,
          )), 'warning');
        }
      }
    }
  } catch (Exception $e) {
    drupal_set_message(t("There was an error while syncing old Bynder media."), 'error');
    watchdog('bynder', $e
      ->getMessage());
    $context['finished'] = 1;
  }
}
function isValid($type, $val) {
  switch ($type) {
    case "uuid":
      return preg_match("/^[0-9a-fA-F]{8}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{12}\$/", $val);
    case "idHash":
      return preg_match("/[a-f0-9]{16}/", $val);
    case "bynder_drupal_url":
      return preg_match("/.*?(cloudfront\\.net\\/media).*?(" . variable_get('bynder_custom_derivative') . ")/", $val);
    case "id":
      return preg_match("/^[0-9a-f]{16}\$/", $val);
  }
  return true;
}
function validateId($str) {
  if (isValid('id', $str)) {
    return $str;
  }
  else {
    error_log("Invalid ID: " . $str);
    return false;
  }
}
function validateUUID($str) {
  if (isValid("uuid", $str)) {
    return $str;
  }
  else {
    error_log("Invalid UUID: " . $str);
    return false;
  }
}
function validateIdHash($str) {
  if (isValid('idHash', $str)) {
    return $str;
  }
  else {
    error_log("Invalid IDHash: " . $str);
    return false;
  }
}
function validateBynderDrupalUrl($url) {
  try {
    $reqHeaders = BynderMediaApi::getBynderApi()
      ->genericRequest($url);
    if ($reqHeaders
      ->getStatusCode() == '302' && isValid('bynder_drupal_url', reset($reqHeaders
      ->getHeaders()['Location']))) {
      return $url;
    }
    elseif ($reqHeaders
      ->getStatusCode() == '202') {
      return 'pending';
    }
  } catch (Exception $e) {
    watchdog('bynder', $e
      ->getMessage());
  }
  return false;
}
function customResolutionUrl($idHash, $effect) {
  $bynder_url = variable_get('bynder_cdn_url', false);
  if (!$bynder_url) {
    $bynder_url = variable_get('bynder_url', '');
  }
  $url = $bynder_url . '/images/media/' . $idHash . '/derivatives/' . variable_get('bynder_custom_derivative') . '?w=' . $effect['data']['width'] . '&h=' . $effect['data']['height'];
  $effectName = str_replace('bynder_custom_resolution_', '', $effect['name']);
  switch ($effectName) {
    case 'crop':
    case 'extent':
      $url .= '&' . $effectName . '=1';
      break;
  }
  return validateBynderDrupalUrl($url);
}
function load_files_by_filemime($filemime) {
  $query = db_select('file_managed', 'f')
    ->fields('f')
    ->condition('f.filemime', $filemime);

  // Load all file ids in an array.
  $fids = $query
    ->execute()
    ->fetchCol();

  // Return the file objects.
  return file_load_multiple($fids);
}