You are here

bynder_upload.inc in Bynder 7

File

includes/bynder_upload.inc
View source
<?php

const BYNDER_MEDIA_UPLOAD_URL = 'admin/content/media/add/bynder/upload';
const BYNDER_SETTINGS_URL = 'admin/config/media/bynder';

/**
 * Create a form to add media from Bynder.
 */
function bynder_upload($form, &$form_state) {
  unset($_SESSION['bynder_upload_browser']);
  $bynderApi = BynderMediaApi::getBynderApi();
  $tokens = $bynderApi
    ->hasAccessToken();
  if (!$bynderApi
    ->hasSettings()) {
    $form['message'] = [
      '#markup' => t('You haven\'t set up the <a href="' . url(BYNDER_SETTINGS_URL, array(
        'absolute' => true,
      )) . '" class="oauth-link" target="_blank">Bynder settings</a> properly, please do so before importing assets.'),
      '#prefix' => '<p>',
      '#suffix' => '</p>',
    ];
  }
  elseif (!variable_get('bynder_brand_selected')) {
    $form['message'] = [
      '#markup' => t('You need to set up the brand associated to file uploads before you can use this functionality:
                <a href="' . url(BYNDER_SETTINGS_URL, array(
        'absolute' => true,
      )) . '" class="oauth-link" target="_blank">Bynder settings</a>.'),
      '#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 uploading assets.'),
      '#prefix' => '<p>',
      '#suffix' => '</p>',
    ];
    $form['reload'] = [
      '#type' => 'button',
      '#value' => 'Reload after submit',
      '#attributes' => [
        'class' => [
          'oauth-reload',
          'visually-hidden',
        ],
      ],
    ];
    $_SESSION['bynder_oauth_login'] = true;
  }
  elseif ($bynderApi
    ->hasUploadPermissions()) {
    $form['bynder_dropzone'] = array(
      '#type' => 'fieldset',
      '#attributes' => array(
        'class' => array(
          'dropzone',
        ),
      ),
    );
    $form['bynder_dropzone']['bynder_dropzone_url'] = array(
      '#type' => 'hidden',
      '#value' => url('bynder/upload/process', array(
        'absolute' => true,
      )),
      '#attributes' => array(
        'id' => 'bynder-dropzone-url',
      ),
    );
    $form_token = drupal_get_token('bynder_upload');
    $form['bynder_dropzone']['bynder_form_token'] = array(
      '#type' => 'hidden',
      '#attributes' => array(
        'class' => 'bynder-token',
      ),
      '#value' => $form_token,
    );
    $form['#attached']['library'][] = array(
      'bynder',
      'media_dropzone',
    );
    $form['#attributes'] = array(
      'class' => array(
        'dropzone-form',
      ),
    );
    $form['submit'] = array(
      '#type' => 'submit',
      '#value' => 'Submit',
      '#attributes' => array(
        'id' => array(
          'dropzone-submit',
        ),
      ),
    );
  }
  else {
    $form['message'] = [
      '#markup' => t("Your account doesn't have enough permissions to upload assets to Bynder"),
    ];
  }
  return $form;
}
function bynder_upload_process_files() {
  if (!empty($_FILES)) {
    if (isset($_POST['bynder_form_token'])) {
      $savedFiles = array();
      $folder = variable_get('file_default_scheme', 'public') . '://bynder_tmp/';
      file_prepare_directory($folder, FILE_CREATE_DIRECTORY);
      foreach ($_FILES['file']['name'] as $key => $file) {
        $source = $_FILES['file']['tmp_name'][$key];
        $destination = file_stream_wrapper_uri_normalize($folder . $_FILES['file']['name'][$key]);
        $uri = file_unmanaged_move($source, $destination, FILE_EXISTS_RENAME);
        $file = file_uri_to_object($uri);
        file_save($file);
        $savedFiles[] = $file;
      }
      $_SESSION[$_POST['bynder_form_token']] = $savedFiles;
      drupal_json_output(true);
    }
    else {
      drupal_json_output(false);
    }
  }
}
function bynder_upload_submit($form, &$form_state) {

  // We need to check whether this is the Media browser overlay or the page because for some reason the oauth login form
  // submits the upload form when returning from Bynder.
  if (!isset($_SESSION['bynder_oauth_login'])) {
    $files = $_SESSION[$form_state['values']['bynder_form_token']];
    if (isset($files)) {
      $batchOperations = array();
      $totalFiles = count($files);
      foreach ($files as $file) {
        $batchOperations[] = array(
          'bynder_upload_file_batch',
          array(
            $file,
          ),
        );
        $batchOperations[] = array(
          'bynder_upload_delete_tmp_files',
          array(),
        );
        $batchOperations[] = array(
          'bynder_upload_add_to_library',
          array(),
        );
      }
      $batch = array(
        'operations' => $batchOperations,
        'finished' => 'bynder_upload_file_batch_finished',
        'title' => t('Batch to upload files to Bynder'),
        'init_message' => t('Bynder upload process is starting...'),
        'progress_message' => t('Processed @current out of @totalFiles.', array(
          '@totalFiles' => $totalFiles,
        )),
        'error_message' => t('Import has encountered an error.'),
      );

      // If we're in a popup
      if (current_path() == BYNDER_MEDIA_UPLOAD_URL) {
        $_SESSION['bynder_upload_browser'] = 'library';
      }
      batch_set($batch);
    }
  }
  unset($_SESSION['bynder_oauth_login']);
}
function bynder_upload_file_batch($file, &$context) {

  // update message during each run so you know where you are in the process
  $context['message'] = 'Now processing image with name ' . $file->filename;
  $file = file_load($file->fid);
  $data = array(
    'filePath' => drupal_realpath($file->uri),
    'brandId' => variable_get('bynder_brand_selected'),
    'name' => $file->filename,
    'description' => 'Image description',
    'audit' => variable_get('bynder_upload_method') == 'upload' ? false : true,
  );
  $fileInfo = BynderMediaApi::getBynderApi()
    ->uploadFile($data);
  $context['results']['to_delete'] = $file;
  $context['results']['uploaded_file'] = $fileInfo;
}
function bynder_upload_delete_tmp_files(&$context) {
  if (isset($context['results']['to_delete'])) {
    $name = $context['results']['to_delete']->filename;
    file_delete($context['results']['to_delete']);
    $context['results']['files_done'][] = $name;
  }
}
function bynder_upload_add_to_library(&$context) {

  // We only try to save the file if it's not going to the waiting room.
  if (variable_get('bynder_upload_method') == 'upload') {
    $uploaded = false;
    for ($retries = 0; $retries < 10; $retries++) {
      $id = $context['results']['uploaded_file']['mediaid'];
      $selected_media = BynderMediaApi::getBynderApi()
        ->getObjectById($id);
      if (isset($selected_media['id'])) {
        $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'];
        $file = file_save($file);
        $file->file = array();
        $file->file[LANGUAGE_NONE] = array();
        $file->file[LANGUAGE_NONE][0] = (array) $file + array(
          'display' => true,
        );
        $file->is_new = true;
        field_attach_insert('media', $file);

        // Save Bynder asset entry.
        $bynderId = $selected_media['id'];
        $name = $selected_media['name'];
        $description = $selected_media['description'];
        $derivatives = $selected_media['thumbnails'];
        try {
          db_insert('bynder_media_entity')
            ->fields(array(
            'bynder_id' => $bynderId,
            'bynder_hash_id' => $idHash,
            'name' => $name,
            'description' => $description,
            'derivatives' => serialize($derivatives),
            'fid' => $file->fid,
          ))
            ->execute();
          $uploaded = true;
          $context['results']['fids_done'][] = $file->fid;
          break;
        } catch (Exception $e) {
          watchdog('bynder', $e
            ->getMessage());
        }
      }
      else {
        sleep(5);
        continue;
      }
    }
    if (!$uploaded) {
      drupal_set_message(t('An error occurred: a file was uploaded to Bynder but it was
            not added to your Drupal Media Library.'), 'warning');
    }
  }
  else {
    drupal_set_message(t("The media file was successfully uploaded to Bynder and sent to the \n            Waiting Room. You will have to add this file to your Drupal media library manually once it has been accepted."), 'warning');
  }
}
function bynder_upload_file_batch_finished($success, $results, $operations) {
  if ($success) {

    // Here we do something meaningful with the results.
    $message = t('@count items successfully processed:', array(
      '@count' => count($results['files_done']),
    ));
    $message .= theme('item_list', array(
      'items' => $results['files_done'],
    ));
    drupal_set_message($message);
  }
  else {

    // An error occurred.
    // $operations contains the operations that remained unprocessed.
    $error_operation = reset($operations);
    $message = t('An error occurred while processing %error_operation with arguments: @arguments', array(
      '%error_operation' => $error_operation[0],
      '@arguments' => print_r($error_operation[1], true),
    ));
    drupal_set_message($message, 'error');
  }
  if (!isset($_SESSION['bynder_upload_browser'])) {
    drupal_goto('/media/browser', array(
      'query' => array(
        'render' => 'media-popup',
        'fid' => isset($results['fids_done']) ? $results['fids_done'] : array(),
      ),
    ));
  }
  else {
    drupal_set_message(t("Successfully added the selected assets."), 'status');
    drupal_goto('admin/content/file');

    // page to return to after complete
  }
}