<?php

/**
 * @file
 * Offer proposal forms so users can suggest pedagogical resources.
 */

/**
 * Implements hook_init().
 */
function archibald_proposals_init() {
  // This is a hack for adding field permissions to our new proposal fields. We
  // cannot do this on install, as at that time the special field permissions
  // have not been registered yet. We set a system variable when done, so we
  // only do this once.
  if (
    !variable_get('archibald_proposals_set_permissions', FALSE) &&
    in_array('create proposal_name', array_keys(module_invoke_all('permission')))
  ) {
    archibald_proposals_reset_field_permissions();

    // Allow anonymous users to create content. It also seems that new versions
    // of Drupal require the "access content" permission for this to work.
    user_role_change_permissions(DRUPAL_ANONYMOUS_RID, array(
      'create archibald_lomch_description content' => TRUE,
      'access content' => TRUE,
    ));

    variable_set('archibald_proposals_set_permissions', TRUE);
  }
}

/**
 * Implements hook_menu().
 */
function archibald_proposals_menu() {
  return array(
    'admin/config/services/archibald-proposals' => array(
      'title' => 'Archibald Proposals',
      'description' => 'Configure Archibald Proposals settings',
      'access arguments' => array('administer archibald'),
      'page callback' => 'drupal_get_form',
      'page arguments' => array('archibald_proposals_admin_settings_form'),
    ),
  );
}

/**
 * Implements hook_permission().
 */
function archibald_proposals_permission() {
  return array(
    'get notified on proposal creation' => array(
      'title' => t('Get notified when a proposal is created'),
    ),
  );
}

/**
 * Implements hook_form_FORM_ID_alter() for archibald_lomch_description_node_form().
 */
function archibald_proposals_form_archibald_lomch_description_node_form_alter(&$form, $form_state) {
  // If we are editing a node, and the following fields are empty, block access.
  // This is actually a hack, but makes the form much easier to/ use for
  // editors. In any case, though, do not make the fields required.
  foreach (archibald_proposals_archibald_lomch_description_fields() as $field_name => $field_options) {
    if (isset($form[$field_name]) && !empty($form['#node']->nid)) {
      // Get the field value.
      if ($field_options['type'] == 'email') {
        $form[$field_name][LANGUAGE_NONE][0]['email']['#required'] = FALSE;
        $value = $form[$field_name][LANGUAGE_NONE][0]['email']['#default_value'];
      }
      else {
        $form[$field_name][LANGUAGE_NONE][0]['value']['#required'] = FALSE;
        $value = $form[$field_name][LANGUAGE_NONE][0]['value']['#default_value'];
      }

      if (empty($value)) {
        $form[$field_name]['#access'] = FALSE;
      }
    }
  }
}

/**
 * Implement hook_rules_action_info().
 */
function archibald_proposals_rules_action_info() {
  return array(
    'archibald_proposals_rules_load_users_with_perm' => array(
      'label' => t("Load a list of users with a permission"),
      'group' => t("User"),
      'parameter' => array(
        'permission' => array(
          'type' => 'text',
          'label' => t("Permission to check"),
          'description' => t("Provide a permission, and all users with this permission will be loaded"),
        ),
      ),
      'provides' => array(
        'users' => array(
          'type' => 'list<user>',
          'label' => t("Users"),
        ),
      ),
    ),
  );
}

/**
 * Form callback.
 */
function archibald_proposals_admin_settings_form($form, $form_state) {
  $form['reset_field_permissions'] = array(
    '#type' => 'fieldset',
    '#title' => t("Reset the default field permissions"),
    '#description' => t("Revert all field permissions in the Description node form to the defaults. This hides most fields, and only gives access to a small sub-set."),
  );

  $form['reset_field_permissions']['do'] = array(
    '#type' => 'button',
    '#value' => t("Reset the proposal field permissions"),
    '#op' => 'reset_field_permissions',
  );

  return $form;
}

/**
 * Validation callback for archibald_proposals_admin_settings_form().
 */
function archibald_proposals_admin_settings_form_validate($form, $form_state) {
  if ($form_state['triggering_element']['#op'] == 'reset_field_permissions') {
    archibald_proposals_reset_field_permissions();
  }
}

/**
 * Fetch a list of fields for the proposal form.
 *
 * @return array
 */
function archibald_proposals_archibald_lomch_description_fields() {
  return array(
    'proposal_name' => array(
      'label' => "Name",
      'cardinality' => 1,
      'type' => 'text',
      'required' => TRUE,
      'widget' => array(
        'type' => 'text_textfield',
      ),
      'api_help' => array(
        'help' => t("Provide your name.", array(), array('context' => 'archibald:help')),
      ),
    ),
    'proposal_email' => array(
      'label' => "Email",
      'cardinality' => 1,
      'type' => 'email',
      'required' => TRUE,
      'widget' => array(
        'type' => 'email_textfield',
      ),
      'display' => array(
        'default' => array(
          'type' => 'email_plain',
        ),
      ),
      'api_help' => array(
        'help' => t("Provide your email address, so we can reach you if needed.", array(), array('context' => 'archibald:help')),
      ),
    ),
    'proposal_message' => array(
      'label' => "Message",
      'cardinality' => 1,
      'type' => 'text_long',
      'required' => TRUE,
      'widget' => array(
        'type' => 'text_textarea',
      ),
      'api_help' => array(
        'help' => t("Provide an explanation of why you think this resource is relevant.", array(), array('context' => 'archibald:help')),
      ),
    ),
  );
}

/**
 * Set the default configuration for the node form field permissions.
 */
function archibald_proposals_reset_field_permissions() {
  foreach (archibald_proposals_archibald_lomch_description_fields() as $field_name => $field_options) {
    // Allow anonymous users, but not authenticated ones. Authenticated ones
    // can view the data, though.
    user_role_change_permissions(DRUPAL_ANONYMOUS_RID, array(
      "create {$field_name}" => TRUE,
    ));
    user_role_change_permissions(DRUPAL_AUTHENTICATED_RID, array(
      // Normally, we don't explicitly need to set this to false. But it
      // explicit is better than implicit.
      "create {$field_name}" => FALSE,
      "edit {$field_name}" => TRUE,
      "view {$field_name}" => TRUE,
    ));

    // If this site has an user_admin_role set, it will get permission to see
    // these fields on the create/edit form, which is obviously not something
    // we want. Make sure we disable these permissions.
    if ($rid = variable_get('user_admin_role', FALSE)) {
      user_role_change_permissions($rid, array(
        "create {$field_name}" => FALSE,
        "edit own {$field_name}" => FALSE,
        "edit {$field_name}" => FALSE,
      ));
    }
  }

  // Block access to the following fields.
  foreach (array(
    'archibald_publication_catalogs',
    'archibald_publication_partner',
    'lomch_resource_language',
    'lomch_aggregation_level',
    'lomch_keywords',
    'lomch_coverage',
    'lomch_version',
    'lomch_lifecycle_author',
    'lomch_lifecycle_editor',
    'lomch_lifecycle_publisher',
    'lomch_technical_format',
    'lomch_size',
    'lomch_location',
    'lomch_platform_requirements',
    'lomch_duration',
    'lomch_preview_image',
    'lomch_learning_resource_type',
    'lomch_intended_enduserrole',
    'lomch_context',
    'lomch_typical_age_range',
    'lomch_difficulty_level',
    'lomch_typical_learning_time',
    'lomch_educational_description',
    'lomch_rights_cost',
    'lomch_rights_description',
    'lomch_relations',
    'archibald_lp21',
    'archibald_per',
    'archibald_stdlehr',
  ) as $field_name) {
    // Register custom permissions.
    if ($field = field_info_field($field_name)) {
      $field['field_permissions']['type'] = FIELD_PERMISSIONS_CUSTOM;
      field_update_field($field);
      user_role_change_permissions(DRUPAL_AUTHENTICATED_RID, array(
        "create {$field_name}" => TRUE,
        "edit {$field_name}" => TRUE,
        "view {$field_name}" => TRUE,
      ));
    }
  }
}
