Skip to content
question_notify.module 9.58 KiB
Newer Older
<?php
// $Id$
/**
 * @file
 * Allows users to be notified when their question is answered.
 * 
 * TODO
 * Tests!
 * Check  submit handler to delete record from notify table when question is deleted (or mass-deleted) from queue
 */

/**
 * Implements hook_trigger_info().
 * 
 * List the triggers defined by this module when actions
 * can be fired. 
 */
function question_notify_trigger_info() {
  return array(
    'question' => array(
      'question_submission' => array(
        'label' => t('After a question is submitted to the queue'),
      ),
      'question_response' => array(
        'label' => t('After a reply is made to a question'),
      ),
    ),
  );
}

/**
 * Implementation of hook_action_info().
 * 
 * Define actions that can be triggered on certain events.
 */
function question_action_info() {
  return array(
    'question_email_questioner_action' => array(
      'label' => t('Send email to questioner'),
      'type' => 'question',
      'configurable' => TRUE,
      'triggers' => array('question_submission', 'question_response'),
    ),
  );
}

/**
 * Configuration form for the "Send email to questioner" action
 */
function question_email_questioner_action_form($context) {
  $form['email'] = array(
    '#title' => t('Email body'),
    '#type' => 'textfield',
    '#description' => t('Enter the body message of the email here.'),
    '#default_value' => 'A question you asked has been answered',
  );
  return $form;
} 

function question_email_questioner_action_submit($form, $form_state) {
  return array('message' => $form_state['values']['email']);
}

function question_email_questioner_action($object, $context) {
  // Check that the email is valid
  if(valid_email_address($object->mail)) {

    // Try to retrieve account information for this email address
    $account = user_load(array('mail' => $email));
    // If the account is not anonymous
    if ($account) {
      $language = user_preferred_language($account);
    }
    else {
      $language = language_default();
    }

    // Build the array of parameters to complete the email template
    $params['question'] = $node->title;
    $params['nid'] = $node->nid;

    // Attempt to send the e-mail to the asker.
    $mail_sent = drupal_mail('question', 'question_submission', $object->mail, $email, $language, $params);

    // Check whether successful
    if ($mail_sent) {
      watchdog('Question', 'Asker notification email sent to @to for question @quest',
              array('@to' => $object->mail, '@quest' => check_plain($node->title)), WATCHDOG_NOTICE);
    }
    else {
      watchdog('Question', 'Asker notification email to @to failed for the "@quest" question.',
             array('@to' => $email, '@quest' => check_plain($node->title)), WATCHDOG_ERROR);
    }
  }
}

/**
 * Implementation of hook_mail().
 * 
 * This function defines the templates for al emails sent from question module.
 */
function question_mail($key, &$message, $params) {
  $message['headers']['Content-Type'] = 'text/html; charset=UTF-8; format=flowed';
  $language = $message['language'];
  $variables = user_mail_tokens($params['account'], $language);
  switch ($key) {
    case 'question_submission':
      $subject = t('You have been assigned a question on !site', $variables, $language->language);
      $body = t('Dear !username,', array('!username' => 'user'), $language->language) . '\n<br/><br/>';
      $body .= t('The following question has been posted on the Teenage Health Freak site.', $language->language) . '\n<br/><br/>';
      $body .= $params['question'];
      break;

    case 'question_response':
      $subject = t('You have been assigned a question on !site', $variables, $language->language);
      $body = t('Dear !username,', array('!username' => 'user'), $language->language) . '\n<br/><br/>';
      $body .= t('The following question has been posted on the Teenage Health Freak site.', $language->language) . '\n<br/><br/>';
      $body .= $params['question'];
      break;      
  }
  $message['body'] = $body;
  $message['subject'] = $subject;
}



/************************************************
 *                                              *
 *     USER QUESTION SUBMISSION                 *
 *                                              *
 ************************************************/

/**
 * Implements hook_form_FORM_ID_alter().
 * 
 * Add new form fields to the question submission form
 * to record user's notification email address.
 */
function question_notify_form_question_ask_form_alter(&$form, &$form_state) {
  // Registered users sign up for notifications with a checkbox
  if (user_is_logged_in()) {
    $form['notify'] = array(
      '#type' => 'checkbox',
      '#title' => t('Notify by e-mail'),
      '#default_value' => FALSE,
      '#weight' => 0,
      '#description' => t('Check this box to receive an email when your question is answered.'),
    );
  }
  // Anonymous users must provide a notification email address
  else {
    $form['email'] = array(
      '#type' => 'textfield',
      '#title' => t('Your email address'),
      '#size' => 40,
      '#maxlength' => 60,
      '#description' => t('If you would like to be notified when your question is answered, please enter your email address'),
    );
  }
  // Add validation and submit handlers for the new fields
  $form['#validate'][] = 'question_notify_question_ask_form_validate';
  $form['#submit'][] = 'question_notify_question_ask_form_submit';
}

/**
 * Implements _form_validate().
 */
function question_notify_question_ask_form_validate(&$form, &$form_state) {
  // Check validity of notification email address
  if (!empty($form_state['values']['email'])) {
    if (!valid_email_address($form_state['values']['email'])) {
      form_set_error('email', t('Please enter a valid email address'));
    }
  }
}

/**
 * Implements _form_submit().
 */
function question_notify_question_ask_form_submit($form, &$form_state) {
  // If an authenticated user asked to be notified, get their user email address
  if (isset($form_state['values']['notify']) && $form_state['values']['notify']) {
    global $user;
    $mail = $user->mail;
  }
  // If an anonymous user asked to be notified, get the (validated) email address
  elseif (!empty($form_state['values']['email'])) {
    $mail = $form_state['values']['email'];
  }
  
  $row = array();
  
  if (isset($mail)) {
    // Make an array containing all the values to insert
    $row = array(
      'qid' => $form_state['storage']['qid'],
      'mail' => $mail,
    );
    // Insert the row
    db_insert('question_notify')->fields($row)->execute();
  }
  
  // Trigger all actions associated with a question submission
  $aids = trigger_get_assigned_actions('question_submission');
  $context = array(
    'group' => 'question',
    'hook' => 'question_submission'
  );
  actions_do(array_keys($aids), (object) $row, $context);
}

/************************************************
 *                                              *
 *     QUESTION QUEUE MANAGEMENT                *
 *                                              *
 ************************************************ /

/**
 * Implements hook_form_FORM_ID_alter().
 * 
 * Alter the question queue form.
 */
function question_notify_form_question_queue_admin_alter(&$form, &$form_state) {
  // Add an additional submit handler
  $form['#submit'][] = 'question_notify_question_queue_multiple_delete_confirm_submit';
}
/**
 * Delete row from question_fields table when corresponding
 * question is deleted from the queue.
 */
function question_notify_question_queue_multiple_delete_confirm_submit($form, &$form_state) {
  if ($form['operation']['#value'] = 'delete' && $form_state['values']['confirm']) {
    foreach ($form_state['values']['questions'] as $qid => $value) {
      $num_deleted = db_delete('question_notify')
        ->condition('qid', $qid)
        ->execute();
    }
  }
}

function question_notify_form_question_delete_confirm_alter(&$form, &$form_state) {
  // Add an additional submit handler
  $form['#submit'][] = 'question_notify_question_queue_delete_confirm_submit';
}

function question_notify_question_queue_delete_confirm_submit($form, &$form_state) {
  if ($form_state['values']['confirm']) {
    $qid = $form_state['values']['qid'];
    $num_deleted = db_delete('question_notify')
        ->condition('qid', $qid)
        ->execute();
  }
}

/************************************************
 *                                              *
 *     RESPOND TO QUESTIONS                     *
 *                                              *
 ************************************************/

/**
 * Implements hook_form_FORM_ID_alter().
 */
function question_notify_form_question_node_form_alter(&$form, &$form_state) {
  // Add additional submit handler
  $form['#submit'][] = 'question_notify_question_node_form_submit';
}

/**
 * Implements _form_submit().
 */
function question_notify_question_node_form_submit(&$elements, &$form_state, $form_id = NULL) {

  // If this node came from the queue
  if (isset($elements['qid'])) {
    
    // If the user asked to be notifed, get the right email address
    $mail = db_query("SELECT mail FROM {question_notify} WHERE qid = :qid", array(':qid' => $elements['qid']['#value']))->fetchField();
  
    // Then delete the notification record from the queue
    $num_deleted = db_delete('question_notify')
      ->condition('qid', $elements['qid']['#value'])
      ->execute();
  }

  $options = new stdClass();
  $options->mail = $mail;
  
  // Trigger all actions associated with a question response
  $aids = trigger_get_assigned_actions('question_response');
  $context = array(
    'group' => 'question',
    'hook' => 'question_response'
  );
  actions_do(array_keys($aids), (object) $options, $context);
}