You are here

uc_wishlist.module in UC Wish List 7

Same filename and directory in other branches
  1. 8 uc_wishlist.module
  2. 6 uc_wishlist.module

Allows users to create public shopping/wish lists.

Original development by Joe Turgeon [http://arithmetric.com] sponsored by Sundays Energy [http://www.sundaysenergy.com].

D6 migration and support by Commerce Guys [http://www.commerceguys.com].

D7 port by Jerry Hudgins [http://www.laureldigital.com]

File

uc_wishlist.module
View source
<?php

/**
 * @file
 * Allows users to create public shopping/wish lists.
 *
 * Original development by Joe Turgeon [http://arithmetric.com] sponsored by
 *   Sundays Energy [http://www.sundaysenergy.com].
 *
 * D6 migration and support by Commerce Guys [http://www.commerceguys.com].
 *
 * D7 port by Jerry Hudgins [http://www.laureldigital.com]
 */

/*******************************************************************************
 * Hook Functions (Drupal)
 ******************************************************************************/

/**
 * Implements hook_help().
 */
function uc_wishlist_help($path, $arg) {
  switch ($path) {

    // Main module help for the uc_wishlist module
    case 'admin/help#uc_wishlist':
      $output = '<p>' . '<strong>ABOUT</strong>' . '</p>';
      $output .= '<p>' . 'uc_wishlist is a module that adds wish list/gift registry functionality to Ubercart. It allows your customers to create and manage simple wish lists of products in your Ubercart store. Other customers can search for a particular wish list and purchase items from the list on behalf of the wish list creator. ' . '</p>';
      $output .= '<p>' . '<strong>FEATURES</strong>' . '</p>';
      $output .= '<p>' . 'This module enables users to create a gift list for use as a personal shopping list or a public gift registry. An "Add to wish list" button is added wherever there is an "Add to cart" button.' . '</p>';
      return $output;
    case 'admin/store/customers/wishlist':
      return '<p>' . 'This page displays users and their wishlists' . '</p>';
  }
}

/**
 * Implements hook_menu().
 */
function uc_wishlist_menu() {
  $items = array();
  $items['admin/store/customers/wishlist'] = array(
    'title' => 'Wish lists',
    'description' => 'Manage user wish lists.',
    'page callback' => 'uc_wishlist_admin',
    'access arguments' => array(
      'administer wish lists',
    ),
    'file' => 'uc_wishlist.admin.inc',
  );
  $items['admin/store/customers/wishlist/%uc_wishlist/delete'] = array(
    'title' => 'Delete a wish list',
    'description' => 'Confirm the deletion of a wish list.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'uc_wishlist_admin_delete_form',
      4,
    ),
    'access arguments' => array(
      'administer wish lists',
    ),
    'file' => 'uc_wishlist.admin.inc',
  );
  $items['admin/store/settings/wishlist'] = array(
    'title' => 'Wish list settings',
    'description' => 'Configure the wish list settings.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'uc_wishlist_admin_settings_form',
    ),
    'access arguments' => array(
      'administer wish lists',
    ),
    'file' => 'uc_wishlist.admin.inc',
  );
  $items['wishlist'] = array(
    'title' => 'Wish list',
    'description' => 'View or modify the contents of your wish list.',
    'page callback' => 'uc_wishlist_display',
    'access arguments' => array(
      'create wish lists',
    ),
    'file' => 'uc_wishlist.pages.inc',
  );
  $items['wishlist/search'] = array(
    'title' => 'Find a wish list',
    'description' => 'Search for a wish list.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'uc_wishlist_search_form',
    ),
    'access arguments' => array(
      'access wish lists',
    ),
    'file' => 'uc_wishlist.pages.inc',
  );
  $items['wishlist/search/%'] = array(
    'title' => 'Find a wish list',
    'description' => 'Search for a wish list.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'uc_wishlist_search_form',
      2,
    ),
    'access arguments' => array(
      'access wish lists',
    ),
    'file' => 'uc_wishlist.pages.inc',
  );

  // TODO: Convert this to use the autoloaded %uc_wishlist.
  $items['wishlist/%'] = array(
    'title' => 'Wish list',
    'description' => 'View or modify the contents of your wish list.',
    'page callback' => 'uc_wishlist_display',
    'page arguments' => array(
      1,
    ),
    'access arguments' => array(
      'access wish lists',
    ),
    'file' => 'uc_wishlist.pages.inc',
  );
  $items['user/%user/wishlist'] = array(
    'title' => 'Wish list',
    'description' => 'View or modify the contents of your wish list.',
    'page callback' => 'uc_wishlist_user_display',
    'page arguments' => array(
      1,
      'user',
    ),
    'access arguments' => array(
      'create wish lists',
    ),
    'file' => 'uc_wishlist.pages.inc',
    'type' => MENU_LOCAL_TASK,
  );
  $items['user/%user/wishlist-email'] = array(
    'title' => 'Wishlist email',
    'description' => 'Email wishlist to other user.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'uc_wishlist_email_form',
      1,
    ),
    'access arguments' => array(
      'email wishlist',
    ),
    'file' => 'uc_wishlist.pages.inc',
    'type' => MENU_LOCAL_TASK,
  );
  return $items;
}

/**
 * Implements hook_permission().
 */
function uc_wishlist_permission() {
  return array(
    'administer wish lists' => array(
      'title' => t('Administer wish lists'),
      'description' => t('Allows editing or deletion of any wish list.'),
    ),
    'create wish lists' => array(
      'title' => t('Create wish lists'),
      'description' => t('Allow creation and editing of own wish list.'),
    ),
    'access wish lists' => array(
      'title' => t('Access wish lists'),
      'description' => t('Allow viewing of any wish list.'),
    ),
    'email wishlist' => array(
      'title' => t('Email Own wish list'),
      'description' => t('Allow Email Own wish list'),
    ),
  );
}

/**
 * Implements hook_cron().
 */
function uc_wishlist_cron() {

  // TODO: Add clean up of anonymous wish lists.
}

/**
 * Implements hook_theme().
 */
function uc_wishlist_theme() {
  return array(
    'uc_wishlist_block_title' => array(
      'variables' => array(
        'wishlist_image' => NULL,
        'uc_wishlist_path' => FALSE,
        'arrow_up_image' => FALSE,
      ),
    ),
    'uc_wishlist_block_content' => array(
      'variables' => array(),
    ),
    'uc_wishlist_view_form' => array(
      'render element' => 'form',
    ),
    'uc_wishlist_user_display' => array(
      'variables' => array(
        'settings_form' => array(),
        'expired' => FALSE,
        'expiration_date' => '',
        'message' => '',
        'wishlist' => '',
        'email_link' => '',
      ),
      'template' => 'uc_wishlist_user_display',
    ),
  );
}

/**
 * Implements hook_search_access().
 */
function uc_wishlist_search_access() {
  return user_access('access wish lists');
}

/**
 * Implements hook_search_info().
 */
function uc_wishlist_search_info() {
  return array(
    'title' => t('Wish lists'),
    'path' => 'wishlist',
  );
}

/**
 * Implements hook_search_execute().
 *
 * Provides wishlist/search page to list and search for users with wish lists.
 */
function uc_wishlist_search_execute($keys = NULL, $conditions = NULL) {
  global $user;
  $links = array();

  // Check for user, wish list title, or address matches.
  $query = db_select('uc_wishlists', 'w');
  $query
    ->join('users', 'u', 'w.uid = u.uid');
  $query
    ->fields('w', array(
    'wid',
    'title',
  ));
  $query
    ->condition(db_or()
    ->condition('u.name', '%' . $keys . '%', 'LIKE')
    ->condition('w.title', '%' . $keys . '%', 'LIKE')
    ->condition('w.address', '%' . $keys . '%', 'LIKE'));
  $result = $query
    ->orderBy('w.title')
    ->execute();
  foreach ($result as $wishlist) {
    $results[] = array(
      'link' => url('wishlist/' . $wishlist->wid),
      'type' => t('Wish list'),
      'title' => filter_xss($wishlist->title),
    );
  }
  return $results;
}

/**
 * Implements hook_block_info().
 */
function uc_wishlist_block_info() {
  $blocks['search']['info'] = t('Find a wish list');
  return $blocks;
}

/**
 * Implements hook_block_view().
 */
function uc_wishlist_block_view($delta) {
  $block = array();
  if (user_access('access wish lists')) {
    if ($delta == 'search') {
      $block['subject'] = t('Find a wish list');
      $block['content'] = drupal_get_form('uc_wishlist_block_search_form');
    }
  }
  return $block;
}

/**
 * Implements hook_exit().
 *
 * Code from CacheExclude - http://drupal.org/project/cacheexclude
 */
function uc_wishlist_exit() {
  global $base_root;
  $pages = array(
    'wishlist',
    'wishlist/search',
  );
  $this_page = request_uri();
  foreach ($pages as $page) {
    if ($page && strstr($this_page, $page) !== FALSE) {
      cache_clear_all($base_root . $this_page, 'cache_page');
      return;
    }
  }
}

/**
 * Implements hook_user_login().
 */
function uc_wishlist_user_login(&$edit, $account) {
  $saved_id = empty($_SESSION['uc_wishlist_uid']) ? 0 : $_SESSION['uc_wishlist_uid'];
  $oldwid = db_query("SELECT wid FROM {uc_wishlists} WHERE uid = :uid", array(
    ':uid' => $saved_id,
  ))
    ->fetchField();
  $newwid = uc_wishlist_get_wid();
  if ($oldwid && $newwid) {
    $res = db_query("SELECT * FROM {uc_wishlist_products} WHERE wid = :wid", array(
      ':wid' => $oldwid,
    ));
    foreach ($res as $obj) {

      // NOTE: the delete must precede uc_wishlist_add_item because
      // it may update the old record but we expect it to insert a new record.
      db_delete('uc_wishlist_products')
        ->condition('wpid', $obj->wpid)
        ->execute();
      uc_wishlist_add_item($obj->nid, $obj->qty, unserialize($obj->data), $newwid);
    }
    db_delete('uc_wishlists')
      ->condition('wid', $oldwid)
      ->execute();
  }
  elseif ($oldwid && !$newwid) {
    db_update('uc_wishlists')
      ->fields(array(
      'uid' => $account->uid,
    ))
      ->condition('wid', $oldwid)
      ->execute();
  }
}

/**
 * Implements hook_user_view().
 */
function uc_wishlist_user_view($account, $view_mode) {
  $res = db_query("SELECT * FROM {uc_wishlists} WHERE uid = :uid", array(
    ':uid' => $account->uid,
  ));
  $items = array();
  foreach ($res as $obj) {
    $items['wishlist_' . $obj->wid] = array(
      'value' => l($obj->title, "wishlist/{$obj->wid}"),
    );
  }
  if (count($items) > 0) {
    return array(
      t('Wish lists') => $items,
    );
  }
}

/**
 * Implements hook_user_cancel().
 */
function uc_wishlist_user_cancel($edit, $account, $method) {

  // Find and delete any wish lists associated with the user being deleted.
  $result = db_query("SELECT wid FROM {uc_wishlists} WHERE uid = :uid", array(
    ':uid' => $account->uid,
  ));
  foreach ($result as $row) {
    uc_wishlist_delete($row->wid);
  }
}

/**
 * Implements hook_user_delete().
 */
function uc_wishlist_user_delete($account) {
  db_query("delete from {uc_wishlist_products} where wid in (select wid from {uc_wishlists} where uid = :uid)", array(
    ':uid' => $account->uid,
  ));
  db_delete("uc_wishlists")
    ->condition('uid', $account->uid)
    ->execute();
}

/**
 * Implements hook_form_alter().
 *
 * Alter uc_product_add_to_cart_form instances to include 'add to wish list'
 * button. Form submission is routed through uc_wishlist_add_to_wishlist
 * to differentiate between 'add to cart' and 'add to wish list'. If this
 * module is added to Ubercart core, then this can be simplified.
 *
 * Alter uc_cart_checkout_form to include by default the delivery address
 * of a wish list's owner, if items come from a single wish list.
 */
function uc_wishlist_form_alter(&$form, &$form_state, $form_id) {
  if (strpos($form_id, 'uc_product_add_to_cart_form_') === 0 || strpos($form_id, 'uc_product_kit_add_to_cart_form_') === 0) {

    // Allow users to add product to wishlist which has 'create wishlist' access.
    if (!user_access('create wish lists')) {
      return;
    }

    // Add products to wishlist, that are available in stock.
    $product = $form_state['build_info']['args'][0];
    if (!variable_get('uc_wishlist_out_of_stock', FALSE)) {

      // Check for the stock of the product.
      if (module_exists('uc_stock')) {
        $stock_level = uc_stock_level($product->model);
        if ($stock_level !== FALSE && $stock_level <= 0) {
          return;
        }
      }
    }

    // Add the wish list button to the add to cart form.
    $form['actions']['wishlist'] = array(
      '#type' => 'submit',
      '#attributes' => array(
        'class' => array(
          'node-add-to-wishlist',
        ),
      ),
      '#value' => t('Add to wish list'),
      '#submit' => array(
        'uc_wishlist_add_to_wishlist_submit',
      ),
      '#weight' => 1,
    );
  }

  // Checking if the product is added from wishlist in checkout page.
  if ($form_id == 'uc_cart_checkout_form') {
    if (isset($form['panes']['cart']['cart_review_table']['#items']) && !empty($form['panes']['cart']['cart_review_table']['#items'])) {
      $items = $form['panes']['cart']['cart_review_table']['#items'];
      $wids = array();
      foreach ($items as $item) {
        if (!empty($item->data['wid'])) {
          $wids[] = $item->data['wid'];
        }
      }
      $wids = array_unique($wids);
      if (count($wids) > 1) {
        drupal_set_message(t('This order contains items from multiple wish lists. It is not possible to automatically address this order for its recipient.'));
      }
      elseif (count($wids) == 1) {
        $wishlist = uc_wishlist_load($wids[0]);
        if (variable_get('uc_wishlist_save_address', TRUE) && !empty($wishlist->address->firstname) && !empty($wishlist->address->lastname) && !empty($wishlist->address->addr1) && !empty($wishlist->address->postcode) && is_object($form['panes']['delivery']['address']['#default_value']) && empty($form['panes']['delivery']['address']['#default_value']->delivery_first_name)) {
          $order = uc_order_load($_SESSION['cart_order']);
          if ($order) {
            $defaults = $order;
            $defaults->delivery_first_name = $wishlist->address->firstname;
            $defaults->delivery_last_name = $wishlist->address->lastname;
            $defaults->delivery_company = $wishlist->address->company;
            $defaults->delivery_street1 = $wishlist->address->addr1;
            $defaults->delivery_street2 = $wishlist->address->addr2;
            $defaults->delivery_city = $wishlist->address->city;
            $defaults->delivery_country = $wishlist->address->country;
            $defaults->delivery_zone = $wishlist->address->zone;
            $defaults->delivery_postal_code = $wishlist->address->postcode;
            $defaults->delivery_phone = $wishlist->address->phone;
            $form['panes']['delivery']['address']['#default_value'] = $defaults;
            drupal_set_message(t('This order contains items from a wish list. The delivery address has been automatically set to the preferred address from the wish list. You may change this address.'));
          }
        }
      }
    }
  }
}

/**
 * Submit handler of the uc_wishlist_add_to_wishlist.
 *
 * See comment for uc_wishlist_form_alter: This function handles submission
 * of uc_product_add_to_cart_form and differentiates between 'add to cart'
 * and 'add to wish list' functions.
 */
function uc_wishlist_add_to_wishlist_submit($form, &$form_state) {

  // Add the item to the user's wish list.
  uc_wishlist_add_item($form_state['values']['nid'], $form_state['values']['qty'], module_invoke_all('uc_add_to_cart_data', $form_state['values']));
}

/*******************************************************************************
 * Hook Functions (Ubercart)
 ******************************************************************************/

/**
 * Implements hook_uc_order().
 *
 * When the status of an order is changed to pending, then the order is
 * scanned for items from wish lists (that contain wid and wpid data fields).
 * If items are found, then their records in uc_wishlist_products are
 * updated with the additional purchases.
 */
function uc_wishlist_uc_order($op, $order, $arg2) {
  if ($op == 'update') {
    if (uc_order_status_data($order->order_status, 'state') != 'in_checkout' || uc_order_status_data($arg2, 'state') == 'in_checkout' || uc_order_status_data($arg2, 'state') == 'canceled') {
      return;
    }
    $o = $order;
    foreach ($o->products as $key => $item) {
      if (isset($item->data['wid']) && isset($item->data['wpid']) && !isset($item->data['wset'])) {
        $wid = $item->data['wid'];
        $wpid = $item->data['wpid'];
        $w = uc_wishlist_load($wid);
        $witem = uc_wishlist_get_product($wpid);
        $purchase = array(
          'order_id' => $item->order_id,
          'order_product_id' => $item->order_product_id,
          'uid' => $o->uid,
          'date' => REQUEST_TIME,
        );
        for ($i = 0; $i < $item->qty; $i++) {
          $witem->purchase[] = $purchase;
        }
        uc_wishlist_update_purchase($witem);
      }
    }
  }
}

/*******************************************************************************
 * Callback Functions, Forms, and Tables
 ******************************************************************************/

/**
 * Update information about a specific item in current wish list.
 */
function uc_product_update_wishlist_item($nid, $data = array(), $qty, $wid = NULL, $wpid = NULL) {
  if (!$nid) {
    return NULL;
  }
  $wid = $wid ? $wid : uc_wishlist_get_wid();
  if ($qty < 1) {
    $wpid = $wpid ? $wpid : $data['wpid'];
    uc_wishlist_remove_item($wpid);
  }
  else {
    db_update('uc_wishlist_products')
      ->fields(array(
      'qty' => $qty,
      'changed' => REQUEST_TIME,
    ))
      ->condition('wpid', $wpid)
      ->execute();
  }
  if (strpos(request_uri(), 'wishlist', 1) !== FALSE) {
    drupal_set_message(t('Your item(s) have been updated.'));
  }
}

/*******************************************************************************
 * Module and Helper Functions
 ******************************************************************************/

/**
 * Get either an authenticated user's uid or an anonymous user's unique ID.
 */
function uc_wishlist_get_uid() {
  global $user;

  // Get either an authenticated user's uid or an anonymous user's unique ID.
  if ($user->uid) {
    $uid = $user->uid;
  }
  else {
    if (!isset($_SESSION['uc_wishlist_uid']) || empty($_SESSION['uc_wishlist_uid'])) {
      $_SESSION['uc_wishlist_uid'] = md5(uniqid(rand(), TRUE));
    }
    $uid = $_SESSION['uc_wishlist_uid'];
  }
  return $uid;
}

/**
 * Return the wish list ID of the specified user (defaults to current user).
 */
function uc_wishlist_get_wid($uid = NULL) {

  // Find the wish list matching the authenticated or anonymous user ID.
  // TODO: Handle multiple wishlists?
  if (empty($uid)) {
    $uid = uc_wishlist_get_uid();
  }
  return db_query("SELECT wid FROM {uc_wishlists} WHERE uid = :uid", array(
    ':uid' => $uid,
  ))
    ->fetchField();
}

/**
 * Load a wish list object from the database.
 *
 * @param numeric $wid
 *   The wish list ID to load; if NULL, looks for the current user's wish list.
 *
 * @return object
 *   A wish list object.
 */
function uc_wishlist_load($wid) {
  if (empty($wid)) {
    $wid = uc_wishlist_get_wid();
  }
  if (!$wid || !is_numeric($wid)) {
    return FALSE;
  }
  $result = db_query("SELECT * FROM {uc_wishlists} WHERE wid = :wid", array(
    ':wid' => $wid,
  ));
  if ($wishlist = $result
    ->fetchObject()) {
    $wishlist->address = unserialize($wishlist->address);
    return $wishlist;
  }
}

/**
 * Get the items in a specified wish list.
 */
function uc_wishlist_get_contents($wid = NULL) {
  $wid = $wid ? $wid : uc_wishlist_get_wid();
  if (!$wid || !is_numeric($wid)) {
    return FALSE;
  }
  $items = array();
  $query = db_select('node', 'n');
  $query
    ->join('uc_wishlist_products', 'w', 'n.nid = w.nid');
  $query
    ->fields('w');
  $query
    ->addField('n', 'title');
  $query
    ->addField('n', 'vid');
  $query
    ->condition('w.wid', $wid);
  $query
    ->addTag('node_access');
  $res = $query
    ->execute();

  // Iterating through the array.
  foreach ($res as $item) {
    for ($i = 0; $i < count($items); $i++) {
      if ($items[$i]->nid == $item->nid && $items[$i]->data == $item->data) {
        $items[$i]->qty += $item->qty;
        continue 2;
      }
    }
    $product = node_load($item->nid);
    $item->model = $product->model;
    $item->cost = $product->cost;
    $item->price = $product->sell_price;
    $item->weight = $product->weight;
    $item->weight_units = $product->weight_units;
    $item->shippable = $product->shippable;
    $item->data = unserialize($item->data);
    $item->module = $item->data['module'];
    $item->purchase = unserialize($item->purchase);
    $item->options = array();

    // Add wishlist id data.
    $item->data['wid'] = $item->wid;
    $item->data['wpid'] = $item->wpid;
    $items[] = $item;
  }
  return $items;
}

/**
 * Returns a wish list cart product given its wpid.
 */
function uc_wishlist_get_product($wpid) {
  if (!$wpid) {
    return FALSE;
  }
  $item = FALSE;
  $query = db_select('node', 'n');
  $query
    ->join('uc_wishlist_products', 'w', 'n.nid = w.nid');
  $query
    ->fields('w');
  $query
    ->addField('n', 'title');
  $query
    ->addField('n', 'vid');
  $query
    ->condition('w.wpid', $wpid);
  $query
    ->addTag('node_access');
  $res = $query
    ->execute();
  foreach ($res as $item) {
    $product = node_load($item->nid);
    $item->model = $product->model;
    $item->cost = $product->cost;
    $item->price = $product->sell_price;
    $item->weight = $product->weight;
    $item->weight_units = $product->weight_units;
    $item->shippable = $product->shippable;
    $item->data = unserialize($item->data);
    $item->module = $item->data['module'];
    $item->purchase = unserialize($item->purchase);
    $item->options = array();

    // Add wishlist id data.
    $item->data['wid'] = $item->wid;
    $item->data['wpid'] = $item->wpid;

    // Invoke hook_uc_update_cart_item() in enabled modules.
    // An especially important hook is uc_attribute_cart_item which
    // updates the item given the attributes.
    foreach (module_implements('uc_update_cart_item') as $module) {
      $func = $module . '_uc_update_cart_item';
      $func($item->nid, $item->data, $item->qty);
    }
  }
  return $item;
}

/**
 * Used by uc_wishlist_order to update the data on the wish list item purchase.
 */
function uc_wishlist_update_purchase($witem) {
  if ($witem->wpid && is_array($witem->purchase)) {
    $rv = db_update('uc_wishlist_products')
      ->fields(array(
      'purchase' => serialize($witem->purchase),
    ))
      ->condition('wpid', $witem->wpid)
      ->execute();
  }
}

/**
 * Save wishlist for the current authenticated or anonymous user.
 */
function uc_wishlist_save_wishlist($wishlist = NULL) {
  if (is_object($wishlist) && $wishlist->wid) {
    $return = drupal_write_record('uc_wishlists', $wishlist, 'wid');
    return $return;
  }
  else {
    global $user;

    // Abort if user is not logged in and anonymous wish lists are not allowed.
    if (!$user->uid && !user_access('create wish lists')) {
      drupal_set_message(t('You must be logged in to create a wish list. Please <a href="!login_url">login</a> or <a href="!register_url">register</a>.', array(
        '!login_url' => url('user', array(
          'query' => drupal_get_destination(),
        )),
        '!register_url' => url('user/register', array(
          'query' => drupal_get_destination(),
        )),
      )), 'error');
      return FALSE;
    }
    $title = variable_get('uc_wishlist_default_title', "%user's wish list");
    if (strpos($title, '%user') !== FALSE) {
      $uname = !empty($user->name) ? $user->name : variable_get('anonymous', t('Anonymous'));
      $title = str_replace('%user', $uname, $title);
    }
    $wishlist = new stdClass();
    $wishlist->uid = uc_wishlist_get_uid();
    $wishlist->title = $title;
    $wishlist->expiration = REQUEST_TIME + variable_get('uc_wishlist_default_length', 2592000);
    $wishlist->private = variable_get('uc_wishlist_default_private', FALSE) ? variable_get('uc_wishlist_default_private', FALSE) : 0;
    $wishlist->description = '';
    $return = drupal_write_record('uc_wishlists', $wishlist);
  }
  return $return;
}

/**
 * Adds an item to a user's wish list.
 */
function uc_wishlist_add_item($nid, $qty = 1, $data = NULL, $wid = NULL, $msg = TRUE, $check_redirect = TRUE) {
  $wid = $wid ? $wid : uc_wishlist_get_wid();
  $created = FALSE;
  if (!$wid || $wid === NULL) {
    $wid = uc_wishlist_save_wishlist();
    if (!$wid) {
      drupal_set_message(t('Could not create wish list. Adding item failed.'), 'error');
      return FALSE;
    }
    $created = TRUE;
  }
  $node = node_load($nid);

  // Adding data variables.
  if (empty($data)) {
    $data = array(
      'module' => 'uc_product',
    );
  }
  elseif (!array_key_exists('module', $data)) {
    $data['module'] = 'uc_product';
  }

  // If Product Kit is enable, then add products into data array.
  if (module_exists('uc_product_kit') && $node->type == 'product_kit') {

    // Adding products of the product kit into data object.
    $products = $node->products;
    foreach ($products as $pid => $product) {
      $data['products'][$pid]['nid'] = $pid;
      $data['products'][$pid]['qty'] = $product->qty;

      // Creating attributes array.
      $attributes = array();

      // Getting attributes list of the product.
      $product_attributes = $product->attributes;

      // Iterating through the attributes list.
      foreach ($product_attributes as $aid => $product_attribute) {
        $attribute[$product_attribute->aid] = $product_attribute->default_option;
      }

      // Assigning attributes to data array.
      $data['products'][$pid]['attributes'] = $attributes;
    }
  }

  // If product kit module is install in the site, then we need to check if the
  // product is product kit or product.
  if (module_exists('uc_product_kit')) {
    $supported_node_types = array_merge(array_keys(uc_product_node_info()), array_keys(uc_product_kit_node_info()));
  }
  else {
    $supported_node_types = array_keys(uc_product_node_info());
  }

  // Checking if the node is product type or product kit type.
  if (!in_array($node->type, $supported_node_types)) {
    drupal_set_message(t('@title is not a product. Unable to add to wish list.', array(
      '@title' => $node->title,
    )), 'error');
    return;
  }
  $result = module_invoke_all('add_to_cart', $nid, $qty, $data);
  if (is_array($result) && !empty($result)) {
    foreach ($result as $row) {
      if ($row['success'] === FALSE) {
        if (isset($row['message']) && !empty($row['message'])) {
          $message = $row['message'];
        }
        else {
          $message = t('Sorry, that item is not available for purchase at this time.');
        }
        drupal_set_message(filter_xss($message), 'error');
        return;
      }
    }
  }
  $result = db_query("SELECT * FROM {uc_wishlist_products} WHERE wid = :wid AND nid = :nid AND data = :data", array(
    ':wid' => $wid,
    ':nid' => $nid,
    ':data' => serialize($data),
  ));
  $item = $result
    ->fetchObject();

  // If the item isn't in the cart yet, add it.
  if (is_null($item) || $item === FALSE) {
    $id = db_insert('uc_wishlist_products')
      ->fields(array(
      'wid' => $wid,
      'nid' => $nid,
      'qty' => $qty,
      'changed' => REQUEST_TIME,
      'data' => serialize($data),
      'purchase' => '',
    ))
      ->execute();
    if ($msg) {
      drupal_set_message(t('<b>@product-title</b> added to <a href="!url">your wish list</a>.', array(
        '@product-title' => filter_xss($node->title),
        '!url' => url('wishlist'),
      )));
    }
  }
  else {

    // Update the item instead.
    $qty += $item->qty;
    $wpid = $item->wpid;
    uc_product_update_wishlist_item($nid, $data, min($qty, 999999), $wid, $wpid);
    if ($msg) {
      drupal_set_message(filter_xss(t('Your <a href="!url">wish list</a> has been updated.', array(
        '!url' => url('wishlist'),
      ))));
    }
  }
  if ($check_redirect) {
    if (isset($_GET['destination'])) {
      drupal_goto();
    }
  }
  if ($created) {
    drupal_goto('wishlist');
  }
}

/**
 * Remove an item from the wish list.
 */
function uc_wishlist_remove_item($wpid) {
  db_delete('uc_wishlist_products')
    ->condition('wpid', $wpid)
    ->execute();
}

/**
 * Updates the quantity of all the items in a cart object.
 */
function uc_wishlist_update_item_object($wform) {
  if (is_object($wform)) {
    if ($wform->wid) {
      $wid = $wform->wid;
    }
    else {
      $wid = uc_wishlist_get_wid();
    }
    foreach ($wform->items as $item) {
      $data = unserialize($item['data']);
      $wpid = $data['wpid'];
      if ($item['remove']) {
        module_invoke($item['module'], 'update_wishlist_item', $item['nid'], $data, 0, $wid, $wpid);
      }
      else {
        module_invoke($item['module'], 'update_wishlist_item', $item['nid'], $data, $item['wantqty'], $wid, $wpid);
      }
    }
  }
}

/**
 * Adds wishlist items to the shopping cart.
 */
function uc_wishlist_add_items_to_cart($form_values) {
  if (is_object($form_values)) {
    if ($form_values->wid) {
      $wid = $form_values->wid;
    }
    else {
      $wid = uc_wishlist_get_wid();
    }
    foreach ($form_values->items as $item) {
      if ($item['qty'] > 0) {

        // TODO: add attribute information 'gift to user' that shows up on
        // receipts. see uc_wishlist_cart_item
        $data = unserialize($item['data']);
        uc_cart_add_item($item['nid'], $item['qty'], $data);
      }
    }
  }
}

/**
 * Deletes a wish list and all its products.
 */
function uc_wishlist_delete($wid) {
  db_delete('uc_wishlists')
    ->condition('wid', $wid)
    ->execute();
  db_delete('uc_wishlist_products')
    ->condition('wid', $wid)
    ->execute();
}

/**
 * Displays the wish list search block form.
 */
function uc_wishlist_block_search_form($form) {
  $form = array();
  $form['keywords'] = array(
    '#type' => 'textfield',
    '#title' => t('Search keywords'),
    '#description' => t('Enter the keywords to use to search wish list titles and addresses.'),
    '#size' => 16,
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Search'),
  );
  return $form;
}

/**
 * Submission handler for the wish list search block form.
 */
function uc_wishlist_block_search_form_submit($form, &$form_state) {
  if (empty($form_state['values']['keywords'])) {
    $form_state['redirect'] = 'wishlist/search';
  }
  else {
    $form_state['redirect'] = 'wishlist/search/' . drupal_encode_path($form_state['values']['keywords']);
  }
}

/**
 * Checking if order has wishlist product or not.
 */
function uc_wishlist_order_wishlist($order) {

  // If there is no product in order, return false.
  if (!is_array($order->products) || empty($order->products)) {
    return FALSE;
  }
  foreach ($order->products as $product) {
    $result = db_query("SELECT * FROM {uc_wishlist_products} WHERE nid = :nid AND data = :data", array(
      ':nid' => $product->nid,
      ':data' => serialize($product->data),
    ));
    $item = $result
      ->fetchObject();

    // If there is wishlist product, return true.
    if (!empty($item)) {
      return TRUE;
    }
  }
  return FALSE;
}

/**
 * Implements hook_mail().
 */
function uc_wishlist_mail($key, &$message, $params) {
  if (isset($params['subject'])) {
    $message['subject'] = $params['subject'];
  }
  if (isset($params['body'])) {
    $message['body'][] = $params['body'];
  }
  if (isset($params['headers']) && is_array($params['headers'])) {
    $message['headers'] += $params['headers'];
  }
}

/**
 * Implements hook_views_api().
 */
function uc_wishlist_views_api() {
  return array(
    'api' => 3,
  );
}

Functions

Namesort descending Description
uc_product_update_wishlist_item Update information about a specific item in current wish list.
uc_wishlist_add_item Adds an item to a user's wish list.
uc_wishlist_add_items_to_cart Adds wishlist items to the shopping cart.
uc_wishlist_add_to_wishlist_submit Submit handler of the uc_wishlist_add_to_wishlist.
uc_wishlist_block_info Implements hook_block_info().
uc_wishlist_block_search_form Displays the wish list search block form.
uc_wishlist_block_search_form_submit Submission handler for the wish list search block form.
uc_wishlist_block_view Implements hook_block_view().
uc_wishlist_cron Implements hook_cron().
uc_wishlist_delete Deletes a wish list and all its products.
uc_wishlist_exit Implements hook_exit().
uc_wishlist_form_alter Implements hook_form_alter().
uc_wishlist_get_contents Get the items in a specified wish list.
uc_wishlist_get_product Returns a wish list cart product given its wpid.
uc_wishlist_get_uid Get either an authenticated user's uid or an anonymous user's unique ID.
uc_wishlist_get_wid Return the wish list ID of the specified user (defaults to current user).
uc_wishlist_help Implements hook_help().
uc_wishlist_load Load a wish list object from the database.
uc_wishlist_mail Implements hook_mail().
uc_wishlist_menu Implements hook_menu().
uc_wishlist_order_wishlist Checking if order has wishlist product or not.
uc_wishlist_permission Implements hook_permission().
uc_wishlist_remove_item Remove an item from the wish list.
uc_wishlist_save_wishlist Save wishlist for the current authenticated or anonymous user.
uc_wishlist_search_access Implements hook_search_access().
uc_wishlist_search_execute Implements hook_search_execute().
uc_wishlist_search_info Implements hook_search_info().
uc_wishlist_theme Implements hook_theme().
uc_wishlist_uc_order Implements hook_uc_order().
uc_wishlist_update_item_object Updates the quantity of all the items in a cart object.
uc_wishlist_update_purchase Used by uc_wishlist_order to update the data on the wish list item purchase.
uc_wishlist_user_cancel Implements hook_user_cancel().
uc_wishlist_user_delete Implements hook_user_delete().
uc_wishlist_user_login Implements hook_user_login().
uc_wishlist_user_view Implements hook_user_view().
uc_wishlist_views_api Implements hook_views_api().