You are here

uc_webform.module in Ubercart Webform Integration 7

Same filename and directory in other branches
  1. 6 uc_webform.module
  2. 7.3 uc_webform.module
  3. 7.2 uc_webform.module

File

uc_webform.module
View source
<?php

/***********************************
 * Drupal Hooks
 */

/**
 * Impliments hook_views_api()
 */
function uc_webform_views_api() {
  return array(
    'api' => 2.0,
    'path' => drupal_get_path('module', 'uc_webform') . '/views',
  );
}

/**
 * Implements hook_menu
 */
function uc_webform_menu() {
  $items = array();
  $items['uc_webform/autocomplete'] = array(
    'title' => 'Ubercart Webform autocomplete',
    'page callback' => 'uc_webform_autocomplete',
    'access callback' => 'user_access',
    'access arguments' => array(
      'edit own webform submissions',
    ),
    'type' => MENU_CALLBACK,
  );
  $items['admin/store/orders/%/webform'] = array(
    'title' => t('Webform Results'),
    'page callback' => 'uc_webform_application',
    'page arguments' => array(
      3,
    ),
    'access arguments' => array(
      'view all orders',
    ),
    'type' => MENU_LOCAL_TASK,
  );
  return $items;
}
function uc_webform_application($oid) {
  $urls = explode('/', $_GET['q']);
  $webform_order_query = db_query('SELECT * FROM {uc_webform_submission} uc LEFT JOIN {webform_submissions} wc ON uc.sid = wc.sid WHERE order_id = :oid', array(
    ':oid' => $urls[3],
  ));
  $display = '<ul>';
  include_once drupal_get_path('module', 'webform') . '/includes/webform.submissions.inc';
  foreach ($webform_order_query as $record) {

    // get the result
    $display .= '<li>' . l('Webform Results', 'node/' . $record->nid . '/submission/' . $record->sid) . '</li>';

    // drupal_render(webform_submission_page($webform, $record->sid, 'html')) . '<hr/>';
  }
  $display .= '</ul>';
  return $display;
}

/**
 * Implements hook_node_load
 */
function uc_webform_node_load($nodes, $types) {
  $result = db_query('SELECT * FROM {uc_webform} WHERE nid IN(:nids)', array(
    ':nids' => array_keys($nodes),
  ));
  foreach ($result as $record) {
    if (uc_product_is_product($nodes[$record->nid])) {
      $nodes[$record->nid]->webform_nid = $record->webform_nid;
      $nodes[$record->nid]->uc_webform_submit = $record->submit;
    }
  }
}

/**
 * Implements hook_node_delete
 */
function uc_webform_node_delete($node) {
  if (!isset($node->webform_nid) || !isset($node->uc_webform_submit)) {
    return;
  }
  db_delete('uc_webform')
    ->condition('nid', $node->nid)
    ->execute();
}

/** 
 * Implements hook_node_insert
 */
function uc_webform_node_insert($node) {
  if (uc_product_is_product($node)) {
    db_insert('uc_webform')
      ->fields(array(
      'nid' => $node->nid,
      'webform_nid' => $node->webform_nid,
      'submit' => $node->uc_webform_submit,
    ))
      ->execute();
  }
}

/**
 * Implements hook_node_update
 */
function uc_webform_node_update($node) {
  uc_webform_node_delete($node);
  uc_webform_node_insert($node);
}

/****************************************
 * Form API 
 */

/**
 * Implements hook_form_FORM_ID_alter
 */
function uc_webform_form_node_form_alter(&$form, &$form_state) {
  if ($form['#node']->type == 'webform') {
    $form['base']['uc_webform_submit'] = array(
      '#type' => 'checkbox',
      '#title' => t('Add this webform to cart on submission?'),
      '#default_value' => isset($form['#node']->uc_webform_submit) ? $form['#node']->uc_webform_submit : FALSE,
    );
    $form['#submit'][] = 'uc_webform_form_node_submit';
  }
  else {
    if (uc_product_is_product($form['#node'])) {
      $form['base']['uc_webform'] = array(
        '#type' => 'feildset',
        '#title' => t('Webform Settings'),
      );
      $form['base']['uc_webform']['webform_nid'] = array(
        '#type' => 'textfield',
        '#title' => t('Application Form'),
        '#autocomplete_path' => 'uc_webform/autocomplete',
        '#default_value' => isset($form['#node']->webform_nid) ? $form['#node']->webform_nid : null,
        '#value_callback' => 'uc_webform_autocomplete_value',
        '#element_validate' => array(
          'uc_webform_autocomplete_validate',
        ),
      );
      $form['base']['uc_webform']['uc_webform_submit'] = array(
        '#type' => 'checkbox',
        '#title' => t('Redirect user to cart after form submission.'),
        '#default_value' => isset($form['#node']->uc_webform_submit) ? $form['#node']->uc_webform_submit : null,
      );
    }
  }
}
function uc_webform_autocomplete($string) {
  $results = db_select('node', 'n')
    ->fields('n')
    ->condition('n.title', '%' . $string . '%', 'LIKE')
    ->condition('n.type', 'webform')
    ->range(0, 10)
    ->execute();
  foreach ($results as $row) {
    $matches[$row->title . " [nid:{$row->nid}]"] = '<div class="reference-autocomplete">' . $row->title . '</div>';
  }
  return drupal_json_output($matches);
}

/**
 * Value callback for a uc_webform autocomplete element.
 *
 * Replace the node nid with a node title.
 */
function uc_webform_autocomplete_value($element, $input = FALSE, $form_state) {
  if ($input === FALSE) {

    // We're building the displayed 'default value': expand the raw nid into
    // "node title [nid:n]".
    $nid = $element['#default_value'];
    if (!empty($nid)) {
      $q = db_select('node', 'n');
      $node_title_alias = $q
        ->addField('n', 'title');
      $q
        ->addTag('node_access')
        ->condition('n.nid', $nid)
        ->range(0, 1);
      $result = $q
        ->execute();

      // @todo If no result (node doesn't exist or no access).
      $value = $result
        ->fetchField();
      $value .= ' [nid:' . $nid . ']';
      return $value;
    }
  }
}

/**
 * Validation callback for a node_reference autocomplete element.
 */
function uc_webform_autocomplete_validate($element, &$form_state, $form) {
  $value = $element['#value'];
  $nid = NULL;
  if (!empty($value)) {

    // Check whether we have an explicit "[nid:n]" input.
    preg_match('/^(?:\\s*|(.*) )?\\[\\s*nid\\s*:\\s*(\\d+)\\s*\\]$/', $value, $matches);
    if (!empty($matches)) {

      // Explicit nid. Check that the 'title' part matches the actual title for
      // the nid.
      list(, $title, $nid) = $matches;
      if (!empty($title)) {
        $real_title = db_select('node', 'n')
          ->fields('n', array(
          'title',
        ))
          ->condition('n.nid', $nid)
          ->execute()
          ->fetchField();
        if (trim($title) != trim($real_title)) {
          form_error($element, t('%name: title mismatch. Please check your selection.', array(
            '%name' => $instance['label'],
          )));
        }
      }
    }
  }
  form_set_value($element, $nid, $form_state);
}
function uc_webform_form_uc_product_add_to_cart_form_alter(&$form, &$form_state) {
  if (isset($form['node']['#value']->webform_nid)) {

    // replace standard add to cart with the webform corresponding to this product
  }
}
function uc_webform_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'webform_component_form' || $form_id == 'webform_component_edit_form') {

    // allow select components to change attributes/options selected for a product, ie via sku
    if ($form['type']['#value'] == 'select') {
      $form['extra']['uc_webform_options'] = array(
        '#title' => t('Product SKU '),
        '#description' => t('You can choose to set what options will be selected by safe_key|option '),
        '#type' => 'textarea',
        '#default_value' => variable_get('uc_webform_sku_' . $form['nid']['#value'] . '_' . $form['cid']['#value'], ''),
      );
      $form['#submit'][] = 'uc_webform_sku_submit';
    }
  }
  if (strpos($form_id, 'webform_client_form') === 0) {
    $form['#submit'][] = 'uc_webform_webform_client_form_submit';
  }
}
function uc_webform_sku_submit(&$form, &$form_state) {
  variable_set('uc_webform_sku_' . $form_state['values']['nid'] . '_' . $form_state['values']['cid'], $form_state['values']['extra']['uc_webform_options']);
}
function uc_webform_webform_client_form_submit(&$form, &$form_state) {
  if (has_completed_webform($form['#node']->nid) == TRUE) {
    $uc_webform_query = db_query('SELECT * FROM {uc_webform} WHERE webform_nid = :nid', array(
      ':nid' => $form['#node']->nid,
    ));
    $uc_webform = null;
    foreach ($uc_webform_query as $record) {
      $uc_webform = $record;
    }

    // we need to get the aid and oid to add this to the cart
    $attributes = array();
    foreach ($form_state['values']['submitted'] as $id => $value) {
      $option_ids = variable_get('uc_webform_sku_' . $form['#node']->nid . '_' . $id, NULL);
      if (isset($option_ids)) {

        // explode the options so that we can set them as part of the add to cart call
        $option_ids = explode("\n", $option_ids);
        $available_options = array();
        foreach ($option_ids as $option) {
          $opt = explode("|", $option);
          $available_options[$opt[0]] = $opt[1];
        }
        $option_ids = $available_options;
        $option_name = $option_ids[$value];

        // This is the selected option submitted in the webform
        $attribute_query = db_query('SELECT aid, oid, name FROM {uc_attribute_options} WHERE name = :name', array(
          ':name' => $option_name,
        ));
        foreach ($attribute_query as $record) {
          $attributes[$record->aid] = $record->oid;
        }
      }
    }
    $cid = isset($cid) ? $cid : uc_cart_get_id();
    $items = uc_cart_get_contents();
    variable_set('uc_webform_cart_item_' . $items[count($items) - 1]->cart_item_id . '_' . $cid, $form_state['values']['details']['sid']);
    uc_cart_add_item($uc_webform->nid, 1, array(
      'attributes' => $attributes,
      'sid' => $form_state['values']['details']['sid'],
    ));
    $product = node_load($uc_webform->nid);
    if ($product->uc_webform__submit == 1) {

      // drupal_goto('cart');
    }
  }
}

/****************************************
 * Ubercart Hooks
 */

/**
 * Implements hook_uc_checkout_pane
 */
function uc_webform_uc_checkout_pane() {
  $panes[] = array(
    'id' => 'application',
    'callback' => 'application_checkout_pane',
    'title' => t('Class application information'),
    'weight' => 4,
  );
  return $panes;
}
function application_checkout_pane($op, $order, $form = NULL, &$form_state = NULL) {
  if (!is_object($order)) {
    return;
  }
}

/*
 * Implements hook_uc_add_to_cart()
 */
function uc_webform_uc_add_to_cart($nid, &$qty, &$data) {
  $cid = isset($cid) ? $cid : uc_cart_get_id();
  $items = uc_cart_get_contents();
  $node = node_load($nid);
  $data['sid'] = $date['sid'];
}
function _uc_webform_add_to_cart($node) {

  // if this product has a webform add that to the cart instead and attach this node as data
  $items = uc_cart_get_contents();
  foreach ($items as $item) {
    if ($item->nid == $node->webform_nid) {
      $item->qty++;
      $item->data['original_node'][$node->nid] = $node;
      uc_cart_update_item($item);
      $found = TRUE;
      break;
    }
  }
  if (!isset($found)) {
    $data['original_node'][$node->nid] = $node;
    uc_cart_add_item($node->webform_nid, 1, $data);
  }
}

/**
 * Implements hook_uc_order()
 */
function uc_webform_uc_order($op, &$arg1, $arg2) {
  switch ($op) {
    case 'save':
      foreach ($arg1->products as $product) {
        if (isset($product->data['sid'])) {
          _uc_webform_save_submission($product->data['sid'], $arg1);
        }
      }

      // _uc_webform_order_load($arg1);
      break;
    case 'new':
    case 'load':

      // _uc_webform_order_load($arg1);
      break;
  }
}

/**
 * Implements hook_uc_cart_item()
 */
function uc_webform_uc_cart_item($op, &$item) {
  switch ($op) {
    case 'load':
      $item->data['sid'] = variable_get('uc_webform_cart_item_' . $item->cart_item_id . '_' . $item->cart_id, null);
      break;
    case 'remove':
      if (isset($item->data['sid'])) {

        // Delete any anonymous session information.
        if (isset($_SESSION['webform_submission'][$item->data['sid']])) {
          unset($_SESSION['webform_submission'][$item->data['sid']]);
        }
        db_delete('webform_submitted_data')
          ->condition('sid', $item->data['sid'])
          ->execute();
        db_delete('webform_submissions')
          ->condition('sid', $item->data['sid'])
          ->execute();
        db_delete('uc_webform_submission')
          ->condition('sid', $item->data['sid'])
          ->execute();
      }
      break;
  }
}

/****************************************
 * Webform Hooks
 */

/**
 * Implements hook_webform_submission_insert()
 */
function uc_webform_webform_submission_insert($node, $submission) {
  $found = FALSE;
  $items = uc_cart_get_contents();
  foreach ($items as $item) {
    if ($item->nid == $submission->nid) {
      $item->data['sid'] = $submission->sid;
      uc_cart_update_item($item);
      $found = TRUE;
    }
  }

  // we didnt find the node in the cart, so lets add it
  if ($found !== TRUE && isset($node->uc_webform_submit) && $node->uc_webform_submit) {
    $data['sid'] = $submission->sid;
    uc_cart_add_item($node->nid, 1, $data);
  }
}

/**
 * Implements hook_webform_submission_delete()
 */
function uc_webform_webform_submission_delete($node, $submission) {
  db_delete('uc_webform_submission')
    ->condition('sid', $submission->sid)
    ->execute();
}

/**
 * Implements hook_webform_submission_load(&$submissions)
 */
function uc_webform_webform_submission_load(&$submissions) {
  foreach ($submissions as $delta => $submission) {
    $query = db_select('uc_webform_submission', 'ucs')
      ->fields('ucs')
      ->condition('sid', $submission->sid)
      ->execute()
      ->fetchAssoc();
    if ($query) {
      $submissions[$delta] = (object) array_merge((array) $submission, $query);
    }
  }
}

/**
 * Implements hook_webform_submission_render_alter() 
 */
function uc_webform_webform_submission_render_alter(&$renderable) {
  if (!isset($renderable['#submission']->order_id)) {
    return;
  }
}

/****************************************
 * Helper functions
 */
function has_completed_webform($webform_nid) {
  global $user;
  $query = db_select('webform_submissions', 'ws');
  $query
    ->leftJoin('uc_webform_submission', 'uc_ws', 'uc_ws.sid = ws.sid');
  $query
    ->leftJoin('uc_orders', 'o', 'uc_ws.order_id = o.order_id');
  $or = db_or();
  $or
    ->condition('o.order_status', 'Completed', '!=')
    ->condition('o.order_status', NULL);
  $row = $query
    ->fields('ws')
    ->fields('o')
    ->condition('ws.nid', $webform_nid)
    ->condition('ws.uid', $user->uid)
    ->condition('ws.is_draft', 0)
    ->condition($or)
    ->execute()
    ->fetchAssoc();
  return (bool) $row;
}
function _uc_webform_save_submission($sid, $order) {
  $fields = array(
    'sid' => $sid,
    'order_id' => $order->order_id,
  );
  db_delete('uc_webform_submission')
    ->condition('sid', $sid)
    ->execute();
  db_insert('uc_webform_submission')
    ->fields($fields)
    ->execute();
}