<?php

/**
 * @file
 * Actions support for the Flag module.
 */

/**
 * Implements hook_flag_flag(). Trigger actions if any are available.
 */
function flag_actions_flag_flag($flag, $entity_id, $account, $flagging) {
  flag_actions_do('flag', $flag, $entity_id, $account);
}

/**
 * Implements hook_flag_unflag(). Trigger actions if any are available.
 */
function flag_actions_flag_unflag($flag, $entity_id, $account, $flagging) {
  flag_actions_do('unflag', $flag, $entity_id, $account);
}

/**
 * Implements hook_menu().
 */
function flag_actions_menu() {
  $items = array();

  $items[FLAG_ADMIN_PATH . '/actions'] = array(
    'title' => 'Actions',
    'page callback' => 'flag_actions_page',
    'access callback' => 'user_access',
    'access arguments' => array('administer actions'),
    'type' => MENU_LOCAL_TASK,
    'weight' => 1,
  );
  $items[FLAG_ADMIN_PATH . '/actions/add'] = array(
    'title' => 'Add action',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('flag_actions_form', NULL, 5),
    'access callback' => 'user_access',
    'access arguments' => array('administer actions'),
    'type' => MENU_CALLBACK,
  );
  $items[FLAG_ADMIN_PATH . '/actions/delete'] = array(
    'title' => 'Delete action',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('flag_actions_delete_form', 5),
    'access callback' => 'user_access',
    'access arguments' => array('administer actions'),
    'type' => MENU_CALLBACK,
  );
  $items[FLAG_ADMIN_PATH . '/actions/configure'] = array(
    'title' => 'Edit action',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('flag_actions_form', 5),
    'access callback' => 'user_access',
    'access arguments' => array('administer actions'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

/**
 * Implements hook_theme().
 */
function flag_actions_theme() {
  return array(
    'flag_actions_page' => array(
      'variables' => array('actions' => NULL, 'form' => NULL),
    ),
    'flag_actions_add_form' => array(
      'render element' => 'form',
    ),
    'flag_actions_flag_form' => array(
      'render element' => 'form',
    ),
  );
}

function flag_actions_get_action($aid) {
  $actions = flag_actions_get_actions();
  return $actions[$aid];
}

function flag_actions_get_actions($flag_name = NULL, $reset = FALSE) {
  $flag_actions = &drupal_static(__FUNCTION__);
  module_load_include('inc', 'flag', 'includes/flag.actions');

  // Get a list of all possible actions defined by modules.
  $actions = module_invoke_all('action_info');

  // Retrieve the list of user-defined flag actions.
  if (!isset($flag_actions) || $reset) {
    $flag_actions = array();
    $query = db_select('flag_actions', 'a');
    $query->innerJoin('flag', 'f', 'a.fid = f.fid');
    $query->addField('f', 'name', 'flag');
    $result = $query
      ->fields('a')
      ->execute();
    foreach ($result as $action) {
      if (!isset($actions[$action->callback])) {
        $actions[$action->callback] = array(
          'description' => t('Missing action "@action-callback". Module providing it was either uninstalled or disabled.', array('@action-callback' => $action->callback)),
          'configurable' => FALSE,
          'type' => 'node',
          'missing' => TRUE,
        );
      }
      $action->parameters = unserialize($action->parameters);
      $action->label = $actions[$action->callback]['label'];
      $action->configurable = $actions[$action->callback]['configurable'];
      $action->behavior = isset($actions[$action->callback]['behavior']) ? $actions[$action->callback]['behavior'] : array();
      $action->type = $actions[$action->callback]['type'];
      $action->missing = !empty($actions[$action->callback]['missing']);

      $flag_actions[$action->aid] = $action;
    }
  }

  // Filter actions to a specified flag.
  if (isset($flag_name)) {
    $specific_flag_actions = array();
    foreach ($flag_actions as $aid => $action) {
      if ($action->flag == $flag_name) {
        $specific_flag_actions[$aid] = $action;
      }
    }
    return $specific_flag_actions;
  }

  return $flag_actions;
}

/**
 * Insert a new flag action.
 *
 * @param $fid
 *   The flag object ID.
 * @param $event
 *   The flag event, such as "flag" or "unflag".
 * @param $threshold
 *   The flagging threshold at which this action will be executed.
 * @param $repeat_threshold
 *   The number of additional flaggings after which the action will be repeated.
 * @param $callback
 *   The action callback to be executed.
 * @param $parameters
 *   The action parameters.
 */
function flag_actions_insert_action($fid, $event, $threshold, $repeat_threshold, $callback, $parameters) {
  return db_insert('flag_actions')
    ->fields(array(
      'fid' => $fid,
      'event' => $event,
      'threshold' => $threshold,
      'repeat_threshold' => $repeat_threshold,
      'callback' => $callback,
      'parameters' => serialize($parameters),
    ))
    ->execute();
}

/**
 * Update an existing flag action.
 *
 * @param $aid
 *   The flag action ID to update.
 * @param $event
 *   The flag event, such as "flag" or "unflag".
 * @param $threshold
 *   The flagging threshold at which this action will be executed.
 * @param $repeat_threshold
 *   The number of additional flaggings after which the action will be repeated.
 * @param $parameters
 *   The action parameters.
 */
function flag_actions_update_action($aid, $event, $threshold, $repeat_threshold, $parameters) {
  return db_update('flag_actions')
    ->fields(array(
      'event' => $event,
      'threshold' => $threshold,
      'repeat_threshold' => $repeat_threshold,
      'parameters' => serialize($parameters),
    ))
    ->condition('aid', $aid)
    ->execute();
}

/**
 * Delete a flag action.
 *
 * @param $aid
 *   The flag action ID to delete.
 */
function flag_actions_delete_action($aid) {
  return db_delete('flag_actions', array('return' => Database::RETURN_AFFECTED))
    ->condition('aid', $aid)
    ->execute();
}

/**
 * Perform flag actions.
 */
function flag_actions_do($event, $flag, $entity_id, $account) {
  $actions = flag_actions_get_actions($flag->name);
  if (!$actions) {
    return;
  }

  $flag_action = $flag->get_flag_action($entity_id);
  $flag_action->action = $event;
  $flag_action->count = $count = $flag->get_count($entity_id);
  $relevant_objects = $flag->get_relevant_action_objects($entity_id);
  $object_changed = FALSE;
  foreach ($actions as $aid => $action) {
    if ($action->event == 'flag') {
      $at_threshold = ($count == $action->threshold);
      $repeat = $action->repeat_threshold ? (($count > $action->threshold) && (($count - $action->threshold) % $action->repeat_threshold == 0)) : FALSE;
    }
    elseif ($action->event == 'unflag') {
      $at_threshold = ($count == $action->threshold - 1);
      $repeat = $action->repeat_threshold ? (($count < $action->threshold - 1) && (($count - $action->threshold - 1) % $action->repeat_threshold == 0)) : FALSE;
    }
    if (($at_threshold || $repeat) && $action->event == $event && !$action->missing) {
      $context = $action->parameters;
      $context['callback'] = $action->callback;
      // We're setting 'hook' to something, to prevent PHP warnings by actions
      // who read it. Maybe we should set it to nodeapi/comment/user, depending
      // on the flag, because these three are among the only hooks some actions
      // in system.module "know" to work with.
      $context['hook'] = 'flag';
      $context['type'] = $action->type;
      $context['account'] = $account;
      $context['flag'] = $flag;
      $context['flag-action'] = $flag_action;
      // We add to the $context all the objects we know about:
      $context = array_merge($relevant_objects, $context);
      $callback = $action->callback;

      if (isset($relevant_objects[$action->type])) {
        $callback($relevant_objects[$action->type], $context);
      }
      else {
        // What object shall we send as last resort? Let's send a node, or
        // the flag's object.
        if (isset($relevant_objects['node'])) {
          $callback($relevant_objects['node'], $context);
        }
        else {
          $callback($relevant_objects[$flag->entity_type], $context);
        }
      }

      if (is_array($action->behavior) && in_array('changes_property', $action->behavior)) {
        $object_changed = TRUE;
      }
    }
  }

  // Actions by default do not save elements unless the save action is
  // explicitly added. We run it automatically upon flagging.
  if ($object_changed) {
    $save_action = $action->type . '_save_action';
    if (function_exists($save_action)) {
      $save_action($relevant_objects[$action->type]);
    }
  }
}

/**
 * Menu callback for FLAG_ADMIN_PATH/actions.
 */
function flag_actions_page() {
  $actions = flag_actions_get_actions();
  $add_action_form = drupal_get_form('flag_actions_add_form');

  return theme('flag_actions_page', array('actions' => $actions, 'form' => $add_action_form));
}

/**
 * Theme the list of actions currently in place for flags.
 */
function theme_flag_actions_page($variables) {
  $actions = $variables['actions'];
  $add_action_form = $variables['form'];

  $rows = array();
  foreach ($actions as $action) {
    $flag = flag_get_flag($action->flag);

    // Build a sample string representing repeating actions.
    if ($action->repeat_threshold) {
      $repeat_count = 3;
      $repeat_subtract = ($action->event == 'flag') ? 1 : -1;
      $repeat_samples = array();
      for ($n = 1; $n < $repeat_count + 2; $n++) {
        $sample = $action->threshold + (($n * $action->repeat_threshold) * $repeat_subtract);
        if ($sample > 0) {
          $repeat_samples[] = $sample;
        }
      }
      if (count($repeat_samples) > $repeat_count) {
        $repeat_samples[$repeat_count] = '&hellip;';
      }
      $repeat_string = implode(', ', $repeat_samples);
    }
    else {
      $repeat_string = '-';
    }

    $row = array();
    $row[] = $flag->get_title();
    $row[] = ($action->event == 'flag' ? '&ge; ' : '&lt; ') . $action->threshold;
    $row[] = $repeat_string;
    $row[] = empty($action->missing) ? $action->label : '<div class="error">' . $action->label . '</div>';
    $row[] = l(t('edit'), FLAG_ADMIN_PATH . '/actions/configure/' . $action->aid);
    $row[] = l(t('delete'), FLAG_ADMIN_PATH . '/actions/delete/' . $action->aid);
    $rows[] = $row;
  }

  if (empty($rows)) {
    $rows[] = array(array('data' => t('Currently no flag actions. Use the <em>Add new flag action</em> form to add an action.'), 'colspan' => 6));
  }

  $header = array(
    t('Flag'),
    t('Threshold'),
    t('Repeats'),
    t('Action'),
    array('data' => t('Operations'), 'colspan' => 2),
  );

  $output = '';
  $output .= theme('table', array('header' => $header, 'rows' => $rows));
  $output .= drupal_render($add_action_form);
  return $output;
}

/**
 * Modified version of the Add action form that redirects back to the flag list.
 */
function flag_actions_add_form($form, &$form_state) {
  $flags = flag_get_flags();
  $options = array();
  foreach ($flags as $flag) {
    $options[$flag->name] = $flag->get_title();
  }

  if (empty($options)) {
    $options[] = t('No flag available');
  }

  $form['flag'] = array(
    '#type' => 'select',
    '#options' => empty($options) ? array(t('No flag available')) : $options,
    '#disabled' => empty($options),
    '#title' => t('Select a flag'),
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Add action'),
  );

  return $form;
}

function flag_actions_add_form_submit($form, &$form_state) {
  if ($form_state['values']['flag']) {
    $form_state['redirect'] = array(FLAG_ADMIN_PATH . '/actions/add/' . $form_state['values']['flag']);
  }
}

function theme_flag_actions_add_form($variables) {
  $form = $variables['form'];

  $fieldset = array(
    '#type' => 'fieldset',
    '#title' => t('Add a new flag action'),
    '#children' => '<div class="container-inline">' . drupal_render($form['flag']) . drupal_render($form['submit']) . '</div>',
    '#parents' => array('add_action'),
    '#attributes' => array(),
    '#groups' => array('add_action' => array()),
  );

  return drupal_render($fieldset) . drupal_render_children($form);
}

/**
 * Generic configuration form for configuration of flag actions.
 *
 * @param $form_state
 *   The form state.
 * @param $aid
 *   If editing an action, an action ID must be passed in.
 * @param $flag_name
 *   If adding a new action to a flag, a flag name must be specified.
 */
function flag_actions_form($form, &$form_state, $aid = NULL, $flag_name = NULL) {
  // This is a multistep form. Get the callback value if set and continue.
  if (isset($form_state['storage']['callback'])) {
    $callback = $form_state['storage']['callback'];
    unset($form_state['storage']['callback']);
  }

  if (isset($aid)) {
    $action = flag_actions_get_action($aid);
    $callback = $action->callback;
    $flag = flag_get_flag($action->flag);
    drupal_set_title(t('Edit the "@action" action for the @title flag', array('@action' => $action->label, '@title' => $flag->get_title())));
  }
  elseif (isset($flag_name)) {
    $flag = flag_get_flag($flag_name);
  }

  if (empty($flag)) {
    drupal_not_found();
  }

  $form['new'] = array(
    '#type' => 'value',
    '#value' => isset($callback) ? FALSE : TRUE,
  );

  if (!isset($callback)) {
    drupal_set_title(t('Add an action to the @title flag', array('@title' => $flag->get_title())));

    $actions = $flag->get_valid_actions();
    $options = array();
    foreach ($actions as $key => $action) {
      $options[$key] = $action['label'];
    }

    $form['callback'] = array(
      '#title' => t('Select an action'),
      '#type' => 'select',
      '#options' => $options,
    );

    $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Continue'),
    );

    return $form;
  }
  elseif (!isset($action)) {
    $actions = $flag->get_valid_actions();
    $action = (object) $actions[$callback];
    $action->parameters = array();
    $action->event = 'flag';
    $action->threshold = 10;
    $action->repeat_threshold = 0;
    drupal_set_title(t('Add "@action" action to the @title flag', array('@action' => $action->label, '@title' => $flag->get_title())));
  }

  $form['flag'] = array(
    '#tree' => TRUE,
    '#weight' => -9,
    '#theme' => 'flag_actions_flag_form',
    '#action' => $action,
    '#flag' => $flag,
  );

  $form['flag']['flag'] = array(
    '#type' => 'value',
    '#value' => $flag,
  );

  $form['flag']['callback'] = array(
    '#type' => 'value',
    '#value' => $callback,
  );

  $form['flag']['aid'] = array(
    '#type' => 'value',
    '#value' => $aid,
  );

  $form['flag']['event'] = array(
    '#type' => 'select',
    '#options' => array(
      'flag' => t('reaches'),
      'unflag' => t('falls below'),
    ),
    '#default_value' => $action->event,
  );

  $form['flag']['threshold'] = array(
    '#type' => 'textfield',
    '#size' => 6,
    '#maxlength' => 6,
    '#default_value' => $action->threshold,
    '#required' => TRUE,
  );

  $form['flag']['repeat_threshold'] = array(
    '#type' => 'textfield',
    '#size' => 6,
    '#maxlength' => 6,
    '#default_value' => $action->repeat_threshold,
  );

  if ($flag->global) {
    $form['flag']['threshold']['#disabled'] = 1;
    $form['flag']['threshold']['#value'] = 1;
    $form['flag']['repeat_threshold']['#access'] = FALSE;
    $form['flag']['repeat_threshold']['#value'] = 0;
  }

  // Merge in the standard flag action form.
  $action_form = $callback . '_form';
  $edit = array();
  if (function_exists($action_form)) {
    $edit += $action->parameters;
    $edit['actions_label'] = $action->label;
    $edit['actions_type'] = $action->type;
    $edit['actions_flag'] = $flag->name;
    $additions = flag_actions_form_additions($action_form, $edit);
    $form = array_merge($form, $additions);
  }

  // Add a few customizations to existing flag actions.
  $flag_actions_form = 'flag_actions_' . $callback . '_form';
  if (function_exists($flag_actions_form)) {
    $flag_actions_form($form, $flag, $edit);
  }

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );

  return $form;
}

/**
 * Execute an action form callback to retrieve form additions.
 *
 * This function prevents the form callback from modifying local variables.
 */
function flag_actions_form_additions($callback, $edit) {
  return $callback($edit);
}

/**
 * Generic submit handler for validating flag actions.
 */
function flag_actions_form_validate($form, &$form_state) {
  // Special validation handlers may be needed to save this form properly.
  // Try to load the action's validation routine if needed.
  if (isset($form_state['values']['flag']['callback'])) {
    $callback = $form_state['values']['flag']['callback'];
    $validate_function = $callback . '_validate';
    if (function_exists($validate_function)) {
      $validate_function($form, $form_state);
    }
  }
}

/**
 * Generic submit handler for saving flag actions.
 */
function flag_actions_form_submit($form, &$form_state) {
  // If simply gathering the callback, save it to form state storage and
  // rebuild the form to gather the complete information.
  if ($form_state['values']['new']) {
    $form_state['storage']['callback'] = $form_state['values']['callback'];
    $form_state['rebuild'] = TRUE;
    return;
  }

  $aid              = $form_state['values']['flag']['aid'];
  $flag             = $form_state['values']['flag']['flag'];
  $event            = $form_state['values']['flag']['event'];
  $threshold        = $form_state['values']['flag']['threshold'];
  $repeat_threshold = $form_state['values']['flag']['repeat_threshold'];
  $callback         = $form_state['values']['flag']['callback'];

  // Specialized forms may need to execute their own submit handlers on save.
  $submit_function = $callback . '_submit';
  $parameters = function_exists($submit_function) ? $submit_function($form, $form_state) : array();

  if (empty($aid)) {
    $aid = flag_actions_insert_action($flag->fid, $event, $threshold, $repeat_threshold, $callback, $parameters);
    $form_state['values']['flag']['aid'] = $aid;
    $form_state['values']['flag']['is_new'] = TRUE;
  }
  else {
    flag_actions_update_action($aid, $event, $threshold, $repeat_threshold, $parameters);
  }

  $action = flag_actions_get_action($aid);

  drupal_set_message(t('The "@action" action for the @title flag has been saved.', array('@action' => $action->label, '@title' => $flag->get_title())));
  $form_state['redirect'] = FLAG_ADMIN_PATH . '/actions';
}

function theme_flag_actions_flag_form($variables) {
  $form = $variables['form'];

  $event = drupal_render($form['event']);
  $threshold = drupal_render($form['threshold']);
  $repeat_threshold = drupal_render($form['repeat_threshold']);
  $action = $form['#action']->label;

  $output  = '';
  $output .= '<div class="container-inline">';
  $output .= t('Perform action when content !event !threshold flags', array('!event' => $event, '!threshold' => $threshold));
  if ($form['#flag']->global) {
    $output .= ' ' . t('(global flags always have a threshold of 1)');
  }
  $output .= '</div>';
  $output .= '<div class="container-inline">';
  if (!$form['#flag']->global) {
    $output .= t('Repeat this action every !repeat_threshold additional flags after the threshold is reached', array('!repeat_threshold' => $repeat_threshold));
  }
  $output .= '</div>';

  $element = array(
    '#title' => t('Flagging threshold'),
    '#required' => TRUE,
  );

  return $output . drupal_render_children($form);
}

function flag_actions_delete_form($form, &$form_state, $aid) {
  $action = flag_actions_get_action($aid);
  $flag = flag_get_flag($action->flag);

  $form['action'] = array(
    '#type' => 'value',
    '#value' => $action,
  );

  $form['flag'] = array(
    '#type' => 'value',
    '#value' => $flag,
  );

  $question = t('Delete the "@action" action for the @title flag?', array('@action' => $action->label, '@title' => $flag->get_title()));
  $path = FLAG_ADMIN_PATH . '/actions';

  return confirm_form($form, $question, $path, NULL, t('Delete'));
}

function flag_actions_delete_form_submit(&$form, &$form_state) {
  flag_actions_delete_action($form_state['values']['action']->aid);
  drupal_set_message(t('The "@action" action for the @title flag has been deleted.', array('@action' => $form_state['values']['action']->label, '@title' => $form_state['values']['flag']->get_title())));
  $form_state['redirect'] = FLAG_ADMIN_PATH . '/actions';
}

/**
 * Make modifications to the "Send e-mail" action form.
 */
function flag_actions_system_send_email_action_form(&$form, &$flag, $context) {
  if (!isset($context['recipient'])) {
    $form['recipient']['#default_value'] = '[site:mail]';
  }

  if (!isset($context['subject'])) {
    $form['subject']['#default_value'] = t('Content Flagged @flag_title', array('@flag_title' => $flag->get_title()));
  }

  if (!isset($context['message'])) {
    $form['message']['#default_value'] = t("The @flag_entity_type [flag-action:content-title] has been flagged [flag-action:count] times with the @flag_title flag.\n\nView this @flag_entity_type at [flag-action:content-url].", array('@flag_entity_type' => $flag->entity_type, '@flag_title' => $flag->get_title()));
  }

  $form['help'] = array(
    '#type' => 'fieldset',
    '#title' => t('Tokens'),
    '#description' => t('The following tokens can be used in the recipient, subject, or message.'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
  );
  $form['help']['basic'] = array(
    '#markup' => theme('flag_tokens_browser', array('types' => array('flag', 'flag-action'))),
  );

  $form['help']['tokens'] = array(
    '#type' => 'fieldset',
    '#title' => t('More tokens'),
    '#description' => t("Depending on the type of the content being flagged, the following tokens can be used in the recipients, subject, or message. For example, if the content being flagged is a node, you can use any of the node tokens --but you can't use the comment tokens: they won't be recognized. Similarly, if the content being flagged is a user, you can use only the user tokens."),
    '#value' => theme('flag_tokens_browser', array('types' => $flag->get_labels_token_types(), 'global_types' => FALSE)),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
  );
}
