You are here

function forward_form_submit in Forward 7.3

Same name and namespace in other branches
  1. 5 forward.module \forward_form_submit()
  2. 6 forward.module \forward_form_submit()
  3. 7 forward.module \forward_form_submit()
  4. 7.2 forward.module \forward_form_submit()

Submit callback function for forward form submit

File

./forward.module, line 632
Allows forwarding of entities by email, and provides a record of how often each has been forwarded.

Code

function forward_form_submit($form, &$form_state) {
  global $base_url, $user;
  $recipient_list = _forward_recipient_list($form_state);
  $recipients = $recipient_list['recipients'];
  $token = array(
    'forward' => $recipient_list['token'],
  );
  $dynamic_content = '';

  // Access control:
  // Possibly impersonate another user depending on dynamic block configuration settings
  $access_control = variable_get('forward_block_access_control', 'recipient');
  $switch_user = $access_control == 'recipient' || $access_control == 'anonymous';
  $impersonate_user = variable_get('forward_dynamic_block', 'none') != 'none' && $switch_user;
  if ($impersonate_user) {
    $original_user = $user;
    $old_state = drupal_save_session();
    drupal_save_session(FALSE);
    if ($access_control == 'recipient') {
      $account = user_load_by_mail(trim($form_state['values']['recipients']));

      // Fall back to anonymous user if recipient is not a valid account
      $user = isset($account->status) && $account->status == 1 ? $account : drupal_anonymous_user();
    }
    else {
      $user = drupal_anonymous_user();
    }
  }

  // Compose the body:
  // Note how the form values are accessed the same way they were accessed in the validate function.
  // If selected assemble dynamic footer block.
  switch (variable_get('forward_dynamic_block', '')) {
    case 'node':
      if (module_exists('blog')) {
        $dynamic_content_header = '<h3>' . t('Recent blog posts') . '</h3>';
        $query = db_select('node', 'n');
        $query
          ->fields('n', array(
          'nid',
          'title',
        ));
        $query
          ->condition('n.type', 'blog');
        $query
          ->condition('n.status', 1);
        $query
          ->orderBy('n.created', 'DESC');
        if (variable_get('forward_block_access_control', 'recipient') != 'none') {
          $query
            ->addTag('node_access');
        }
        $dynamic_content = _forward_top5_list($query, $base_url, 'node');
      }
      break;
    case 'user':
      if (variable_get('forward_block_access_control', 'recipient') != 'none' && user_access('access user profiles')) {
        $dynamic_content_header = '<h3>' . t("Who's new") . '</h3>';
        $query = db_select('users', 'u');
        $query
          ->fields('u', array(
          'uid',
          'name',
        ));
        $query
          ->condition('u.status', 0, '<>');
        $query
          ->orderBy('u.uid', 'DESC');
        $dynamic_content = _forward_top5_list($query, $base_url, 'user');
      }
      break;
    case 'comment':
      if (module_exists('comment')) {
        $dynamic_content_header = '<h3>' . t('Recent comments') . '</h3>';
        $query = db_select('comment', 'c');
        $query
          ->fields('c', array(
          'nid',
          'cid',
          'subject',
        ));
        $query
          ->condition('c.status', 1);
        $query
          ->orderBy('c.created', 'DESC');
        if (variable_get('forward_block_access_control', 'recipient') != 'none') {
          $query
            ->addTag('node_access');
        }
        $dynamic_content = _forward_top5_list($query, $base_url, 'comment');
      }
      break;
    case 'popular':
      if (module_exists('statistics')) {
        $dynamic_content_header = '<h3>' . t('Most Popular Content') . '</h3>';
        $query = db_select('node_counter', 's');
        $query
          ->join('node', 'n', 's.nid = n.nid');
        $query
          ->fields('n', array(
          'nid',
          'title',
        ));
        $query
          ->condition('s.totalcount', 0, '>');
        $query
          ->condition('n.status', 1);
        $query
          ->orderBy('s.totalcount', 'DESC');
        if (variable_get('forward_block_access_control', 'recipient') != 'none') {
          $query
            ->addTag('node_access');
        }
        $dynamic_content = _forward_top5_list($query, $base_url, 'node');
      }
      break;
  }

  // Only include header for non-empty dynamic block
  if ($dynamic_content) {
    $dynamic_content = $dynamic_content_header . $dynamic_content;
  }

  // Restore user if impersonating someone else during dynamic block build
  if ($impersonate_user) {
    $user = $original_user;
    drupal_save_session($old_state);
  }

  // Get current language
  $langcode = $GLOBALS['language_content']->language;

  // Initialize
  $content = '';
  $entity = NULL;
  $entity_wrapper = NULL;

  // Send email of appropriate type based on module configuration
  if (!$form_state['values']['path'] || $form_state['values']['path'] == 'epostcard') {
    $emailtype = 'epostcard';
    $returnurl = '';
    $entity_id = 0;
    $entity_type = '';
  }
  else {
    $emailtype = 'email';
    $returnurl = $form_state['values']['path'];
    $entity_type = $form_state['values']['entity_type'];
    $entity_id = $form_state['values']['entity_id'];
    if ($entity_id) {

      //   Forwarding an entity, get entity content
      $entity = entity_load_single($entity_type, $entity_id);
      if (!entity_access('view', $entity_type, $entity)) {
        return MENU_ACCESS_DENIED;
      }
      $entity_wrapper = entity_metadata_wrapper($entity_type, $entity);
      $token['forward']['entity'] = $entity_wrapper;
      if (variable_get('forward_custom_viewmode', FALSE)) {
        $view_mode = 'forward';
        $content = _forward_build_message_content($entity_type, $entity, $entity_id, $view_mode, $langcode);
      }
      if (!$content) {
        $view_mode = variable_get('forward_full_body', FALSE) ? 'full' : 'teaser';
        $content = _forward_build_message_content($entity_type, $entity, $entity_id, $view_mode, $langcode);
      }
      $label = entity_label($entity_type, $entity);
    }
    else {

      // Forwarding a path, get page content
      menu_set_active_item($form_state['values']['path']);
      $content = menu_execute_active_handler(NULL, FALSE);
      if (is_array($content)) {

        // Render the content if the active handler returns a render array
        $content = render($content);
      }
      $label = check_plain(menu_get_active_title());

      // Make sure the path is valid and the user has access
      $headers = drupal_get_http_header();
      if ($headers) {
        foreach ($headers as $header) {
          if (preg_match('/404 Not Found/', $header) == 1) {
            return;
          }
        }
      }
      if ($content == MENU_NOT_FOUND) {
        return MENU_NOT_FOUND;
      }
      if ($content == MENU_ACCESS_DENIED) {
        return MENU_ACCESS_DENIED;
      }
    }
  }
  $token['user'] = $user;
  if (variable_get('forward_message', TRUE)) {
    $message = variable_get('forward_filter_html', FALSE) ? nl2br(filter_xss(token_replace($form_state['values']['message'], $token), explode(',', variable_get('forward_filter_tags', 'p,br,em,strong,cite,code,ul,ol,li,dl,dt,dd')))) : nl2br(check_plain(token_replace($form_state['values']['message'], $token)));
  }
  else {
    $message = FALSE;
  }
  global $theme_key;
  $theme_key = variable_get('theme_default', '');
  $logo = variable_get('forward_header_image', '') == '' ? theme_get_setting('logo') : variable_get('forward_header_image', '');
  $node = $entity_id && $entity_type == 'node' ? node_load($entity_id) : NULL;
  $vars = array(
    'type' => $emailtype,
    'site_name' => check_plain(variable_get('site_name', 'Drupal')),
    'name' => check_plain($form_state['values']['name']),
    'email' => check_plain($form_state['values']['email']),
    'forward_message' => token_replace(t(variable_get('forward_' . $emailtype . '_message', '[forward:sender] thought you would like to see the [site:name] web site.')), $token),
    'message' => $message,
    'base_url' => $base_url,
    'content' => $content,
    'path' => $returnurl,
    'dynamic_content' => $dynamic_content,
    'forward_ad_footer' => variable_get('forward_ad_footer', ''),
    'forward_footer' => variable_get('forward_footer', ''),
    'site_url' => url('forward/emailref', array(
      'absolute' => TRUE,
      'query' => array(
        'path' => '<front>',
      ),
    )),
    'width' => variable_get('forward_width', 400),
    'logo' => !empty($logo) ? '<img src="' . url($logo, array(
      'absolute' => TRUE,
    )) . '" alt="" />' : '',
    'title' => $emailtype == 'email' ? l($label, 'forward/emailref', array(
      'absolute' => TRUE,
      'query' => array(
        'path' => $returnurl,
      ),
    )) : FALSE,
    'submitted' => $emailtype == 'email' && isset($node->type) && variable_get('node_submitted_' . $node->type) ? !empty($node->name) ? t('by %author', array(
      '%author' => $node->name,
    )) : t('by %author', array(
      '%author' => variable_get('anonymous', 'Anonymous'),
    )) : FALSE,
    'entity_type' => $emailtype == 'email' ? $entity_type : FALSE,
    'entity_id' => $emailtype == 'email' ? $entity_id : FALSE,
    'link' => $emailtype == 'email' ? l(t('Click here to read more on our site'), 'forward/emailref', array(
      'absolute' => TRUE,
      'query' => array(
        'path' => $returnurl,
      ),
    )) : FALSE,
  );

  // Use theme template file forward.tpl.php to build the email message body
  $params['body'] = theme('forward', array(
    'vars' => $vars,
  ));

  // Apply filters such as pathologic for link correction
  $filter_format = variable_get('forward_filter_format', '');
  if ($filter_format) {

    // This filter was setup by the forward administrator for this purpose only, whose permission to run the filter was checked at that time
    // Therefore, no need to check again here
    $params['body'] = check_markup($params['body'], $filter_format, $langcode);
  }

  // Email subject
  $params['subject'] = token_replace(t(variable_get('forward_' . $emailtype . '_subject', '[forward:sender] has sent you a message from [site:name]')), $token);

  // Email from address
  $from = variable_get('forward_sender_address', '');
  if (empty($from)) {
    $from = variable_get('site_mail', '');
  }
  $params['from'] = trim(mime_header_encode($form_state['values']['name']) . ' <' . $from . '>');
  $params['headers']['Reply-To'] = trim(mime_header_encode($form_state['values']['name']) . ' <' . $form_state['values']['email'] . '>');

  // Send email to each listed recipient
  foreach ($recipients as $to) {
    drupal_mail('forward', 'forward_page', trim($to), $langcode, $params, $params['from']);

    // Flood control
    flood_register_event('forward');
  }

  // insert into log
  db_insert('forward_log')
    ->fields(array(
    'path' => $form_state['values']['path'],
    'type' => 'SENT',
    'timestamp' => REQUEST_TIME,
    'uid' => $user->uid,
    'hostname' => ip_address(),
  ))
    ->execute();

  // update statistics
  if (!empty($entity_id)) {
    list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
    db_update('forward_statistics')
      ->fields(array(
      'last_forward_timestamp' => REQUEST_TIME,
    ))
      ->expression('forward_count', 'forward_count + 1')
      ->condition('type', $entity_type)
      ->condition('bundle', $bundle)
      ->condition('id', $id)
      ->execute();
  }

  // Increment global counters
  variable_set('forward_total', variable_get('forward_total', 0) + 1);
  variable_set('forward_recipients', variable_get('forward_recipients', 0) + count($recipients));

  // Send thank you email if needed
  drupal_set_message(token_replace(t(variable_get('forward_thankyou', 'Thank you for spreading the word about [site:name]. We appreciate your help.')), $token), 'status');
  if (variable_get('forward_thankyou_send', FALSE)) {
    $thankyou_params = array(
      'from' => $from,
      'subject' => token_replace(t(variable_get('forward_thankyou_subject', 'Thank you for spreading the word about [site:name]')), $token),
      'body' => token_replace(t(variable_get('forward_thankyou_text', "Dear [forward:sender],\n\nThank you for spreading the word about [site:name]. We appreciate your help.")), $token),
    );
    $mail = drupal_mail('forward', 'forward_thankyou', trim($form_state['values']['email']), $langcode, $thankyou_params, $thankyou_params['from']);
  }
  $form_state['redirect'] = $returnurl != '' ? $returnurl : variable_get('forward_epostcard_return', '');

  // CRMAPI integration
  if (module_exists('crmapi')) {
    if (!empty($user->crmapi_contact) && is_numeric($user->crmapi_contact)) {
      $contact = crmapi_contact_load('', $user->crmapi_contact);
      $contact_id = $user->crmapi_contact;
    }
    else {
      $contact['email'] = $form_state['values']['email'];
      $names = explode(' ', $form_state['values']['name']);
      $contact['first_name'] = $names[0];
      $contact['last_name'] = isset($names[2]) ? $names[2] : $names[1];
      $contact['mail_name'] = $form_state['values']['name'];
      $contact_id = crmapi_contact_save($contact);
    }
    $activity_params = array(
      'contact_id' => $contact_id,
      'activity_id' => 'OLForward',
      'activity_type' => 'F',
      'level' => '',
      'flag' => '',
      'description' => substr(url($returnurl, array(
        'absolute' => TRUE,
      )), 0, 100),
    );
    crmapi_activity_save($activity_params);
  }

  // Rules integration
  if (module_exists('rules')) {
    if ($entity_wrapper) {
      rules_invoke_event('entity_forward', $user, $entity_wrapper);

      // Continue to trigger node events for backwards compatibility with 7.x-2.x
      if ($entity_type == 'node') {
        rules_invoke_event('node_forward', $user, $entity);
      }
    }
  }
}