Advertisement
Guest User

uc_attribute.module

a guest
Aug 7th, 2012
310
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 48.05 KB | None | 0 0
  1. -------------------------------uc_attribute.module------------------------------
  2. <?php
  3.  
  4. /**
  5.  * @file
  6.  * Ubercart Attribute module.
  7.  *
  8.  * Allows customers to buy slightly different products from the same listing.
  9.  *
  10.  * Many manufacturers provide options to their products. This module provides
  11.  * a way for store administrators to consolidate these options into one product
  12.  * instead of listing each combination separately.
  13.  */
  14.  
  15.  
  16. /**
  17.  * Implements hook_help().
  18.  */
  19. function uc_attribute_help($path, $arg) {
  20.   switch ($path) {
  21.     // Help messages for the attributes overview on products and classes.
  22.     case 'node/%/edit/attributes':
  23.       return '<p>' . t('Add attributes to this product using the <a href="!url">add attributes form</a>. You may then adjust the settings for these attributes on this page and go on to configure their options in the <em>Options</em> tab.', array('!url' => url('node/' . $arg[1] . '/edit/attributes/add'))) . '</p>';
  24.     case 'admin/store/products/classes/%/attributes':
  25.       return '<p>' . t('Add attributes to the product class using the <a href="!url">add attributes form</a>. You may then adjust the settings for these attributes on this page and go on to configure their options in the <em>Options</em> tab.', array('!url' => url('admin/store/products/classes/' . $arg[4] . '/attributes/add'))) . '</p>';
  26.  
  27.     // Help message for adding an attribute to a product or class.
  28.     case 'node/%/edit/attributes/add':
  29.     case 'admin/store/products/classes/%/attributes/add':
  30.       return '<p>' . t('Select the attributes you want to add and submit the form.') . '</p>';
  31.  
  32.     // Help message for adjusting the options on a product or class.
  33.     case 'node/%/edit/options':
  34.     case 'admin/store/products/classes/%/options':
  35.       return '<p>' . t('Use the checkboxes to enable options for attributes and the radio buttons to specify the default option. Attributes with no enabled options will be displayed as text fields. Drag and drop the options to reorder them.') . '</p><p>' . t('The cost, price and weight fields will make adjustments against the original product, so you may enter positive or negative amounts here, or enter 0 if the option should make no adjustment.') . '</p>';
  36.  
  37.     // Help message for the product Adjustments tab.
  38.     case 'node/%/edit/adjustments':
  39.       return '<p>' . t('Enter an alternate SKU to be used when the specified set of options are chosen and the product is added to the cart.') . '</p><p>' . t('<b>Warning:</b> Adding or removing attributes from this product will reset all the SKUs on this page to the default product SKU.') . '</p>';
  40.   }
  41. }
  42.  
  43. /**
  44.  * Implements hook_menu().
  45.  */
  46. function uc_attribute_menu() {
  47.   $items['admin/store/products/attributes'] = array(
  48.     'title' => 'Attributes',
  49.     'description' => 'Create and edit product attributes and options.',
  50.     'page callback' => 'uc_attribute_admin',
  51.     'access arguments' => array('administer attributes'),
  52.     'weight' => -8,
  53.     'file' => 'uc_attribute.admin.inc',
  54.   );
  55.   $items['admin/store/products/attributes/add'] = array(
  56.     'title' => 'Add an attribute',
  57.     'description' => 'Add a product attribute.',
  58.     'page callback' => 'drupal_get_form',
  59.     'page arguments' => array('uc_attribute_form'),
  60.     'access arguments' => array('administer attributes'),
  61.     'type' => MENU_LOCAL_ACTION,
  62.     'file' => 'uc_attribute.admin.inc',
  63.   );
  64.   $items['admin/store/products/attributes/%uc_attribute/edit'] = array(
  65.     'title' => 'Edit attribute',
  66.     'description' => 'Edit a product attribute.',
  67.     'page callback' => 'drupal_get_form',
  68.     'page arguments' => array('uc_attribute_form', 4),
  69.     'access arguments' => array('administer attributes'),
  70.     'file' => 'uc_attribute.admin.inc',
  71.   );
  72.   $items['admin/store/products/attributes/%uc_attribute/delete'] = array(
  73.     'title' => 'Delete attribute',
  74.     'description' => 'Delete a product attribute.',
  75.     'page callback' => 'drupal_get_form',
  76.     'page arguments' => array('uc_attribute_delete_confirm', 4),
  77.     'access arguments' => array('administer attributes'),
  78.     'file' => 'uc_attribute.admin.inc',
  79.   );
  80.   $items['admin/store/products/attributes/%uc_attribute/options'] = array(
  81.     'title' => 'Options',
  82.     'description' => "Edit a product attribute's options.",
  83.     'page callback' => 'drupal_get_form',
  84.     'page arguments' => array('uc_attribute_options_form', 4),
  85.     'access arguments' => array('administer attributes'),
  86.     'file' => 'uc_attribute.admin.inc',
  87.   );
  88.   $items['admin/store/products/attributes/%uc_attribute/options/add'] = array(
  89.     'title' => 'Add an option',
  90.     'description' => 'Add a product attribute option.',
  91.     'page callback' => 'drupal_get_form',
  92.     'page arguments' => array('uc_attribute_option_form', 4, NULL),
  93.     'access arguments' => array('administer attributes'),
  94.     'type' => MENU_LOCAL_ACTION,
  95.     'file' => 'uc_attribute.admin.inc',
  96.   );
  97.   $items['admin/store/products/attributes/%uc_attribute/options/%uc_attribute_option/edit'] = array(
  98.     'title' => 'Edit option',
  99.     'description' => 'Edit a product attribute option.',
  100.     'page callback' => 'drupal_get_form',
  101.     'page arguments' => array('uc_attribute_option_form', 4, 6),
  102.     'access arguments' => array('administer attributes'),
  103.     'file' => 'uc_attribute.admin.inc',
  104.   );
  105.   $items['admin/store/products/attributes/%uc_attribute/options/%uc_attribute_option/delete'] = array(
  106.     'title' => 'Delete option',
  107.     'description' => 'Delete a product attribute option.',
  108.     'page callback' => 'drupal_get_form',
  109.     'page arguments' => array('uc_attribute_option_delete_confirm', 4, 6),
  110.     'access arguments' => array('administer attributes'),
  111.     'file' => 'uc_attribute.admin.inc',
  112.   );
  113.  
  114.   // Menu items for default product class attributes and options.
  115.   $items['admin/store/products/classes/%uc_product_class/attributes'] = array(
  116.     'title' => 'Attributes',
  117.     'description' => 'Administer product class attributes.',
  118.     'page callback' => 'drupal_get_form',
  119.     'page arguments' => array('uc_object_attributes_form', 4, 'class'),
  120.     'access callback' => 'uc_attribute_product_class_access',
  121.     'type' => MENU_LOCAL_TASK,
  122.     'weight' => 1,
  123.     'file' => 'uc_attribute.admin.inc',
  124.   );
  125.   $items['admin/store/products/classes/%uc_product_class/options'] = array(
  126.     'title' => 'Options',
  127.     'description' => 'Administer product class options.',
  128.     'page callback' => 'drupal_get_form',
  129.     'page arguments' => array('uc_object_options_form', 4, 'class'),
  130.     'access callback' => 'uc_attribute_product_class_access',
  131.     'type' => MENU_LOCAL_TASK,
  132.     'weight' => 2,
  133.     'file' => 'uc_attribute.admin.inc',
  134.   );
  135.  
  136.   // Insert subitems into the edit node page for product types.
  137.   $items['node/%node/edit/attributes'] = array(
  138.     'title' => 'Attributes',
  139.     'description' => 'Edit product attributes.',
  140.     'page callback' => 'drupal_get_form',
  141.     'page arguments' => array('uc_object_attributes_form', 1, 'product', 'overview'),
  142.     'access callback' => 'uc_attribute_product_access',
  143.     'access arguments' => array(1),
  144.     'type' => MENU_LOCAL_TASK,
  145.     'weight' => 1,
  146.     'file' => 'uc_attribute.admin.inc',
  147.   );
  148.   $items['node/%node/edit/attributes/add'] = array(
  149.     'title' => 'Add an attribute',
  150.     'description' => 'Add an attribute to this product.',
  151.     'page callback' => 'drupal_get_form',
  152.     'page arguments' => array('uc_object_attributes_form', 1, 'product', 'add'),
  153.     'access callback' => 'uc_attribute_product_access',
  154.     'access arguments' => array(1),
  155.     'type' => MENU_LOCAL_ACTION,
  156.     'weight' => 1,
  157.     'file' => 'uc_attribute.admin.inc',
  158.   );
  159.   $items['node/%node/edit/options'] = array(
  160.     'title' => 'Options',
  161.     'description' => 'Administer product attribute options.',
  162.     'page callback' => 'drupal_get_form',
  163.     'page arguments' => array('uc_object_options_form', 1, 'product'),
  164.     'access callback' => 'uc_attribute_product_option_access',
  165.     'access arguments' => array(1),
  166.     'type' => MENU_LOCAL_TASK,
  167.     'weight' => 2,
  168.     'file' => 'uc_attribute.admin.inc',
  169.   );
  170.   $items['node/%node/edit/adjustments'] = array(
  171.     'title' => 'Adjustments',
  172.     'description' => 'Administer SKU adjustments for different variants of this product.',
  173.     'page callback' => 'drupal_get_form',
  174.     'page arguments' => array('uc_product_adjustments_form', 1),
  175.     'access callback' => 'uc_attribute_product_option_access',
  176.     'access arguments' => array(1),
  177.     'type' => MENU_LOCAL_TASK,
  178.     'weight' => 3,
  179.     'file' => 'uc_attribute.admin.inc',
  180.   );
  181.  
  182.   return $items;
  183. }
  184.  
  185. /**
  186.  * Implements hook_admin_paths().
  187.  */
  188. function uc_attribute_admin_paths() {
  189.   $paths = array(
  190.     'node/*/edit/attributes' => TRUE,
  191.     'node/*/edit/attributes/add' => TRUE,
  192.     'node/*/edit/options' => TRUE,
  193.     'node/*/edit/adjustments' => TRUE,
  194.   );
  195.  
  196.   return $paths;
  197. }
  198.  
  199. /**
  200.  * Access callback for editing a product class's attributes and options.
  201.  */
  202. function uc_attribute_product_class_access() {
  203.   return user_access('administer product classes') && user_access('administer attributes');
  204. }
  205.  
  206. /**
  207.  * Access callback for editing a product's attributes.
  208.  */
  209. function uc_attribute_product_access($node) {
  210.   if ($node->type == 'product_kit') {
  211.     return FALSE;
  212.   }
  213.  
  214.   return uc_product_is_product($node) && node_access('update', $node) && (user_access('administer attributes') || user_access('administer product attributes'));
  215. }
  216.  
  217. /**
  218.  * Access callback for editing a product's options.
  219.  */
  220. function uc_attribute_product_option_access($node) {
  221.   if ($node->type == 'product_kit') {
  222.     return FALSE;
  223.   }
  224.  
  225.   return uc_product_is_product($node) && isset($node->attributes) && node_access('update', $node) && (user_access('administer attributes') || user_access('administer product attributes') || user_access('administer product options'));
  226. }
  227.  
  228. /**
  229.  * Implements hook_permission().
  230.  */
  231. function uc_attribute_permission() {
  232.   return array(
  233.     'administer attributes' => array(
  234.       'title' => t('Administer attributes'),
  235.     ),
  236.     'administer product attributes' => array(
  237.       'title' => t('Administer product attributes'),
  238.     ),
  239.     'administer product options' => array(
  240.       'title' => t('Administer product options'),
  241.     ),
  242.   );
  243. }
  244.  
  245. /**
  246.  * Implements hook_theme().
  247.  */
  248. function uc_attribute_theme() {
  249.   return array(
  250.     'uc_attribute_option' => array(
  251.       'variables' => array('option' => '', 'price' => ''),
  252.       'file' => 'uc_attribute.theme.inc',
  253.     ),
  254.     'uc_attribute_add_to_cart' => array(
  255.       'render element' => 'form',
  256.       'file' => 'uc_attribute.theme.inc',
  257.     ),
  258.     'uc_object_attributes_form' => array(
  259.       'render element' => 'form',
  260.       'file' => 'uc_attribute.admin.inc',
  261.     ),
  262.     'uc_object_options_form' => array(
  263.       'render element' => 'form',
  264.       'file' => 'uc_attribute.admin.inc',
  265.     ),
  266.     'uc_attribute_options_form' => array(
  267.       'render element' => 'form',
  268.       'file' => 'uc_attribute.admin.inc',
  269.     ),
  270.     'uc_product_attributes' => array(
  271.       'render element' => 'attributes',
  272.       'file' => 'uc_attribute.admin.inc',
  273.     ),
  274.   );
  275. }
  276.  
  277. /**
  278.  * Implements hook_form_FORM_ID_alter() for uc_product_settings_form().
  279.  */
  280. function uc_attribute_form_uc_product_settings_form_alter(&$form, &$form_state) {
  281.   $form['attributes'] = array(
  282.     '#type' => 'fieldset',
  283.     '#title' => 'Attribute settings',
  284.     '#group' => 'product-settings',
  285.     '#weight' => -3,
  286.   );
  287.   $form['attributes']['uc_attribute_option_price_format'] = array(
  288.     '#type' => 'radios',
  289.     '#title' => t('Option price format'),
  290.     '#default_value' => variable_get('uc_attribute_option_price_format', 'adjustment'),
  291.     '#options' => array('none' => t('Do not display'),
  292.       'adjustment' => t('Display price adjustment'),
  293.       'total' => t('Display total price'),
  294.     ),
  295.     '#description' => t('Determines how price variations are displayed to the customer. Prices may be displayed directly next to each attribute option in the attribute selection form either as a total price for the product with that option or as an adjustment (+ or -) showing how that option affects the product base price. Note that the price will always be displayed as an adjustment for attributes that can have multiple options (using checkboxes).'),
  296.    );
  297. }
  298.  
  299. /**
  300.  * Implements hook_module_implements_alter().
  301.  *
  302.  * Ensures that attribute form changes are made after (e.g.) product kits.
  303.  */
  304. function uc_attribute_module_implements_alter(&$implementations, $hook) {
  305.   if ($hook == 'uc_form_alter') {
  306.     $group = $implementations['uc_attribute'];
  307.     unset($implementations['uc_attribute']);
  308.     $implementations['uc_attribute'] = $group;
  309.   }
  310. }
  311.  
  312. /**
  313.  * Implements hook_uc_form_alter().
  314.  *
  315.  * Attaches option selectors to the form with the "Add to Cart" button.
  316.  *
  317.  * This function also handles selecting attributes for products added to orders
  318.  * manually.
  319.  */
  320. function uc_attribute_uc_form_alter(&$form, &$form_state, $form_id) {
  321.   if (strpos($form_id, 'add_to_cart_form') || $form_id == 'uc_order_add_product_form') {
  322.     $use_ajax = strpos($form_id, 'add_to_cart_form') && variable_get('uc_product_update_node_view', FALSE);      
  323.     $node =& $form['node']['#value'];
  324.     $id = $form_id . '-' . $node->nid . '-attributes';
  325.     // If the node has a product list, add attributes to them.
  326.     if (isset($form['products']) || isset($form['sub_products'])) {
  327.       if (isset($form['products'])) {
  328.         $element = &$form['products'];
  329.       }
  330.       else {
  331.         $element = &$form['sub_products'];
  332.       }
  333.       foreach (element_children($element) as $key) {
  334.         $element[$key]['attributes'] = _uc_attribute_alter_form($id . '-' . $key, $node->products[$key], $use_ajax);
  335.        
  336.         if (is_array($element[$key]['attributes'])) {
  337.           $element[$key]['attributes']['#tree'] = TRUE;
  338.           $element[$key]['#type'] = 'fieldset';
  339.         }
  340.       }
  341.     }
  342.     // If not, add attributes to the node.
  343.     else {
  344.      $form['attributes'] = _uc_attribute_alter_form($id, $node, $use_ajax);
  345.  
  346.       if (is_array($form['attributes'])) {
  347.         $form['attributes']['#tree'] = TRUE;
  348.         $form['attributes']['#weight'] = -1;
  349.       }
  350.     }
  351.   }
  352. }
  353.  
  354. /**
  355.  * Implements hook_node_load().
  356.  */
  357. function uc_attribute_node_load($nodes, $types) {
  358.   $product_types = array_intersect(uc_product_types(), $types);
  359.  
  360.   if (empty($product_types)) {
  361.     return;
  362.   }
  363.  
  364.   foreach ($nodes as &$node) {
  365.     if (uc_product_is_product($node->type)) {
  366.       $attributes = uc_product_get_attributes($node->nid);
  367.       if (is_array($attributes) && !empty($attributes)) {
  368.         $node->attributes = $attributes;
  369.       }
  370.     }
  371.   }
  372. }
  373.  
  374. /**
  375.  * Implements hook_node_insert().
  376.  */
  377. function uc_attribute_node_insert($node) {
  378.   // Set attributes from class attributes.
  379.   $select = db_select('uc_class_attributes', 'ca')
  380.     ->fields('ca', array(
  381.       'aid',
  382.       'label',
  383.       'ordering',
  384.       'required',
  385.       'display',
  386.       'default_option',
  387.     ))
  388.     ->condition('pcid', $node->type);
  389.   // SELECT $node->nid AS nid
  390.   $select->addExpression(':nid', 'nid', array(':nid' => $node->nid));
  391.  
  392.   db_insert('uc_product_attributes')
  393.     ->from($select)
  394.     ->execute();
  395.  
  396.   // Set options from class options.
  397.   $select = db_select('uc_class_attribute_options', 'co')
  398.     ->fields('co', array(
  399.       'oid',
  400.       'cost',
  401.       'price',
  402.       'weight',
  403.       'ordering',
  404.     ))
  405.     ->condition('pcid', $node->type);
  406.   $select->addExpression(':nid', 'nid', array(':nid' => $node->nid));
  407.  
  408.   db_insert('uc_product_options')
  409.     ->from($select)
  410.     ->execute();
  411. }
  412.  
  413. /**
  414.  * Implements hook_node_delete().
  415.  */
  416. function uc_attribute_node_delete($node) {
  417.   db_delete('uc_product_options')
  418.     ->condition('nid', $node->nid)
  419.     ->execute();
  420.  
  421.   db_delete('uc_product_adjustments')
  422.     ->condition('nid', $node->nid)
  423.     ->execute();
  424.  
  425.   db_delete('uc_product_attributes')
  426.     ->condition('nid', $node->nid)
  427.     ->execute();
  428. }
  429.  
  430. /**
  431.  * Implements hook_node_update_index().
  432.  */
  433. function uc_attribute_node_update_index($node) {
  434.   $output = '';
  435.  
  436.   $attributes = uc_product_get_attributes($node->nid);
  437.   foreach ($attributes as $attribute) {
  438.     $output .= '<h3>' . _uc_attribute_get_name($attribute) . '</h3>';
  439.  
  440.     foreach ($attribute->options as $option) {
  441.       $output .= $option->name . ' ';
  442.     }
  443.  
  444.     $output .= "\n";
  445.   }
  446.  
  447.   $result = db_query("SELECT model FROM {uc_product_adjustments} WHERE nid = :nid", array(':nid' => $node->nid));
  448.   while ($model = $result->fetchField()) {
  449.     $output .= '<h2>' . $model . "</h2>\n";
  450.   }
  451.  
  452.   return $output;
  453. }
  454.  
  455. /**
  456.  * Implements hook_uc_product_models().
  457.  */
  458. function uc_attribute_uc_product_models($nid) {
  459.   // Get all the SKUs for all the attributes on this node.
  460.   $models = db_query("SELECT DISTINCT model FROM {uc_product_adjustments} WHERE nid = :nid", array(':nid' => $nid))->fetchCol();
  461.  
  462.   return $models;
  463. }
  464.  
  465. /**
  466.  * Stores the customer's choices in the cart.
  467.  */
  468. function uc_attribute_uc_add_to_cart_data($form_values) {
  469.   if (isset($form_values['attributes'])) {
  470.     return array('attributes' => $form_values['attributes']);
  471.   }
  472.   else {
  473.     return array('attributes' => array());
  474.   }
  475. }
  476.  
  477. /**
  478.  * Implements hook_uc_order_product_alter().
  479.  */
  480. function uc_attribute_uc_order_product_alter(&$product, $order) {
  481.   // Convert the attribute and option ids to their current names. This
  482.   // preserves the important data in case the attributes or options are
  483.   // changed later.
  484.   if (!empty($product->data['attributes'])) {
  485.     $attributes_keys = array_keys($product->data['attributes']);
  486.     if (is_numeric(array_shift($attributes_keys))) {
  487.       $attributes = array();
  488.       $options = _uc_cart_product_get_options($product);
  489.       foreach ($options as $aid => $option) {
  490.         $attributes[$option['attribute']][$option['oid']] = $option['name'];
  491.       }
  492.       $product->data['attributes'] = $attributes;
  493.     }
  494.   }
  495. }
  496.  
  497. /**
  498.  * Implements hook_uc_product_class().
  499.  */
  500. function uc_attribute_uc_product_class($type, $op) {
  501.   switch ($op) {
  502.     case 'delete':
  503.       db_delete('uc_class_attributes')
  504.         ->condition('pcid', $type)
  505.         ->execute();
  506.  
  507.       db_delete('uc_class_attribute_options')
  508.         ->condition('pcid', $type)
  509.         ->execute();
  510.  
  511.       break;
  512.   }
  513. }
  514.  
  515. /**
  516.  * Implements hook_uc_product_alter().
  517.  */
  518. function uc_attribute_uc_product_alter(&$node) {
  519.   if (isset($node->data['attributes']) && is_array($node->data['attributes'])) {
  520.     $options = _uc_cart_product_get_options($node);
  521.     foreach ($options as $option) {
  522.       $node->cost += $option['cost'];
  523.       $node->price += $option['price'];
  524.       $node->weight += $option['weight'];
  525.     }
  526.  
  527.     $combination = array();
  528.     foreach ($node->data['attributes'] as $aid => $value) {
  529.       if (is_numeric($value)) {
  530.         $attribute = uc_attribute_load($aid, $node->nid, 'product');
  531.         if ($attribute && ($attribute->display == 1 || $attribute->display == 2)) {
  532.           $combination[$aid] = $value;
  533.         }
  534.       }
  535.     }
  536.     ksort($combination);
  537.  
  538.     $model = db_query("SELECT model FROM {uc_product_adjustments} WHERE nid = :nid AND combination LIKE :combo", array(':nid' => $node->nid, ':combo' => serialize($combination)))->fetchField();
  539.  
  540.     if (!empty($model)) {
  541.       $node->model = $model;
  542.     }
  543.   }
  544. }
  545.  
  546. /**
  547.  * Implements hook_uc_product_description().
  548.  */
  549. function uc_attribute_uc_product_description($product) {
  550.   $description = array(
  551.     'attributes' => array(
  552.       '#product' => array(
  553.         '#type' => 'value',
  554.         '#value' => $product,
  555.       ),
  556.       '#theme' => 'uc_product_attributes',
  557.       '#weight' => 1,
  558.     ),
  559.   );
  560.  
  561.   $desc =& $description['attributes'];
  562.  
  563.   // Cart version of the product has numeric attribute => option values so we
  564.   // need to retrieve the right ones.
  565.   $weight = 0;
  566.   if (empty($product->order_id)) {
  567.     foreach (_uc_cart_product_get_options($product) as $option) {
  568.       if (!isset($desc[$option['aid']])) {
  569.         $desc[$option['aid']]['#attribute_name'] = $option['attribute'];
  570.         $desc[$option['aid']]['#options'] = array($option['name']);
  571.       }
  572.       else {
  573.         $desc[$option['aid']]['#options'][] = $option['name'];
  574.       }
  575.       $desc[$option['aid']]['#weight'] = $weight++;
  576.     }
  577.   }
  578.   elseif (isset($product->data['attributes'])) {
  579.     foreach ($product->data['attributes'] as $attribute => $option) {
  580.       $desc[] = array(
  581.         '#attribute_name' => $attribute,
  582.         '#options' => $option,
  583.         '#weight' => $weight++,
  584.       );
  585.     }
  586.   }
  587.  
  588.   return $description;
  589. }
  590.  
  591. /**
  592.  * Loads attribute objects from the database.
  593.  *
  594.  * @todo If we feel it necessary, we could optimize this, by inverting the
  595.  * logic; that is, we could make uc_attribute load call this function and allow
  596.  * this function to minimize the number of queries necessary. -cha0s
  597.  *
  598.  * @param $aids
  599.  *   Attribute IDs to load.
  600.  * @param $type
  601.  *   The type of attribute. 'product', or 'class'. Any other type will fetch
  602.  *   a base attribute.
  603.  * @param $id
  604.  *   The ID of the product/class this attribute belongs to.
  605.  *
  606.  * @return
  607.  *   An array of loaded attributes.
  608.  */
  609. function uc_attribute_load_multiple($aids = array(), $type = '', $id = NULL) {
  610.   $sql = uc_attribute_type_info($type);
  611.  
  612.   // Product/class attributes.
  613.   if (!empty($type)) {
  614.     // Seems like a big query to get attribute IDs, but it's all about the sort.
  615.     // (I'm not sure if the default ordering is propagating down correctly here.
  616.     // It appears that product/class attributes with no ordering won't let the
  617.     // attribute's propagate down, as it does when loading. -cha0s)
  618.     $query = db_select($sql['attr_table'], 'uca')
  619.       ->fields('uca', array('aid'))
  620.       ->condition("uca.{$sql['id']}", $id);
  621.  
  622.     $query->leftJoin('uc_attributes', 'ua', 'uca.aid = ua.aid');
  623.  
  624.     $query->orderBy('uca.ordering')
  625.       ->orderBy('ua.name');
  626.   }
  627.   // Base attributes.
  628.   else {
  629.     $query = db_select('uc_attributes', 'ua')
  630.       ->fields('ua', array('aid'))
  631.       ->orderBy('ordering')
  632.       ->orderBy('name');
  633.   }
  634.  
  635.   // Filter by the attribute IDs requested.
  636.   if (!empty($aids)) {
  637.     // Sanity check - filter out non-numeric attribute IDs.
  638.     $aids = array_filter($aids, 'is_numeric');
  639.     $query->condition('ua.aid', $aids, 'IN');
  640.   }
  641.  
  642.   $aids = $query->execute()->fetchCol();
  643.  
  644.   // Load the attributes.
  645.   $attributes = array();
  646.   foreach ($aids as $aid) {
  647.     $attributes[$aid] = uc_attribute_load($aid, $id, $type);
  648.   }
  649.  
  650.   return $attributes;
  651. }
  652.  
  653. /**
  654.  * Loads an attribute from the database.
  655.  *
  656.  * @param $aid
  657.  *   The ID of the attribute.
  658.  * @param $type
  659.  *   The type of attribute. 'product', or 'class'. Any other type will fetch
  660.  *   a base attribute.
  661.  * @param $id
  662.  *   The ID of the product/class this attribute belongs to.
  663.  *
  664.  * @return
  665.  *   The attribute object, or FALSE if it doesn't exist.
  666.  */
  667. function uc_attribute_load($aid, $id = NULL, $type = '') {
  668.   $sql = uc_attribute_type_info($type);
  669.  
  670.   switch ($type) {
  671.     case 'product':
  672.     case 'class':
  673.  
  674.       // Read attribute data.
  675.       $query = db_select('uc_attributes', 'a')
  676.         ->fields('a', array('aid', 'name', 'description'))
  677.         ->condition('a.aid', $aid);
  678.  
  679.       $query->leftJoin($sql['attr_table'], 'pa', "a.aid = pa.aid AND pa.{$sql['id']} = :id", array(':id' => $id));
  680.       $query->fields('pa', array('label', 'default_option', 'required', 'ordering', 'display', $sql['id']));
  681.       $query->addField('a', 'label', 'default_label');
  682.       $query->addField('a', 'ordering', 'default_ordering');
  683.       $query->addField('a', 'required', 'default_required');
  684.       $query->addField('a', 'display', 'default_display');
  685.  
  686.       $attribute = $query->execute()->fetchObject();
  687.  
  688.       // Don't try to build it further if it failed already.
  689.       if (!$attribute) return FALSE;
  690.  
  691.       // Set any missing defaults.
  692.       foreach (array('ordering', 'required', 'display', 'label') as $field) {
  693.         if (isset($attribute->{"default_$field"}) && is_null($attribute->$field)) {
  694.           $attribute->$field = $attribute->{"default_$field"};
  695.         }
  696.       }
  697.       if (empty($attribute->label)) {
  698.         $attribute->label = $attribute->name;
  699.       }
  700.  
  701.       // Read option data.
  702.       $query = db_select($sql['opt_table'], 'po')
  703.         ->fields('po', array($sql['id'], 'oid', 'cost', 'price', 'weight', 'ordering'));
  704.       $query->leftJoin('uc_attribute_options', 'ao', "po.oid = ao.oid AND po.{$sql['id']} = :id", array(':id' => $id));
  705.       $query->fields('ao', array('name', 'aid'))
  706.         ->condition('aid', $aid)
  707.         ->orderBy('po.ordering')
  708.         ->orderBy('ao.name');
  709.  
  710.       $result = $query->execute();
  711.     break;
  712.  
  713.     default:
  714.  
  715.       // Read attribute and option data.
  716.       $attribute = db_query("SELECT * FROM {uc_attributes} WHERE aid = :aid", array(':aid' => $aid))->fetchObject();
  717.       $result = db_query("SELECT * FROM {uc_attribute_options} WHERE aid = :aid ORDER BY ordering, name", array(':aid' => $aid));
  718.  
  719.       // Don't try to build it further if it failed already.
  720.       if (!$attribute) {
  721.         return FALSE;
  722.       }
  723.  
  724.     break;
  725.   }
  726.  
  727.   // Got an attribute?
  728.   if ($attribute) {
  729.     // Get its options, too.
  730.     $attribute->options = array();
  731.     foreach ($result as $option) {
  732.       $attribute->options[$option->oid] = $option;
  733.     }
  734.   }
  735.  
  736.   return $attribute;
  737. }
  738.  
  739. /**
  740.  * Fetches an array of attribute objects that belong to a product.
  741.  *
  742.  * @param $nid
  743.  *   Product whose attributes to load.
  744.  *
  745.  * @return
  746.  *   The array of attribute objects.
  747.  */
  748. function uc_attribute_load_product_attributes($nid) {
  749.   return uc_attribute_load_multiple(array(), 'product', $nid);
  750. }
  751.  
  752. /**
  753.  * Saves an attribute object to the database.
  754.  *
  755.  * @param $attribute
  756.  *   The attribute object to save.
  757.  *
  758.  * @return
  759.  *   The integer result from drupal_write_record().
  760.  */
  761. function uc_attribute_save(&$attribute) {
  762.   // Insert or update?
  763.   $key = empty($attribute->aid) ? array() : 'aid';
  764.   return drupal_write_record('uc_attributes', $attribute, $key);
  765. }
  766.  
  767. /**
  768.  * Deletes an attribute from the database.
  769.  *
  770.  * @param $aid
  771.  *   Attribute ID to delete.
  772.  *
  773.  * @return
  774.  *   The Drupal SAVED_DELETED flag.
  775.  */
  776. function uc_attribute_delete($aid) {
  777.   // Delete the class attributes and their options.
  778.   uc_attribute_subject_delete($aid, 'class');
  779.  
  780.   // Delete the product attributes and their options.
  781.   uc_attribute_subject_delete($aid, 'product');
  782.  
  783.   // Delete base attributes and their options.
  784.   db_delete('uc_attribute_options')
  785.     ->condition('aid', $aid)
  786.     ->execute();
  787.   db_delete('uc_attributes')
  788.     ->condition('aid', $aid)
  789.     ->execute();
  790.  
  791.   return SAVED_DELETED;
  792. }
  793.  
  794. /**
  795.  * Loads an attribute option from the database.
  796.  *
  797.  * @param $oid
  798.  *   Option ID to load.
  799.  *
  800.  * @return
  801.  *   The attribute option object.
  802.  */
  803. function uc_attribute_option_load($oid) {
  804.   return db_query("SELECT * FROM {uc_attribute_options} WHERE oid = :oid", array(':oid' => $oid))->fetchObject();
  805. }
  806.  
  807. /**
  808.  * Saves an attribute object to the database.
  809.  *
  810.  * @param $option
  811.  *   The attribute option object to save.
  812.  *
  813.  * @return
  814.  *   The integer result from drupal_write_record().
  815.  */
  816. function uc_attribute_option_save(&$option) {
  817.   // Insert or update?
  818.   $key = empty($option->oid) ? array() : 'oid';
  819.   return drupal_write_record('uc_attribute_options', $option, $key);
  820. }
  821.  
  822. /**
  823.  * Deletes an attribute option from the database.
  824.  *
  825.  * @param $oid
  826.  *   Option ID to delete.
  827.  *
  828.  * @return
  829.  *   The Drupal SAVED_DELETED flag.
  830.  */
  831. function uc_attribute_option_delete($oid) {
  832.   // Delete the class attribute options.
  833.   uc_attribute_subject_option_delete($oid, 'class');
  834.  
  835.   // Delete the product attribute options (and the adjustments!).
  836.   uc_attribute_subject_option_delete($oid, 'product');
  837.  
  838.   // Delete base attributes and their options.
  839.   db_delete('uc_attribute_options')
  840.     ->condition('oid', $oid)
  841.     ->execute();
  842.  
  843.   return SAVED_DELETED;
  844. }
  845.  
  846. /**
  847.  * Saves a product/class attribute.
  848.  *
  849.  * @param &$attribute
  850.  *   The product/class attribute.
  851.  * @param $type
  852.  *   Is this a product or a class?
  853.  * @param $id
  854.  *   The product/class ID.
  855.  * @param $save_options
  856.  *   Save the product/class attribute's options, too?
  857.  *
  858.  * @return
  859.  *   The integer result from drupal_write_record().
  860.  */
  861. function uc_attribute_subject_save(&$attribute, $type, $id, $save_options = FALSE) {
  862.   $sql = uc_attribute_type_info($type);
  863.  
  864.   // Insert or update?
  865.   $key = uc_attribute_subject_exists($attribute->aid, $type, $id) ? array('aid', $sql['id']) : array();
  866.  
  867.   // First, save the options. First because if this is an insert, we'll set
  868.   // a default option for the product/class attribute.
  869.   if ($save_options && is_array($attribute->options)) {
  870.     foreach ($attribute->options as $option) {
  871.       // Sanity check!
  872.       $option = (object) $option;
  873.       uc_attribute_subject_option_save($option, $type, $id);
  874.     }
  875.  
  876.     // Is this an insert? If so, we'll set the default option.
  877.     if (empty($key)) {
  878.       $default_option = 0;
  879.       // Make the first option (if any) the default.
  880.       if (!empty($attribute->options) && is_array($attribute->options)) {
  881.         $option = (object) reset($attribute->options);
  882.         $default_option = $option->oid;
  883.       }
  884.       $attribute->default_option = $default_option;
  885.     }
  886.   }
  887.  
  888.   // Merge in the product/class attribute's ID and save.
  889.   $attribute->{$type == 'product' ? 'nid' : 'pcid'} = $id;
  890.   $result = drupal_write_record($sql['attr_table'], $attribute, $key);
  891.  
  892.   return $result;
  893. }
  894.  
  895. /**
  896.  * Deletes an attribute and all options associated with it.
  897.  *
  898.  * @param $aid
  899.  *   The base attribute ID.
  900.  * @param $type
  901.  *   Is this a product or a class?
  902.  * @param $id
  903.  *   The product/class ID.
  904.  *
  905.  * @return
  906.  *   The Drupal SAVED_DELETED flag.
  907.  */
  908. function uc_attribute_subject_delete($aid, $type, $id = NULL) {
  909.   $sql = uc_attribute_type_info($type);
  910.  
  911.   $query = db_select('uc_attribute_options', 'a')
  912.     ->fields('a', array('oid'));
  913.   $query->join($sql['opt_table'], 'subject', 'a.oid = subject.oid');
  914.  
  915.   // Base conditions, and an ID check if necessary.
  916.   $conditions = db_and()
  917.     ->condition('aid', $aid);
  918.   if ($id) {
  919.     $conditions->condition($sql['id'], $id);
  920.   }
  921.  
  922.   $query->condition($conditions);
  923.   $result = $query->execute();
  924.   while ($oid = $result->fetchField()) {
  925.     // Don't delete the adjustments one at a time. We'll do it in bulk soon for
  926.     // efficiency.
  927.     uc_attribute_subject_option_delete($oid, $type, $id, FALSE);
  928.   }
  929.   db_delete($sql['attr_table'])
  930.     ->condition($conditions)
  931.     ->execute();
  932.  
  933.   // If this is a product attribute, wipe any associated adjustments.
  934.   if ($type == 'product') {
  935.     uc_attribute_adjustments_delete(array(
  936.       'aid' => $aid,
  937.       'nid' => $id,
  938.     ));
  939.   }
  940.  
  941.   return SAVED_DELETED;
  942. }
  943.  
  944. /**
  945.  * Loads a product/class attribute option.
  946.  *
  947.  * @param $oid
  948.  *   The product/class attribute option ID.
  949.  * @param $type
  950.  *   Is this a product or a class?
  951.  * @param $id
  952.  *   The product/class ID.
  953.  *
  954.  * @return
  955.  *   An object containing the product/class attribute option.
  956.  */
  957. function uc_attribute_subject_option_load($oid, $type, $id) {
  958.   $sql = uc_attribute_type_info($type);
  959.  
  960.   $query = db_select($sql['opt_table'], 'po');
  961.   $query->leftJoin('uc_attribute_options', 'ao', 'po.oid = ao.oid');
  962.   $query->fields('po', array($sql['id'], 'oid', 'cost', 'price', 'weight', 'ordering'))
  963.     ->fields('ao', array('name', 'aid'))
  964.     ->condition('po.oid', $oid)
  965.     ->condition("po.{$sql['id']}", $id)
  966.     ->orderBy('po.ordering')
  967.     ->orderBy('ao.name');
  968.  
  969.   return $query->execute()->fetchObject();
  970. }
  971.  
  972. /**
  973.  * Saves a product/class attribute option.
  974.  *
  975.  * @param &$option
  976.  *   The product/class attribute option.
  977.  * @param $type
  978.  *   Is this a product or a class?
  979.  * @param $id
  980.  *   The product/class ID.
  981.  *
  982.  * @return
  983.  *   The integer result from drupal_write_record().
  984.  */
  985. function uc_attribute_subject_option_save(&$option, $type, $id) {
  986.   $sql = uc_attribute_type_info($type);
  987.  
  988.   // Insert or update?
  989.   $key = uc_attribute_subject_option_exists($option->oid, $type, $id) ? array('oid', $sql['id']) : array();
  990.  
  991.   // Merge in the product/class attribute option's ID, and save.
  992.   $option->{$type == 'product' ? 'nid' : 'pcid'} = $id;
  993.   $result = drupal_write_record($sql['opt_table'], $option, $key);
  994.  
  995.   return $result;
  996. }
  997.  
  998. /**
  999.  * Deletes a product/class attribute option.
  1000.  *
  1001.  * @param $oid
  1002.  *   The base attribute's option ID.
  1003.  * @param $type
  1004.  *   Is this a product or a class?
  1005.  * @param $id
  1006.  *   The product/class ID.
  1007.  *
  1008.  * @return
  1009.  *   The Drupal SAVED_DELETED flag.
  1010.  */
  1011. function uc_attribute_subject_option_delete($oid, $type, $id = NULL, $adjustments = TRUE) {
  1012.   $sql = uc_attribute_type_info($type);
  1013.  
  1014.   // Delete the option.
  1015.   $query = db_delete($sql['opt_table'])
  1016.     ->condition('oid', $oid);
  1017.  
  1018.   // Base conditions, and an ID check if necessary.
  1019.   if ($id) {
  1020.     $query->condition($sql['id'], $id);
  1021.   }
  1022.  
  1023.   $query->execute();
  1024.  
  1025.   // If this is a product, clean up the associated adjustments.
  1026.   if ($adjustments && $type == 'product') {
  1027.     uc_attribute_adjustments_delete(array(
  1028.       'aid' => uc_attribute_option_load($oid)->aid,
  1029.       'oid' => $oid,
  1030.       'nid' => $id,
  1031.     ));
  1032.   }
  1033.  
  1034.   return SAVED_DELETED;
  1035. }
  1036.  
  1037. /**
  1038.  * Deletes an attribute adjustment.
  1039.  *
  1040.  * @param $fields
  1041.  *   Fields used to build a condition to delete adjustments against. Fields
  1042.  *   currently handled are 'aid', 'oid', and 'nid'.
  1043.  *
  1044.  * @return
  1045.  *   The Drupal SAVED_DELETED flag.
  1046.  */
  1047. function uc_attribute_adjustments_delete($fields) {
  1048.   // Build the serialized string to match against adjustments.
  1049.   $match = '';
  1050.   if (!empty($fields['aid'])) {
  1051.     $match .= serialize((integer) $fields['aid']);
  1052.   }
  1053.   if (!empty($fields['oid'])) {
  1054.     $match .= serialize((string) $fields['oid']);
  1055.   }
  1056.  
  1057.   // Assemble the conditions and args for the SQL.
  1058.   $query = db_delete('uc_product_adjustments');
  1059.  
  1060.   // If we have to match aid or oid...
  1061.   if ($match) {
  1062.     $query->condition('combination', '%' . db_like($match) . '%', 'LIKE');
  1063.   }
  1064.  
  1065.   // If we've got a node ID to match.
  1066.   if (!empty($fields['nid'])) {
  1067.     $query->condition('nid', $fields['nid']);
  1068.   }
  1069.  
  1070.   // Delete what's necessary,
  1071.   if ($query->conditions()) {
  1072.     $query->execute();
  1073.   }
  1074.  
  1075.   return SAVED_DELETED;
  1076. }
  1077.  
  1078. /**
  1079.  * Checks if a product/class attribute exists.
  1080.  *
  1081.  * @param $aid
  1082.  *   The base attribute ID.
  1083.  * @param $id
  1084.  *   The product/class attribute's ID.
  1085.  * @param $type
  1086.  *   Is this a product or a class?
  1087.  *
  1088.  * @return
  1089.  *   TRUE if the attribute exists.
  1090.  */
  1091. function uc_attribute_subject_exists($aid, $type, $id) {
  1092.   $sql = uc_attribute_type_info($type);
  1093.   $query = db_select($sql['attr_table'], 'a')
  1094.     ->fields('a', array('aid'))
  1095.     ->condition('aid', $aid)
  1096.     ->condition($sql['id'], $id);
  1097.   return FALSE !== $query->execute()->fetchField();
  1098. }
  1099.  
  1100. /**
  1101.  * Checks if a product/class attribute option exists.
  1102.  *
  1103.  * @param $oid
  1104.  *   The base attribute option ID.
  1105.  * @param $id
  1106.  *   The product/class attribute option's ID.
  1107.  * @param $type
  1108.  *   Is this a product or a class?
  1109.  *
  1110.  * @return
  1111.  *   TRUE if the attribute option exists.
  1112.  */
  1113. function uc_attribute_subject_option_exists($oid, $type, $id) {
  1114.   $sql = uc_attribute_type_info($type);
  1115.   $query = db_select($sql['opt_table'], 'o')
  1116.     ->fields('o', array('oid'))
  1117.     ->condition('oid', $oid)
  1118.     ->condition($sql['id'], $id);
  1119.   return FALSE !== $query->execute()->fetchField();
  1120. }
  1121.  
  1122. /**
  1123.  * Returns a list of names to abstract queries between products and classes.
  1124.  *
  1125.  * @param $type
  1126.  *   Is this a product or a class?
  1127.  *
  1128.  * @return
  1129.  *   Array of information helpful for creating SQL queries dealing
  1130.  *   with attributes.
  1131.  */
  1132. function uc_attribute_type_info($type) {
  1133.   switch ($type) {
  1134.     case 'product':
  1135.       return array(
  1136.         'attr_table' => 'uc_product_attributes',
  1137.         'opt_table' => 'uc_product_options',
  1138.         'id' => 'nid',
  1139.       );
  1140.     break;
  1141.  
  1142.     case 'class':
  1143.       return array(
  1144.         'attr_table' => 'uc_class_attributes',
  1145.         'opt_table' => 'uc_class_attribute_options',
  1146.         'id' => 'pcid',
  1147.       );
  1148.     break;
  1149.   }
  1150. }
  1151.  
  1152. /**
  1153.  * Loads all attributes associated with a product node.
  1154.  */
  1155. function uc_product_get_attributes($nid) {
  1156.   $attributes = array();
  1157.  
  1158.   $result = db_query("SELECT upa.aid FROM {uc_product_attributes} AS upa LEFT JOIN {uc_attributes} AS ua ON upa.aid = ua.aid WHERE upa.nid = :nid ORDER BY upa.ordering, ua.name", array(':nid' => $nid));
  1159.   foreach ($result as $attribute) {
  1160.     $attributes[$attribute->aid] = uc_attribute_load($attribute->aid, $nid, 'product');
  1161.   }
  1162.  
  1163.   return $attributes;
  1164. }
  1165.  
  1166. /**
  1167.  * Loads all attributes associated with a product class.
  1168.  */
  1169. function uc_class_get_attributes($pcid) {
  1170.   $attributes = array();
  1171.  
  1172.   $result = db_query("SELECT uca.aid FROM {uc_class_attributes} AS uca LEFT JOIN {uc_attributes} AS ua ON uca.aid = ua.aid WHERE uca.pcid = :type ORDER BY uca.ordering, ua.name", array(':type' => $pcid));
  1173.   foreach ($result as $attribute) {
  1174.     $attributes[$attribute->aid] = uc_attribute_load($attribute->aid, $pcid, 'class');
  1175.   }
  1176.  
  1177.   return $attributes;
  1178. }
  1179.  
  1180. /**
  1181.  * Gets the options chosen for a product that is in the cart.
  1182.  *
  1183.  * @param $item
  1184.  *   An element of the array returned by uc_cart_get_contents.
  1185.  *
  1186.  * @return
  1187.  *   Array of options chosen by a customer, indexed by attribute ids. Each
  1188.  *   element stores the attribute name and the option object chosen.
  1189.  */
  1190. function _uc_cart_product_get_options($item) {
  1191.   $options = array();
  1192.   $data = $item->data;
  1193.   $node = node_load($item->nid);
  1194.  
  1195.   $index = 0;
  1196.   if (!empty($data['attributes']) && is_array($data['attributes'])) {
  1197.     foreach ($data['attributes'] as $aid => $selected) {
  1198.       if (isset($node->attributes[$aid])) {
  1199.         $attribute = $node->attributes[$aid];
  1200.         $name = _uc_attribute_get_name($attribute);
  1201.         // Only discrete options can affect the price of an item.
  1202.         if ($attribute->display && count($attribute->options)) {
  1203.           // There may be many selected options, or just one.
  1204.           foreach ((array)$selected as $oid) {
  1205.             if ($oid > 0) {
  1206.               $options[$index] = (array)$attribute->options[$oid];
  1207.               $options[$index]['attribute'] = $name;
  1208.               $index++;
  1209.             }
  1210.           }
  1211.         }
  1212.         else {
  1213.           // Handle textfield attributes.
  1214.           $options[$index] = array(
  1215.             'attribute' => $name,
  1216.             'aid' => $aid,
  1217.             'oid' => 0,
  1218.             'name' => $selected,
  1219.             'cost' => 0,
  1220.             'price' => 0,
  1221.             'weight' => 0,
  1222.           );
  1223.         }
  1224.         $index++;
  1225.       }
  1226.     }
  1227.   }
  1228.   else {
  1229.     $options = array();
  1230.   }
  1231.   return $options;
  1232. }
  1233.  
  1234. /**
  1235. * Ajax callback for attribute selection form elements.
  1236. */
  1237. function uc_attribute_option_ajax($form, $form_state) {
  1238.     $parents = $form_state['triggering_element']['#array_parents'];
  1239.     $wrapper = '#' . $form_state['triggering_element']['#ajax']['wrapper'];
  1240.     while ($key = array_pop($parents)) {
  1241.         if ($key == 'attributes') {
  1242.             array_push($parents, $key);
  1243.             $element = drupal_array_get_nested_value($form, $parents);
  1244.             $commands[] = ajax_command_replace($wrapper, drupal_render($element));
  1245.             break;
  1246.         }
  1247.     }
  1248.     if (strpos($form['#form_id'], 'add_to_cart_form') !== FALSE) {
  1249.     $commands = array_merge($commands, uc_product_view_ajax_commands($form_state, array('display_price', 'weight', 'cost')));
  1250.     }
  1251.     $commands[] = ajax_command_prepend($wrapper, theme('status_messages'));
  1252.     return array('#type' => 'ajax', '#commands' => $commands);
  1253. }
  1254.    
  1255. /**
  1256.   * Helper function for uc_attribute_form_alter().
  1257.   * @param $id
  1258.   *   The unique id to use to wrap these form elements.
  1259.   * @param &$product
  1260.   *   The product node for which the attribute form elements are to be attached.
  1261.   * @param $use_ajax
  1262.   *   TRUE to add ajax to the form.  Note that ajax may be added even if this is FALSE,
  1263.   *   if there are multiple attributes and one or more of them is set to display total price.
  1264.   *
  1265.   * @see theme_uc_attribute_add_to_cart()
  1266.   * @see uc_attribute_option_ajax()
  1267.   */
  1268.  
  1269. function _uc_attribute_alter_form($id, &$product, $use_ajax) {
  1270.  
  1271.   // If the product doesn't have attributes, return the form as it is.
  1272.   if (empty($product->attributes) || !is_array($product->attributes)) {
  1273.     return NULL;
  1274.   }
  1275.  
  1276.   $nid = $product->nid;
  1277.  
  1278.   $attributes = $product->attributes;
  1279.  
  1280.   $priced_attributes = uc_attribute_priced_attributes($nid);
  1281.  
  1282.   // If the form is being built for the first time, populate attributes with their default values.
  1283.   if (!isset($product->data['attributes'])) {
  1284.     $values = array();
  1285.     foreach($priced_attributes as $aid) {
  1286.       if (!$attributes[$aid]->required && ($attributes[$aid]->display == 1 || $attributes[$aid]->display == 2)) {
  1287.         $values[$aid] = $attributes[$aid]->default_option;
  1288.       }
  1289.     }
  1290.     if (!empty($values)) {
  1291.       $data = $product->data;
  1292.       $data['attributes'] = $values;
  1293.       if (isset($product->qty)) {
  1294.         // Preserve the quantity (for product-kit sub-products).
  1295.         $qty = $product->qty;
  1296.       }
  1297.       $product = uc_product_load_variant($product->nid, $data);
  1298.       if (isset($qty)) {
  1299.         $product->qty = $qty;
  1300.       }
  1301.     }
  1302.   }
  1303.  
  1304.   if (empty($product->data) || !is_array($product->data)) {
  1305.     $product->data = array();
  1306.   }
  1307.  
  1308.   // Initialize the form element.
  1309.   $form_attributes = array(
  1310.     '#theme' => 'uc_attribute_add_to_cart',
  1311.     '#id' => $id,
  1312.   );
  1313.  
  1314.   $price_format = variable_get('uc_attribute_option_price_format', 'adjustment');
  1315.  
  1316.   // Loop through each product attribute and generate its form element.
  1317.   foreach ($attributes as $attribute) {
  1318.     // Build the attribute's options array.
  1319.     $options = array();
  1320.     foreach ($attribute->options as $option) {
  1321.       $display_price = '';
  1322.       if (in_array($attribute->aid, $priced_attributes)) {
  1323.         $data = array('display_only' => TRUE) + $product->data;
  1324.         if (empty($data['attributes'])) {
  1325.           $data['attributes'] = array();
  1326.         }
  1327.         switch ($price_format) {
  1328.            case 'total':
  1329.             // Only display total price for non-checkbox options.
  1330.             // !TODO Fix attribute option total price display for product kits.
  1331.             if ($attribute->display != 3 && !isset($product->data['kit_id'])) {
  1332.               $use_ajax = $use_ajax || (count($priced_attributes) > 1);
  1333.               $data['attributes'] = array($attribute->aid => $option->oid) + $data['attributes'];
  1334.               $variant = node_view(uc_product_load_variant($product->nid, $data), 'teaser');
  1335.               $display_price = uc_currency_format($variant['display_price']['#value']);
  1336.               break;
  1337.             }
  1338.           case 'adjustment':
  1339.             if ($attribute->display == 3 || !$use_ajax) {
  1340.               // For checkboxes, or if the node totals are not being updated,
  1341.               // we compare this attribute against base price.
  1342.               if (empty($base)) { // only build the base once.
  1343.                 unset($data['attributes']);
  1344.                 $base = node_view(uc_product_load_variant($product->nid, $data), 'teaser');
  1345.               }
  1346.               $data['attributes'] = array($attribute->aid => $option->oid);
  1347.               $variant = node_view(uc_product_load_variant($product->nid, $data), 'teaser');
  1348.               $adjustment = $variant['display_price']['#value'] - $base['display_price']['#value'];
  1349.             }
  1350.             else {
  1351.               // Otherwise we compare against current total price.
  1352.               if (empty($selected)) {
  1353.                 $selected = node_view(uc_product_load_variant($product->nid, $data), 'teaser');
  1354.               }
  1355.               $data['attributes'] = array($attribute->aid => $option->oid) + $data['attributes'];
  1356.               $variant = node_view(uc_product_load_variant($product->nid, $data), 'teaser');
  1357.               $adjustment = $variant['display_price']['#value'] - $selected['display_price']['#value'];
  1358.             }
  1359.             if ($adjustment != 0) {
  1360.               $display_price = $adjustment > 0 ? '+' : '-';
  1361.               $display_price .= uc_currency_format(abs($adjustment));
  1362.             }
  1363.             break;
  1364.         }
  1365.       }
  1366.  
  1367.       // Select options are check_plain()ed, but radio button labels are not.
  1368.       $options[$option->oid] = theme('uc_attribute_option', array(
  1369.         'option' => $attribute->display == 2 ? check_plain($option->name) : $option->name,
  1370.         'price' => $display_price,
  1371.       ));
  1372.     }
  1373.  
  1374.     if (count($attribute->options) && $attribute->display > 0) {
  1375.       if ($attribute->required) {
  1376.         if ($attribute->display == 1) {
  1377.           $options = array('' => t('Please select')) + $options;
  1378.         }
  1379.         $attribute->default_option = '';
  1380.       }
  1381.       $attr_type = '';
  1382.       switch ($attribute->display) {
  1383.         case 1:
  1384.           $attr_type = 'select';
  1385.           break;
  1386.         case 2:
  1387.           $attr_type = 'radios';
  1388.           break;
  1389.         case 3:
  1390.           $attr_type = 'checkboxes';
  1391.           $attribute->default_option = array();
  1392.           break;
  1393.       }
  1394.       $form_attributes[$attribute->aid] = array(
  1395.         '#type' => $attr_type,
  1396.         '#default_value' => $attribute->default_option,
  1397.         '#options' => $options,
  1398.       );
  1399.             if ($use_ajax) {
  1400.         $form_attributes[$attribute->aid]['#ajax'] = array(
  1401.           'callback' => 'uc_attribute_option_ajax',
  1402.           'wrapper' => $id,
  1403.         );
  1404.       }
  1405.     }
  1406.     elseif ($attribute->display > 0) {
  1407.       $form_attributes[$attribute->aid] = array(
  1408.         '#type' => 'textfield',
  1409.         '#default_value' => '',
  1410.       );
  1411.       if (!$attribute->required && isset($attribute->options[$attribute->default_option])) {
  1412.         $form_attributes[$attribute->aid]['#default_value'] = $attribute->options[$attribute->default_option]->name;
  1413.       }
  1414.     }
  1415.     else {
  1416.       $form_attributes[$attribute->aid] = array(
  1417.         '#type' => 'textfield',
  1418.         '#default_value' => '',
  1419.       );
  1420.     }
  1421.  
  1422.     $name = _uc_attribute_get_name($attribute, FALSE);
  1423.     if (!is_null($name)) {
  1424.       $form_attributes[$attribute->aid]['#title'] = check_plain($name);
  1425.     }
  1426.  
  1427.     $form_attributes[$attribute->aid]['#description'] = filter_xss($attribute->description);
  1428.     $form_attributes[$attribute->aid]['#required'] = $attribute->required;
  1429.   }
  1430.  
  1431.   return $form_attributes;
  1432. }
  1433.  
  1434. /**
  1435.  * Returns an array of display types used as options when creating attributes.
  1436.  */
  1437. function _uc_attribute_display_types() {
  1438.   return array(
  1439.     0 => t('Text field'),
  1440.     1 => t('Select box'),
  1441.     2 => t('Radio buttons'),
  1442.     3 => t('Checkboxes'),
  1443.   );
  1444. }
  1445.  
  1446. /**
  1447.  * Gets the price affecting attributes for a product.
  1448.  *
  1449.  * @param $nid
  1450.  *   The nid of a product.
  1451.  *
  1452.  * @return
  1453.  *   Array of attribute ids that have price affecting options.
  1454.  */
  1455. function uc_attribute_priced_attributes($nid) {
  1456.   $aids = db_query("SELECT DISTINCT (pa.aid) FROM {uc_product_attributes} AS pa INNER JOIN {uc_attribute_options} AS ao ON ao.aid = pa.aid INNER JOIN {uc_product_options} AS po ON (po.oid = ao.oid AND po.nid = pa.nid) WHERE pa.nid = :nid AND po.price <> :price AND pa.display <> :display", array(':nid' => $nid, ':price' => 0, ':display' => 0))->fetchCol();
  1457.  
  1458.   return $aids;
  1459. }
  1460.  
  1461. /**
  1462.  * Returns the attribute name to display.
  1463.  *
  1464.  * An attribute with a label set returns that label except when set to
  1465.  * '<none>' . In this case, a NULL is returned. The $title argument forces the
  1466.  * function to return the name property instead of label when label is set to
  1467.  * '<none>'.
  1468.  *
  1469.  * The NULL return value is typically used by forms so they know to hide the
  1470.  * #title property of the element.
  1471.  *
  1472.  * @param $attribute
  1473.  *   Attribute object.
  1474.  * @param $title
  1475.  *   TRUE indicates the function is to return the attribute name when its label
  1476.  *   is set to '<none>'.
  1477.  *
  1478.  * @return
  1479.  *   When the attribute label is set and not '<none>', it is returned.
  1480.  *   Otherwise, the attribute name is returned when $title is TRUE and NULL is
  1481.  *   returned when $title is FALSE.
  1482.  */
  1483. function _uc_attribute_get_name($attribute, $title = TRUE) {
  1484.   if (!$title && $attribute->label == '<none>') {
  1485.     return NULL;
  1486.   }
  1487.   else {
  1488.     return (empty($attribute->label) || ($attribute->label == '<none>' && $title) ? $attribute->name : $attribute->label);
  1489.   }
  1490. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement