<?php

/**
 * @file
 * Install, update and uninstall functions for the media_youtube_upload module.
 */

/**
 * Implements hook_install().
 */
function media_youtube_upload_install() {
  // Set file entity fields in a variable for further use.
  $field_machine_names = array(
    'field_file_youtube_title',
    'field_file_youtube_description',
    'field_file_youtube_privacy',
    'field_file_youtube_tags',
    'field_file_youtube_category',
    'field_file_youtube_thumb',
  );
  variable_set('media_youtube_upload_youtube_fields', $field_machine_names);
  
  // Create necessary fields for the file entity.
  _media_youtube_upload_create_entity_fields();

  // Create a vocabulary for the YouTube tags.
  _media_youtube_upload_create_youtube_tags_vocabulary();
}

/**
 * Implements hook_uninstall().
 */
function media_youtube_upload_uninstall() {
  // Delete the settings variables.
  variable_del('media_youtube_upload_app_name');
  variable_del('media_youtube_upload_client_secret');
  variable_del('media_youtube_upload_client_id');
  variable_del('media_youtube_upload_app_country');
  variable_del('media_youtube_upload_token');
  variable_del('media_youtube_upload_automatic_deletion');

  // Delete the default values setting variables.
  $settings_types = array('page_settings', 'block_settings', 'media_settings');
  foreach ($settings_types as $settings_type) {
    variable_del('media_youtube_upload_upload_' . $settings_type . '_fid');
    variable_del('media_youtube_upload_upload_' . $settings_type . '_youtube_fields_enabled_fields');
    variable_del('media_youtube_upload_upload_' . $settings_type . '_allowed_extensions');
    variable_del('media_youtube_upload_upload_' . $settings_type . '_max_uploadsize');
    variable_del('media_youtube_upload_upload_' . $settings_type . '_youtube_redirect');
  }

  // Delete the configuration files.
  $result = db_query('SELECT f.fid FROM {file_managed} f WHERE f.filemime = :filemime', array(':filemime' => 'youtube/config'));
  $config_files = array();
  foreach ($result as $record) {
    $config_files[] = $record->fid;
  }
  file_delete_multiple($config_files);

  // Delete the vocabulary for the YouTube tags.
  $youtube_tags = taxonomy_vocabulary_machine_name_load("youtube_tags");
  taxonomy_vocabulary_delete($youtube_tags->vid);

  // Remove YouTube fields for the video file entity.
  _media_youtube_upload_remove_entity_fields();
}


/**
 * Function to create the vocabulary for YouTube tags.
 */
function _media_youtube_upload_create_youtube_tags_vocabulary() {

  if (!taxonomy_vocabulary_machine_name_load("youtube_tags")) {
    $youtube_tags = (object) array(
      'name' => 'YouTube tags',
      'machine_name' => 'youtube_tags',
      'description' => 'A vocabulary with YouTube tags that are used in YouTube video files',
      'hierarchy' => 0,
      'module' => 'media_youtube_upload',
      'weight' => 0,
    );

    taxonomy_vocabulary_save($youtube_tags);
  }
}

/**
 * Function to remove fields and instances.
 */
function _media_youtube_upload_remove_entity_fields() {

  $field_machine_names = variable_get('media_youtube_upload_youtube_fields');

  foreach ($field_machine_names as $field_machine_name) {
    if ($field = field_info_field($field_machine_name)) {
      field_delete_field(key($field));
    }

    if ($instance = field_info_instance('file', $field_machine_name, 'youtube')) {
      field_delete_instance($instance);
    }
  }
  
  // Remove the variable that contains the youtube fields.
    variable_del('media_youtube_upload_youtube_fields');
}

/**
 * Function to create fields and instances.
 */
function _media_youtube_upload_create_entity_fields() {

  $field_bases = media_youtube_upload_field_bases();

  foreach ($field_bases as $field_base) {
    // Create the fields.
    if (!field_info_field($field_base['field_name'])) {
      field_create_field($field_base);
    }
  }

  $field_instances = media_youtube_upload_field_instances();

  foreach ($field_instances as $field_instance) {
    // Create the field instances.
    if (!field_info_instance($field_instance['entity_type'], $field_instance['field_name'], $field_instance['bundle'])) {
      field_create_instance($field_instance);
    }
  }

}

/**
 * Field bases.
 */
function media_youtube_upload_field_bases() {
  $field_bases = array();

  // Exported field_base: 'field_file_youtube_title'
  $field_bases['field_file_youtube_title'] = array(
    'active' => 1,
    'cardinality' => 1,
    'deleted' => 0,
    'entity_types' => array(),
    'field_name' => 'field_file_youtube_title',
    'indexes' => array(
      'format' => array(
        0 => 'format',
      ),
    ),
    'locked' => 1,
    'module' => 'text',
    'settings' => array(
      'max_length' => 100,
    ),
    'translatable' => 0,
    'type' => 'text',
  );

  // Exported field_base: 'field_file_youtube_description'
  $field_bases['field_file_youtube_description'] = array(
    'active' => 1,
    'cardinality' => 1,
    'deleted' => 0,
    'entity_types' => array(),
    'field_name' => 'field_file_youtube_description',
    'indexes' => array(
      'format' => array(
        0 => 'format',
      ),
    ),
    'locked' => 1,
    'module' => 'text',
    'settings' => array(
      'max_length' => 5000,
    ),
    'translatable' => 0,
    'type' => 'text_long',
  );

  // Exported field_base: 'field_file_youtube_privacy'
  $field_bases['field_file_youtube_privacy'] = array(
    'active' => 1,
    'cardinality' => 1,
    'deleted' => 0,
    'entity_types' => array(),
    'field_name' => 'field_file_youtube_privacy',
    'indexes' => array(
      'value' => array(
        0 => 'value',
      ),
    ),
    'locked' => 1,
    'module' => 'list',
    'settings' => array(
      'allowed_values' => array(
        'public' => 'Public',
        'unlisted' => 'Unlisted',
        'private' => 'Private',
      ),
      'allowed_values_function' => '',
    ),
    'translatable' => 0,
    'type' => 'list_text',
  );

  // Exported field_base: 'field_file_youtube_category'
  $field_bases['field_file_youtube_category'] = array(
    'active' => 1,
    'cardinality' => 1,
    'deleted' => 0,
    'entity_types' => array(),
    'field_name' => 'field_file_youtube_category',
    'indexes' => array(
      'value' => array(
        0 => 'value',
      ),
    ),
    'locked' => 1,
    'module' => 'list',
    'settings' => array(
      'allowed_values' => array(),
      'allowed_values_function' => '_media_youtube_upload_allowed_values_for_category_field_function',
    ),
    'translatable' => 0,
    'type' => 'list_integer',
  );

  // Exported field_base: 'field_file_youtube_tags'
  $field_bases['field_file_youtube_tags'] = array(
    'active' => 1,
    'cardinality' => 10,
    'deleted' => 0,
    'entity_types' => array(),
    'field_name' => 'field_file_youtube_tags',
    'indexes' => array(
      'tid' => array(
        0 => 'tid',
      ),
    ),
    'locked' => 0,
    'module' => 'taxonomy',
    'settings' => array(
      'allowed_values' => array(
        0 => array(
          'vocabulary' => 'youtube_tags',
          'parent' => 0,
        ),
      ),
    ),
    'translatable' => 0,
    'type' => 'taxonomy_term_reference',
  );

  // Exported field_base: 'field_file_youtube_thumb'
  $field_bases['field_file_youtube_thumb'] = array(
    'active' => 1,
    'cardinality' => 1,
    'deleted' => 0,
    'entity_types' => array(),
    'field_name' => 'field_file_youtube_thumb',
    'indexes' => array(
      'fid' => array(
        0 => 'fid',
      ),
    ),
    'locked' => 0,
    'module' => 'image',
    'settings' => array(
      'default_image' => 0,
      'uri_scheme' => 'public',
    ),
    'translatable' => 0,
    'type' => 'image',
  );

  return $field_bases;
}

/**
 * Return field instances.
 */
function media_youtube_upload_field_instances() {
  $field_instances = array();
  $t = get_t();

  // Exported field_instance: 'file-youtube-field_file_youtube_title'
  $field_instances['file-youtube-field_file_youtube_title'] = array(
    'bundle' => 'youtube',
    'default_value' => NULL,
    'deleted' => 0,
    'description' => '',
    'display' => array(
      'default' => array(
        'label' => 'above',
        'module' => 'text',
        'settings' => array(),
        'type' => 'text_default',
        'weight' => 2,
      ),
      'preview' => array(
        'label' => 'above',
        'settings' => array(),
        'type' => 'hidden',
        'weight' => 2,
      ),
      'teaser' => array(
        'label' => 'above',
        'settings' => array(),
        'type' => 'hidden',
        'weight' => 2,
      ),
    ),
    'entity_type' => 'file',
    'field_name' => 'field_file_youtube_title',
    'label' => 'Title',
    'required' => 1,
    'settings' => array(
      'text_processing' => 0,
      'user_register_form' => FALSE,
      'wysiwyg_override' => 0,
    ),
    'widget' => array(
      'active' => 1,
      'module' => 'text',
      'settings' => array(
        'size' => 60,
      ),
      'type' => 'text_textfield',
      'weight' => 2,
    ),
  );

  // Exported field_instance: 'file-video-field_file_youtube_description'
  $field_instances['file-video-field_file_youtube_description'] = array(
    'bundle' => 'youtube',
    'default_value' => NULL,
    'deleted' => 0,
    'description' => 'YouTube video description',
    'display' => array(
      'default' => array(
        'label' => 'above',
        'module' => 'text',
        'settings' => array(),
        'type' => 'text_default',
        'weight' => 3,
      ),
      'preview' => array(
        'label' => 'above',
        'settings' => array(),
        'type' => 'hidden',
        'weight' => 3,
      ),
      'teaser' => array(
        'label' => 'above',
        'settings' => array(),
        'type' => 'hidden',
        'weight' => 3,
      ),
    ),
    'entity_type' => 'file',
    'field_name' => 'field_file_youtube_description',
    'label' => 'Description',
    'required' => 1,
    'settings' => array(
      'text_processing' => 0,
      'user_register_form' => FALSE,
      'wysiwyg_override' => 0,
    ),
    'widget' => array(
      'active' => 1,
      'module' => 'text',
      'settings' => array(
        'rows' => 5,
        'attributes' => array('maxlength' => 5000),
      ),
      'type' => 'text_textarea',
      'weight' => 3,
    ),
  );

  // Exported field_instance: 'file-video-field_file_youtube_privacy'
  $field_instances['file-video-field_file_youtube_privacy'] = array(
    'bundle' => 'youtube',
    'default_value' => NULL,
    'deleted' => 0,
    'description' => '',
    'display' => array(
      'default' => array(
        'label' => 'above',
        'module' => 'list',
        'settings' => array(),
        'type' => 'list_default',
        'weight' => 4,
      ),
      'preview' => array(
        'label' => 'above',
        'settings' => array(),
        'type' => 'hidden',
        'weight' => 4,
      ),
      'teaser' => array(
        'label' => 'above',
        'settings' => array(),
        'type' => 'hidden',
        'weight' => 4,
      ),
    ),
    'entity_type' => 'file',
    'field_name' => 'field_file_youtube_privacy',
    'label' => 'Privacy',
    'required' => 1,
    'settings' => array(
      'user_register_form' => FALSE,
      'wysiwyg_override' => 0,
    ),
    'widget' => array(
      'active' => 1,
      'module' => 'options',
      'settings' => array(),
      'type' => 'options_select',
      'weight' => 4,
    ),
  );

  // Exported field_instance: 'file-video-field_file_youtube_category'
  $field_instances['file-video-field_file_youtube_category'] = array(
    'bundle' => 'youtube',
    'default_value' => NULL,
    'deleted' => 0,
    'description' => '',
    'display' => array(
      'default' => array(
        'label' => 'above',
        'module' => 'list',
        'settings' => array(),
        'type' => 'list_default',
        'weight' => 5,
      ),
      'preview' => array(
        'label' => 'above',
        'settings' => array(),
        'type' => 'hidden',
        'weight' => 5,
      ),
      'teaser' => array(
        'label' => 'above',
        'settings' => array(),
        'type' => 'hidden',
        'weight' => 5,
      ),
    ),
    'entity_type' => 'file',
    'field_name' => 'field_file_youtube_category',
    'label' => 'Category',
    'required' => 1,
    'settings' => array(
      'user_register_form' => FALSE,
      'wysiwyg_override' => 0,
    ),
    'widget' => array(
      'active' => 1,
      'module' => 'options',
      'settings' => array(),
      'type' => 'options_select',
      'weight' => 5,
    ),
  );

  // Exported field_instance: 'file-video-field_file_youtube_tags'
  $field_instances['file-video-field_file_youtube_tags'] = array(
    'bundle' => 'youtube',
    'default_value' => NULL,
    'deleted' => 0,
    'description' => '',
    'display' => array(
      'default' => array(
        'label' => 'above',
        'module' => 'taxonomy',
        'settings' => array(),
        'type' => 'taxonomy_term_reference_link',
        'weight' => 6,
      ),
      'preview' => array(
        'label' => 'above',
        'settings' => array(),
        'type' => 'hidden',
        'weight' => 6,
      ),
      'teaser' => array(
        'label' => 'above',
        'settings' => array(),
        'type' => 'hidden',
        'weight' => 6,
      ),
    ),
    'entity_type' => 'file',
    'field_name' => 'field_file_youtube_tags',
    'label' => 'Tags',
    'required' => 0,
    'settings' => array(
      'user_register_form' => FALSE,
      'wysiwyg_override' => 0,
    ),
    'widget' => array(
      'active' => 0,
      'module' => 'taxonomy',
      'settings' => array(
        'autocomplete_path' => 'taxonomy/autocomplete',
        'size' => 60,
      ),
      'type' => 'taxonomy_autocomplete',
      'weight' => 6,
    ),
  );

  // Exported field_instance: 'file-youtube-field_file_youtube_thumb'
  $field_instances['file-youtube-field_file_youtube_thumb'] = array(
    'bundle' => 'youtube',
    'deleted' => 0,
    'description' => '',
    'display' => array(
      'default' => array(
        'label' => 'above',
        'module' => 'image',
        'settings' => array(
          'image_link' => '',
          'image_style' => '',
        ),
        'type' => 'image',
        'weight' => 7,
      ),
      'preview' => array(
        'label' => 'above',
        'settings' => array(),
        'type' => 'hidden',
        'weight' => 7,
      ),
      'teaser' => array(
        'label' => 'above',
        'settings' => array(),
        'type' => 'hidden',
        'weight' => 7,
      ),
    ),
    'entity_type' => 'file',
    'field_name' => 'field_file_youtube_thumb',
    'label' => 'Thumb',
    'required' => 0,
    'settings' => array(
      'alt_field' => 0,
      'default_image' => 0,
      'file_directory' => 'youtube_thumbs',
      'file_extensions' => 'png gif jpg jpeg',
      'max_filesize' => '',
      'max_resolution' => '',
      'min_resolution' => '',
      'title_field' => 0,
      'user_register_form' => FALSE,
      'wysiwyg_override' => 0,
    ),
    'widget' => array(
      'active' => 1,
      'module' => 'image',
      'settings' => array(
        'preview_image_style' => 'thumbnail',
        'progress_indicator' => 'throbber',
      ),
      'type' => 'image_image',
      'weight' => 7,
    ),
  );

  // Translatables
  // Included for use with string extractors like potx.
  t('Title');
  t('Description');
  t('Privacy');
  t('YouTube video description');
  t('Category');
  t('Tags');
  t('Thumb');

  return $field_instances;
}

/**
 * Implements hook_requirements().
 */
function media_youtube_upload_requirements($phase) {

  // Test if libraries are available and google account working.
  $requirements = array();
  $t = get_t();

  if ($phase == 'runtime') {
    $ytapi = new MediaYoutubeUploadYtapi();
    $t = get_t();
    // Check PHP library.
    $requirements['media_youtube_upload_php'] = array(
      'title' => $t('Google APIs Client Library for PHP'),
      'value' => '',
      'description' => '',
      'severity' => REQUIREMENT_OK,
    );
    if (!$ytapi->mtestGoogleLib()) {
      $url = l($t('here'), 'https://github.com/google/google-api-php-client/archive/master.zip');
      $requirements['media_youtube_upload_php']['description'] = $t('Install the Google APIs Client Library for PHP code with drush command <em>drush myu-libraries</em>
          <br /> or manually (from !here) and extract it to a valid library folder
          <br /> then go to the library folder google-api-php-client and run <em>composer install</em> 
          <br /> so the path <br />libraries/google-api-php-client/src/Google/autoload.php is available',
          array(
            '!here' => $url,
          ));
      $requirements['media_youtube_upload_php']['severity'] = REQUIREMENT_ERROR;
    }
    else {
      $requirements['media_youtube_upload_php']['value'] = 'Loaded';

      // Test Google Account.
      $requirements['media_youtube_upload_app'] = array(
        'title' => $t('Google Application'),
        'value' => '',
        'description' => '',
        'severity' => REQUIREMENT_OK,
      );

      $ac = $ytapi->getFreshToken();
      if ($ac['error']) {
        $url = l($t('here'), 'https://github.com/google/google-api-php-client/archive/master.zip');
        $requirements['media_youtube_upload_app']['description'] = $t('Please authorize your Google Application in the !yt_settings settings.',
            array('!yt_settings' => l($t('Media youtube upload'), 'admin/config/media/media_youtube_upload')));
        $requirements['media_youtube_upload_app']['severity'] = REQUIREMENT_ERROR;
      }
      else {
        $requirements['media_youtube_upload_app']['value'] = 'Checked';
      }
    }

    // Check JS file.
    $requirements['media_youtube_upload_cors'] = array(
      'title' => $t('Google CORS Upload'),
      'value' => '',
      'description' => '',
      'severity' => REQUIREMENT_OK,
    );
    $info = _media_youtube_upload_get_cors_upload();
    if (!$info) {
      $url = l($t('here'), 'https://raw.githubusercontent.com/youtube/api-samples/master/javascript/cors_upload.js');
      $requirements['media_youtube_upload_cors']['description'] = $t('Install the Google CORS upload library code with drush <em>drush myu-libraries</em><br /> or manually (1 single file from !here) and extract it so the path <br />sites/all/libraries/google-api-cors-upload/cors_upload.js <br />or sites/!domain/libraries/google-api-cors-upload/cors_upload.js<br /> is available',
          array(
            '!here' => $url,
            '!domain' => $_SERVER['SERVER_NAME'],
          ));
      $requirements['media_youtube_upload_cors']['severity'] = REQUIREMENT_ERROR;
    }
    else {
      $requirements['media_youtube_upload_cors']['value'] = 'Loaded';
    }
  }
  return $requirements;
}

