You are here

function bynder_update_media_usage in Bynder 7

Updates the media usage entry in the database with the node information.

Parameters

$node:

2 calls to bynder_update_media_usage()
bynder_node_insert in ./bynder.module
Implements hook_node_insert().
bynder_node_update in ./bynder.module
Implements hook_node_update().

File

./bynder.module, line 231

Code

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);
        }
      }
    }
  }
}