bynder.browser.inc in Bynder 7
Manages the Bynder media browser functionality
File
includes/bynder.browser.incView source
<?php
/**
* @file
* Manages the Bynder media browser functionality
*/
const BYNDER_SEARCH_PAGE_SIZE = 10;
/**
* Create a form to add media from Bynder.
*/
function bynder_add($form, &$form_state = array()) {
$bynderApi = BynderMediaApi::getBynderApi();
$tokens = $bynderApi
->hasAccessToken();
if (!$bynderApi
->hasSettings()) {
$form['message'] = [
'#markup' => t('You haven\'t set up the <a href="' . url('admin/config/media/bynder', array(
'absolute' => true,
)) . '" class="oauth-link" target="_blank">Bynder settings</a> properly, please do so before importing assets.'),
'#prefix' => '<p>',
'#suffix' => '</p>',
];
}
elseif (!$tokens || isset($tokens['isRequestToken'])) {
$form['message'] = [
'#markup' => t('You need to <a href="' . url('bynder-oauth', array(
'absolute' => true,
)) . '" class="oauth-link" target="_blank">log into Bynder</a> before importing assets.'),
'#prefix' => '<p>',
'#suffix' => '</p>',
];
$form['reload'] = [
'#type' => 'button',
'#value' => 'Reload after submit',
'#attached' => [
'library' => [
'bynder/oauth',
],
],
'#attributes' => [
'class' => [
'oauth-reload',
'visually-hidden',
],
],
];
}
else {
$form['bynder_search'] = bynder_generate_search($form_state);
$form['submit'] = array(
'#type' => 'submit',
'#value' => 'Submit',
);
$form['#attached']['library'][] = array(
'bynder',
'bynder_administration',
);
$form['#attached']['css'][] = array(
'type' => 'external',
'data' => '//maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.css',
);
}
return $form;
}
function bynder_oauth_login() {
if (isset($_GET['oauth_token'])) {
BynderMediaApi::getBynderApi()
->finishOAuthTokenRetrieval();
return [
'#markup' => '<script>window.close()</script>',
'#allowed_tags' => [
'script',
],
];
}
elseif (isset($_GET['oauth_check_login'])) {
$tokens = BynderMediaApi::getBynderApi()
->hasAccessToken();
if ($tokens && !isset($tokens['isRequestToken'])) {
drupal_json_output(true);
}
elseif (isset($_SESSION['bynderLoginError'])) {
unset($_SESSION['bynderLoginError']);
drupal_set_message(t('There is something wrong with your Bynder configuration, please confirm the details
in @settings and try again', array(
'@settings' => url('admin/config/media/bynder', array(
'absolute' => true,
)),
)), 'error');
drupal_json_output(true);
}
else {
drupal_json_output(false);
}
}
else {
try {
$url = BynderMediaApi::getBynderApi()
->initiateOAuthTokenRetrieval();
drupal_goto($url);
} catch (Exception $e) {
$_SESSION['bynderLoginError'] = true;
return [
'#markup' => '<script>window.close()</script>',
'#allowed_tags' => [
'script',
],
];
}
}
}
function bynder_add_submit($form, &$form_state) {
if ($selected_assets = $form_state['values']['selected_assets']) {
$fids = array();
foreach ($selected_assets as $assetId => $selected) {
if ($selected) {
$result = bynder_save_image($assetId, $form);
if (isset($result['success'])) {
$fids[] = $result['fid'];
}
else {
drupal_set_message(t($result['message']), 'error');
}
}
}
// Save the files
if (!empty($fids)) {
if (current_path() != 'admin/content/media/add/bynder') {
drupal_goto('/media/browser', array(
'query' => array(
'render' => 'media-popup',
'fid' => $fids,
),
));
}
else {
drupal_set_message(t("Successfully added the selected assets."), 'status');
drupal_goto('admin/content/file');
}
}
}
drupal_set_message(t("Couldn't add any assets, please try again."), 'error');
}
function bynder_save_image($id, $form = null) {
try {
$transaction = db_transaction('bynder_save_image');
$selected_media = BynderMediaApi::getBynderApi()
->getObjectById($id);
if ($selected_media['type'] == 'image') {
$idHash = $selected_media['idHash'];
$uri = file_stream_wrapper_uri_normalize("bynder://f/{$id}/i/{$idHash}");
$file = file_uri_to_object($uri, TRUE);
$file->filemime = 'image/bynder';
$file->filesize = 0;
$file->filename = $selected_media['name'];
if (isset($file) && !property_exists($file, 'fid')) {
$file = file_save($file);
field_attach_submit('media', $file, $form, $form_state);
$file->file = [];
$file->file[LANGUAGE_NONE] = [];
$file->file[LANGUAGE_NONE][0] = (array) $file + [
'display' => TRUE,
];
$file->is_new = TRUE;
field_attach_insert('media', $file);
bynder_create_media_entry($selected_media, $idHash, $file->fid);
return [
'success' => 1,
'message' => t('Successfully added Bynder media item to Library'),
'fid' => $file->fid,
];
}
else {
bynder_create_media_usage_entry($selected_media, $file->fid);
return [
'success' => 1,
'message' => t('Bynder media item already exists in Library'),
'fid' => $file->fid,
];
}
}
} catch (Exception $e) {
$transaction
->rollback();
watchdog('bynder', $e
->getMessage());
}
return [
'message' => t("There was an unexpected error when trying to save the Bynder media item."),
];
}
function bynder_create_media_entry($selected_media, $idHash, $fid) {
// Save Bynder asset entry.
$name = $selected_media['name'];
$description = isset($selected_media['description']) ? $selected_media['description'] : '';
$derivatives = $selected_media['thumbnails'];
$schema = drupal_get_schema('bynder_media_entity');
if (isset($schema['fields']['description']['length'])) {
$maxlength = $schema['fields']['description']['length'];
}
$description = isset($maxlength) ? substr($description, 0, $maxlength) : $description;
$bynder_media_entity_id = db_insert('bynder_media_entity')
->fields(array(
'bynder_id' => $selected_media['id'],
'bynder_hash_id' => $idHash,
'name' => $name,
'description' => $description,
'derivatives' => serialize($derivatives),
'fid' => $fid,
))
->execute();
bynder_create_media_usage_entry($selected_media, $fid, $bynder_media_entity_id);
}
function bynder_create_media_usage_entry($selected_media, $fid, $entity_id = null) {
if (!isset($entity_id)) {
$entity = db_select('bynder_media_entity', 'b')
->fields('b', [
'id',
])
->condition('b.fid', $fid, '=')
->condition('b.bynder_id', $selected_media['id'], '=')
->execute()
->fetchAll();
if (!empty($entity)) {
$entity_id = $entity[0]->id;
}
else {
return null;
}
}
return db_insert('bynder_media_usage')
->fields(array(
'bynder_entity_id' => $entity_id,
'bynder_id' => $selected_media['id'],
'fid' => $fid,
'nid' => null,
))
->execute();
}
/**
* Generate search page.
*/
function bynder_generate_search($state) {
$meta_property_prefix = 'property_';
$data = array(
'#type' => 'fieldset',
);
$filter_labels = array(
'brandId' => t('Brands'),
'tags' => t('Tags'),
'type' => t('Type'),
'orientation' => t('Orientation'),
);
$meta_properties = BynderMediaApi::getBynderApi()
->getMetaProperties();
if (!empty($meta_properties)) {
foreach ($meta_properties as $meta_property) {
$filter_labels[$meta_property_prefix . $meta_property['name']] = $meta_property['label'];
foreach ($meta_property['options'] as $meta_property_option) {
$filter_labels[$meta_property_option['name']] = $meta_property_option['label'];
}
}
}
$search = bynder_search_string($state);
$filters = bynder_filters_json($state);
if (isset($_POST['filters'])) {
$filters = json_decode(filter_xss($_POST['filters']))->filters;
}
if (isset($_POST['source_filter'])) {
if ($_POST['source_filter'] == 'bynder_remove_all_facets_filter_key') {
$filters = array();
}
}
$selected_facets = bynder_selected_facets($state);
$results = bynder_search_results($search, $filters, $meta_properties, BYNDER_SEARCH_PAGE_SIZE);
$available_facets = $results['count'];
// Create search section
$data['search'] = array(
'#type' => 'fieldset',
'#title' => t('Search'),
'#collapsible' => false,
'#collapsed' => false,
'#attributes' => array(
'class' => array(
'bynder-search-form',
),
),
);
$data['search']['field'] = array(
'#type' => 'textfield',
'#default_value' => isset($search) ? $search : '',
'#description' => "<p class='alert alert-warning' style='display:none'><span class='text'></span></p>",
);
$data['search']['button'] = array(
'#type' => 'button',
'#value' => t('Search'),
'#submit' => array(
'bynder_add_test',
),
);
$data['selected_facets'] = bynder_generate_selected_facets($filters);
$data['facets'] = bynder_generate_facets($available_facets, $selected_facets);
$data['filters'] = array(
'#type' => 'hidden',
'#default_value' => json_encode($filters) != '[]' ? json_encode($filters) : '{"filters": []}',
);
$data['results'] = array(
'#type' => 'container',
'#attributes' => array(
'id' => array(
'results_list',
),
'class' => array(
'grid',
),
),
);
// Create the results section
$data['results'][] = bynder_generate_results($results);
if (isset($results['totalNrOfResults'])) {
$data['pager_container'] = array(
'#type' => 'container',
'#attributes' => array(
'class' => array(
'.js-form-type-entity-browser-pager',
),
),
);
$data['pager_container']['total_results'] = array(
'#type' => 'html_tag',
'#tag' => 'h3',
'#attributes' => array(
'class' => 'total_results',
),
'#value' => t('Total Results: ') . $results['totalNrOfResults'],
);
$data['pager_container']['pager'] = bynder_generate_pager($results['totalNrOfResults'], 0, array(
'search' => $search,
));
}
return $data;
}
/**
* Retrieve parameter from container.
*/
function bynder_parameter($container, $key, $default = null) {
if (isset($container[$key])) {
return $container[$key];
}
return $default;
}
/**
* Return entered search string.
*/
function bynder_search_string($state) {
$search = null;
if (isset($state['values']['field'])) {
$search = $state['values']['field'];
}
elseif (isset($_GET['search'])) {
$search = check_plain(filter_xss($_GET['search']));
}
return $search;
}
/**
* Return entered filters.
*/
function bynder_filters_json($state) {
$filters = array();
if (isset($state['values']['filters'])) {
$filters_json = json_decode($state['values']['filters']);
}
if (isset($filters_json->filters)) {
$filters = $filters_json->filters;
}
return $filters;
}
/**
* Return selected facets.
*/
function bynder_selected_facets($state) {
$selected_facets = array();
if (isset($state['values']['search'])) {
$selected_facets = array_merge($selected_facets, array(
"keyword" => (array) $state['values']['search'],
));
}
if (isset($state['values']['filters'])) {
$filters_json = json_decode($state['values']['filters']);
$filters = $filters_json->filters;
foreach ($filters as $filter) {
$selected_facets = array_merge($selected_facets, array(
$filter->key => $filter->value,
));
}
}
return $selected_facets;
}
/**
* Search with selected facets and a search term.
*/
function bynder_search_facets($selected_facets, $search_term) {
$query = array();
foreach ($selected_facets as $selected_facet_group_name => $selected_facet_group) {
$query[$selected_facet_group_name] = implode(",", $selected_facet_group);
}
if (isset($search) && strlen($search) > 0) {
$query['keyword'] = urlencode($search_term);
}
$query['count'] = 1;
// Hardcoding this now cause we only support images at the moment.
$query['type'] = 'image';
$bynderApi = bynder_init_api();
$assetBank = $bynderApi
->getAssetBankManager();
$assets = $assetBank
->getMediaList($query)
->wait();
$arr_facets_json = $assets['count'];
if ($arr_facets_json) {
return $arr_facets_json;
}
else {
drupal_set_message("Error fetching media", 'error');
return false;
}
}
/**
* Parse the selected facets.
*/
function bynder_parse_selected_facets($selected_facets) {
if (!$selected_facets) {
return false;
}
if (!empty($selected_facets)) {
$selected_facet_list = array(
'#theme' => 'item_list',
'#type' => 'ul',
'#title' => t('Selected Filters'),
'#attributes' => array(
'class' => 'selected_facet_list',
),
);
foreach ($selected_facets as $facet_category => $facets) {
foreach ($facets as $facet) {
$selected_facet_list['#items'][] = $facet_category . ' => ' . $facet;
}
}
return $selected_facet_list;
}
return false;
}
function bynder_generate_selected_facets($selected_facets) {
global $filter_labels;
if (empty($selected_facets)) {
return array();
}
$facets_list = array(
'#theme' => 'item_list',
'#type' => 'ul',
'#title' => t('Selected Filters'),
'#attributes' => array(
'class' => 'selected_facet_list facet_list',
),
);
foreach ($selected_facets as $selected_facet) {
$selected_facet_key = $selected_facet->key;
$selected_facet_value = $selected_facet->value;
$facet_name = $selected_facet_value;
if (!isset($filter_labels[$selected_facet_key])) {
$filter_labels[$selected_facet_key] = t($selected_facet_key);
}
$facet_category = array(
'data' => "<span>" . filter_xss($facet_name) . "<span class='expand'><i class='fa fa-times'></i></span></span>",
'class' => array(
'facet_title',
),
'data-filter-key' => filter_xss($selected_facet->key),
);
$facets_list['#items'][] = $facet_category;
}
$facet_remove_all = array(
'data' => "<span id='clear-all'>Clear filters<span class='expand'></span></span>",
'class' => array(
'facet_title',
),
'data-filter-key' => 'bynder_remove_all_facets_filter_key',
);
$facets_list['#items'][] = $facet_remove_all;
return $facets_list;
}
/**
* Generate facets.
*/
function bynder_generate_facets($facets, $selected_facets) {
global $filter_labels;
if (empty($facets)) {
return array();
}
$facets_list = array(
'#theme' => 'item_list',
'#type' => 'ul',
'#title' => t('Filters'),
'#prefix' => '<div class="normal-facet-list-wrapper">',
'#suffix' => '</div>',
'#attributes' => array(
'class' => 'normal_facet_list facet_list',
),
);
foreach ($facets as $facet_category_name => $facet_category) {
if ($facet_category_name == 'type' || $facet_category_name == 'categoryId' || $facet_category_name == 'subBrandId') {
continue;
}
//Hide single item filters.
if (count($facet_category) < 2) {
continue;
}
if (!isset($filter_labels[$facet_category_name])) {
$filter_labels[$facet_category_name] = t($facet_category_name);
}
$icons = array(
'brandId' => 'archive',
'tags' => 'tags',
'type' => 'file',
'orientation' => 'image',
);
$children = bynder_generate_facets_link($facet_category, $facet_category_name, $selected_facets);
$facet_category = array(
'data' => "<span><i class='fa fa-" . filter_xss(isset($icons[$facet_category_name]) ? $icons[$facet_category_name] : 'caret-right') . "'></i> " . filter_xss($filter_labels[$facet_category_name]) . "<span class='expand'><i class='fa fa-angle-down'></i></span></span>",
'id' => preg_replace('/\\s+/', '-', $facet_category_name),
'class' => array(
'facet_title',
),
'children' => $children,
);
if (count($children)) {
$facets_list['#items'][] = $facet_category;
}
}
return $facets_list;
}
/**
* Generate links for facets.
*/
function bynder_generate_facets_link($facet_category, $facet_category_name, $selected_facets) {
global $filter_labels;
$facet_links = array();
foreach ($facet_category as $facet_id => $facet_count) {
$facet_name = $facet_id;
if (!isset($filter_labels[$facet_name])) {
$filter_labels[$facet_name] = $facet_name;
}
$filter_key = $facet_category_name;
$filter_value = $facet_id;
$active = bynder_facet_active($selected_facets, array(
$facet_category_name => array(
$facet_id,
),
));
$active_class = $active ? "active" : "";
$link = "";
$link .= '<a class="filter-url ' . filter_xss($active_class) . '" href="#" data-filter-key="' . filter_xss($filter_key) . '" data-filter-value="' . filter_xss($filter_value) . '">' . filter_xss($filter_labels[$facet_name]) . '</a>';
$link .= '<span class="count">(' . filter_xss($facet_count) . ')</span>';
$facet_links[] = $link;
}
return $facet_links;
}
function bynder_query_facet_link($facet, $facet_value, $selected_facets, $deactivate = false) {
if (!$deactivate) {
$selected_facets = array_merge_recursive(array(
$facet => array(
$facet_value,
),
), $selected_facets);
}
else {
if (isset($selected_facets[$facet])) {
$selected_facets[$facet] = array_diff(explode(',', $selected_facets[$facet][0]), array(
$facet_value,
));
}
}
$csv_facets = array();
foreach (array_filter($selected_facets) as $selected_facet_key => $selected_facet) {
$csv_facets[$selected_facet_key] = implode(',', $selected_facet);
}
$value = http_build_query($csv_facets);
return $value;
}
function bynder_facet_active($selected_facets, $current_facet) {
if (isset($selected_facets[key($current_facet)])) {
return in_array($current_facet[key($current_facet)][0], explode(',', $selected_facets[key($current_facet)][0]));
}
else {
return false;
}
}
/**
* Parse the facet link.
*/
function bynder_parse_facet_link($query) {
$pattern = '/\\+\\([A-Za-z0-9 ]*\\)/';
preg_match($pattern, $query, $matches);
$query = urlencode($query);
if (!empty($matches)) {
$query = $query . '&search=' . substr(trim($matches[0]), 2, -1);
}
return $query;
}
function bynder_remove_hidden_facets($available_facets, $selected_facets) {
foreach ($selected_facets as $selected_facet_key => $selected_facet) {
$value = $selected_facet[0];
$isset = isset($available_facets[$selected_facet_key][$value]);
if (!$isset) {
unset($selected_facets[$selected_facet_key]);
}
}
return $selected_facets;
}
/**
* Perform the search.
*
* @param unknown $search
* the query entered.
* @param unknown $selected_facets
* the selected facets.
*
* @return mixed
* the search results.
*/
function bynder_search_results($search, $selected_facets, $meta_properties, $nr_of_results = 5) {
$start_index = 0;
$query = array();
if (isset($_GET['page'])) {
$current_page = (int) filter_xss($_GET['page']);
$current_page += 1;
$start_index = $current_page * $nr_of_results;
}
$selected_facets_meta_properties = [];
foreach ($meta_properties as $meta_property) {
foreach ($meta_property['options'] as $meta_property_option) {
$selected_facets_meta_properties[$meta_property['name']][$meta_property_option['name']] = $meta_property_option['id'];
}
}
if (isset($selected_facets)) {
foreach ($selected_facets as $facet) {
$facets = $facet->value;
$facet_category = $facet->key;
if (isset($selected_facets_meta_properties[$facet_category])) {
$meta_facets = [];
foreach (explode(',', $facets[0]) as $facet) {
$meta_facets[] = $selected_facets_meta_properties[$facet_category][$facet];
}
$query['propertyOptionId'] = implode(',', $meta_facets);
}
else {
$query[$facet_category] = $facets;
}
}
}
if (isset($search) && strlen($search) > 0) {
$query['keyword'] = urlencode($search);
}
$page = 1;
if (isset($start_index) && $start_index > 0) {
$page = $start_index / $nr_of_results;
}
$query = $query + array(
'page' => $page,
'limit' => $nr_of_results,
'count' => 1,
);
$query['type'] = 'image';
$result = BynderMediaApi::getBynderApi()
->getMediaList($query);
if ($result) {
if (isset($result['count']['total'])) {
$result['totalNrOfResults'] = $result['count']['total'];
}
}
else {
drupal_set_message(t('Could not retrieve search results:') . filter_xss($result->error), 'error');
return false;
}
return $result;
}
/**
* Organize results from search engine to visualize them.
*/
function bynder_generate_results($results) {
if (isset($results['totalNrOfResults'])) {
unset($results['totalNrOfResults']);
}
if (isset($results['startIndex'])) {
unset($results['startIndex']);
}
$results = $results['media'];
$output = false;
if (!empty($results)) {
foreach ($results as $key => $media_item) {
if (isset($media_item['thumbnails']['thul'])) {
if (!isset($media_item['idHash'])) {
return "image has no idHash";
}
$output['thumbnail-' . $media_item['id']] = array(
'#type' => 'container',
'#attributes' => array(
'id' => $media_item['id'],
'class' => array(
'grid-item',
),
),
);
$output['thumbnail-' . $media_item['id']]['check_' . $media_item['id']] = array(
'#type' => 'checkbox',
'#parents' => array(
'selected_assets',
$media_item['id'],
),
'#attributes' => array(
'class' => [
'item-selector',
],
),
);
$output['thumbnail-' . $media_item['id']]['image'] = array(
'#name' => $media_item['name'],
'#type' => 'markup',
'#markup' => '<img src="' . $media_item['thumbnails']['thul'] . '" alt="' . $media_item['name'] . '"/>
<div class="more-info">
<h4 class="name">' . $media_item['name'] . '</h4>
</div>',
);
}
}
}
else {
return false;
}
return $output;
}
/**
* Show search result.
*/
function bynder_generate_result_current($media_item) {
return l('
<div class="image-holder">
<img src="' . $media_item['thumbnails']['thul'] . '"/>
</div>
<span class="media_object_type_' . $media_item['type'] . '">' . t($media_item['name']) . '</span>', 'admin/content/media/add/bynder/', array(
'attributes' => array(
'class' => 'bynder-image',
'rel' => $media_item['id'],
'data-id' => $media_item['id'],
'data-idHash' => $media_item['idHash'],
),
'html' => true,
'query' => array(
'id' => $media_item['id'],
'idHash' => $media_item['idHash'],
),
));
}
/**
* Generate paging functionality.
*/
function bynder_generate_pager($num_results, $element = 0, $parameters = array()) {
if (isset($_POST['search'])) {
$_GET['search'] = filter_xss(check_plain($_POST['search']));
}
pager_default_initialize($num_results, BYNDER_SEARCH_PAGE_SIZE, $element);
return array(
'#markup' => theme('pager', array(
'parameters' => $parameters,
'element' => $element,
)),
);
}
Functions
Constants
Name | Description |
---|---|
BYNDER_SEARCH_PAGE_SIZE | @file Manages the Bynder media browser functionality |