/[drupal]/contributions/modules/magento/magento_products/magento_products.module
ViewVC logotype

Diff of /contributions/modules/magento/magento_products/magento_products.module

Parent Directory Parent Directory | Revision Log Revision Log | View Revision Graph Revision Graph | View Patch Patch

revision 1.1 by mtopolov, Mon May 25 10:30:48 2009 UTC revision 1.2 by mtopolov, Mon Nov 16 10:38:48 2009 UTC
# Line 8  define (DATE_FORMAT, 'Y-m-d\TH:i:s'); Line 8  define (DATE_FORMAT, 'Y-m-d\TH:i:s');
8   * Implementation of hook_menu().   * Implementation of hook_menu().
9   */   */
10  function magento_products_menu() {  function magento_products_menu() {
11          $items['admin/settings/magento_products'] = array(    $items['admin/settings/magento_products'] = array(
12          'title' => t('Magento Products Settings'),          'title' => t('Magento Products Settings'),
13                  'page callback' => 'drupal_get_form',                  'page callback' => 'drupal_get_form',
14          'page arguments' => array('magento_products_settings'),          'page arguments' => array('magento_products_settings'),
15          'access arguments' => array('access administration pages'),          'access arguments' => array('access administration pages'),
16          'type' => MENU_NORMAL_ITEM,          'type' => MENU_NORMAL_ITEM,
17          );    );
18          return $items;    return $items;
19  }  }
20  /**  /**
21   * Implementation of hook_form_alter().   * Implementation of hook_form_alter().
22   */   */
23  function magento_products_form_alter(&$form, $form_state, $form_id) {  function magento_products_form_alter(&$form, $form_state, $form_id) {
24          if ($form_id == 'magento_api_synchro_settings') {    if ($form_id == 'magento_api_synchro_settings') {
25                  // Add button for Manual Synchronization to Settings page      // Add button for Manual Synchronization to Settings page
26                  $form['magento_synchronize']['synchronize_products'] = array(      $form['magento_synchronize']['synchronize_products'] = array(
27                          '#type' => 'submit',                          '#type' => 'submit',
28                          '#value' => 'Synchronize Products into Nodes',                          '#value' => 'Synchronize Products into Nodes',
29                          '#submit' => array('magento_products_test'),                          '#submit' => array('magento_products_test'),
30                  );      );
31                  return $form;      // Add button for Manual Synchronization to Settings page
32          }      $form['offer_valid']['check_offer'] = array(
33                            '#type' => 'submit',
34                            '#value' => 'Check Offer Valid Date',
35                            '#submit' => array('magento_products_offer_valid_check'),
36        );
37        return $form;
38      }
39  }  }
40  /**  /**
41   *   *
# Line 37  function magento_products_form_alter(&$f Line 43  function magento_products_form_alter(&$f
43   *   *
44   */   */
45  function magento_products_settings() {  function magento_products_settings() {
46          $form = array();    $form = array();
47          $path = drupal_get_path('module', 'magento_products');    $path = drupal_get_path('module', 'magento_products');
48          drupal_add_js($path . '/js/show_up.js');    drupal_add_js($path . '/js/show_up.js');
49    
50          $form['magento_products_cache_time'] = array(    $form['magento_products_cache_time'] = array(
51                  '#type' => 'radios',                  '#type' => 'radios',
52                  '#title' => t('Products info cache time'),                  '#title' => t('Products info cache time'),
53                  '#description' => t('Select how long additional info for products will be stored in cache'),                  '#description' => t('Select how long additional info for products will be stored in cache'),
54                  '#default_value' => variable_get('magento_products_cache_time', 'CACHE_PERMANENT'),                  '#default_value' => variable_get('magento_products_cache_time', 'CACHE_PERMANENT'),
55                  '#options' => array('CACHE_PERMANENT' => t('Permanent'), 'CACHE_TEMPORARY' => t('Temporary'), 'CUSTOM' => 'Custom Time'),                  '#options' => array('CACHE_PERMANENT' => t('Permanent'), 'CACHE_TEMPORARY' => t('Temporary'), 'CUSTOM' => 'Custom Time'),
56          );    );
57          $form['magento_products_cache_custom_time'] = array(    $form['magento_products_cache_custom_time'] = array(
58                  '#prefix' =>'<div id="cache_time" style="display:none">',                  '#prefix' =>'<div id="cache_time" style="display:none">',
59                  '#type' => 'textfield',                  '#type' => 'textfield',
60                  '#title' => t('Time in hours'),                  '#title' => t('Time in hours'),
61                  '#default_value' => variable_get('magento_products_cache_custom_time', 24),                  '#default_value' => variable_get('magento_products_cache_custom_time', 24),
62                  '#element_validate' => array('magento_products_cache_time_validate'),                  '#element_validate' => array('magento_products_cache_time_validate'),
63                  '#suffix' => '</div>',                  '#suffix' => '</div>',
64          );    );
65          return system_settings_form($form);  
66      return system_settings_form($form);
67  }  }
68  /**  /**
69   * Validate time that was entered on settings page.   * Validate time that was entered on settings page.
70   */   */
71  function magento_products_cache_time_validate($element, &$form_state) {  function magento_products_cache_time_validate($element, &$form_state) {
72          if (is_numeric($element['#value']) ) {    if (is_numeric($element['#value']) ) {
73                  if ($element['#value'] <= 0) {      if ($element['#value'] <= 0) {
74                          form_error($element, t('This field must be positive.'));        form_error($element, t('This field must be positive.'));
75                  }      }
76          }else form_error($element, t('This field must be numeric.'));    }else form_error($element, t('This field must be numeric.'));
77  }  }
78  /**  /**
79   * Implementation of hook_nodeapi().   * Implementation of hook_nodeapi().
80   */   */
81  function magento_products_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {  function magento_products_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
82          global $user;    global $user;
83          if ($node->type == 'product' && $op == 'view' && $a4 == TRUE) {    if ($node->type == 'product' && $op == 'view') {
84                  // Get information about actual product price      // Get information about actual product price
85                  $price = magento_products_get_actual_price($node, $user);      $price = magento_products_get_actual_price($node, $user);
86                  $actual_price = $node->field_actual_price[0]['value'];      $actual_price = $node->field_actual_price[0]['value'];
87                  if ($price != $actual_price) {      if ($price != $actual_price) {
88                          $node->field_actual_price[0]['value'] = $price;        $node->field_actual_price[0]['value'] = $price;
89                          node_save($node);        node_save($node);
90                  }      }
91                  // drupal_set_message(t('Price of this product') . ' = ' . $price);      // drupal_set_message(t('Price of this product') . ' = ' . $price);
92                  // actual price can get from $node->field_actual_price[0]['value'] within node template      // actual price can get from $node->field_actual_price[0]['value'] within node template
93                  $tier_price = magento_products_get_tier_price($node, $price);      $tier_price = magento_products_get_tier_price($node, $price);
94                  foreach ($tier_price as $qty => $cost) {      foreach ($tier_price as $qty => $cost) {
95                          //drupal_set_message('Buy ' . $qty . ' for ' . $cost . ' each');        //drupal_set_message('Buy ' . $qty . ' for ' . $cost . ' each');
96                          // tear price can get from $node->field_tier_price[0]['value'] within node template        // tear price can get from $node->field_tier_price[0]['value'] within node template
97                  }      }
98                  // Getting additional product info from Cache or Magento if not cached yet      // Getting additional product info from Cache or Magento if not cached yet
99                  $info = cache_get('product_info_' . $node->field_product_id[0]['value'],'cache');      magento_products_cache_full_info($node);
100                  // If there is no information in cache or it is expired - reorder it    }
101                  if ($info == 0 || time() > $info->expire) {  }
102                          $StoreView = magento_stores_get_default_store_view(magento_stores_get_default_store(magento_stores_get_default_website()));  
103                          $info = magento_api_catalog_product_full_info($node->field_product_id[0]['value'],$StoreView);  /**
104                          $time = variable_get('magento_products_cache_time', 'CACHE_PERMANENT');   * Getting additional product info from Cache or Magento if not cached yet
105                          if ($time == 'CUSTOM') {   */
106                                  $time = variable_get('magento_products_cache_custom_time', 24);  function magento_products_cache_full_info($node) {
107                                  cache_set('product_info_' . $node->field_product_id[0]['value'], $info,'cache',strtotime ("+". $time ." hour"));    //TODO SAVE into fields, not CACHE
108                          } else cache_set('product_info_' . $node->field_product_id[0]['value'], $info,'cache',$time);    $info = cache_get('product_info_' . $node->field_product_id[0]['value'],'cache');
109                  }    // If there is no information in cache or it is expired - reorder it
110          }    if ($info == 0 || time() > $info->expire) {
111        $StoreView = magento_stores_get_default_store_view(magento_stores_get_default_store(magento_stores_get_default_website()));
112        $info = magento_api_catalog_product_full_info($node->field_product_id[0]['value'],$StoreView);
113        $time = variable_get('magento_products_cache_time', 'CACHE_PERMANENT');
114        if ($time == 'CUSTOM') {
115          $time = variable_get('magento_products_cache_custom_time', 24);
116          cache_set('product_info_' . $node->field_product_id[0]['value'], $info,'cache',strtotime ("+". $time ." hour"));
117        } else cache_set('product_info_' . $node->field_product_id[0]['value'], $info,'cache',$time);
118      }
119    }
120    /**
121     * Getting additional product info from Cache or Magento if not cached yet
122     */
123    function magento_products_cache_full_info_by_id($product_id) {
124      //TODO SAVE into fields, not CACHE
125      $info = cache_get('product_info_' . $product_id,'cache');
126      // If there is no information in cache or it is expired - reorder it
127      if ($info == 0 || time() > $info->expire) {
128        $StoreView = magento_stores_get_default_store_view(magento_stores_get_default_store(magento_stores_get_default_website()));
129        $info = magento_api_catalog_product_full_info($product_id, $StoreView);
130        $time = variable_get('magento_products_cache_time', 'CACHE_PERMANENT');
131        if ($time == 'CUSTOM') {
132          $time = variable_get('magento_products_cache_custom_time', 24);
133          cache_set('product_info_' . $product_id, $info,'cache',strtotime ("+". $time ." hour"));
134        } else cache_set('product_info_' . $product_id, $info,'cache',$time);
135      }
136  }  }
137  /**  /**
138   * Implementation of hook_magento_event().   * Implementation of hook_magento_event().
139   */   */
140  function magento_products_magento_event($event, $productId){  function magento_products_magento_event($event, $productId){
141          // Synchonize updated product    // Synchonize updated product
142          if (($event == 'catalog_product_save' || $event == 'product_status_update') && !empty($productId)) {    if (($event == 'catalog_product_save' || $event == 'product_status_update') && !empty($productId)) {
143                  // Get product info      // Get product info
144                  $StoreView = magento_stores_get_default_store_view(magento_stores_get_default_store(magento_stores_get_default_website()));      $StoreView = magento_stores_get_default_store_view(magento_stores_get_default_store(magento_stores_get_default_website()));
145                  $product = magento_api_catalog_product_list(array('entity_id' => array('eq' => intval($productId))),$StoreView);      $product = magento_api_catalog_product_full_info($productId, $StoreView);
146                  if ($product) magento_product_synchronize($product[0]);      if ($product) magento_product_synchronize($product);
147          }    }
148          // Delete from Drupal deleted product    // Delete from Drupal deleted product
149          if ($event == 'catalog_product_delete' && !empty($productId)) {    if ($event == 'catalog_product_delete' && !empty($productId)) {
150                  // Get node id by product_id      // Get node id by product_id
151                  $nid = magento_products_get_nid($productId);      $nid = magento_products_get_nid($productId);
152                  if($nid) node_delete($nid);      if($nid) node_delete($nid);
153          }    }
154  }  }
155  /*  /*
156   * Synchronize Magento products to Drupal   * Synchronize Magento products to Drupal
157   */   */
158  function magento_products_test() {  function magento_products_test() {
159          // Get list of only SIMPLE products and synchonize it    $StoreView = magento_stores_get_default_store_view(magento_stores_get_default_store(magento_stores_get_default_website()));
160          $StoreView = magento_stores_get_default_store_view(magento_stores_get_default_store(magento_stores_get_default_website()));  
161          $list = magento_api_catalog_product_list(array('type_id' => array('like'=>'simple')),$StoreView);    // Get list of only SIMPLE products and synchonize it
162          if ($list) {    $list = magento_api_catalog_product_list(array('type_id' => array('like'=>'simple')),$StoreView);
163                  $new_products = array();    if (is_array($list) && !empty($list)) {
164                  // Synchronize every product      $new_products = array();
165                  //magento_product_synchronize($list[100]); die;      $old_products = magento_products_get_product();
166                  foreach ($list as $product)     {      // Synchronize every product
167                          magento_product_synchronize($product);      foreach ($list as $product) {
168                          $new_products[] = $product['entity_id'];        magento_product_synchronize($product);
169                  }        $new_products[] = $product['entity_id'];
170                  // Get products that was deleted in Magento and delete it in Drupal too.      }
171                  $old_products = magento_products_get_product();      // Get products that was deleted in Magento and delete it in Drupal too.
172                  $deleted_products = array_diff ($old_products, $new_products);      $deleted_products = array_diff ($old_products, $new_products);
173                  foreach ($deleted_products as $item) {      foreach ($deleted_products as $item) {
174                          $nid = magento_products_get_nid($item);        $nid = magento_products_get_nid($item);
175                          node_delete($nid);        node_delete($nid);
176                  }      }
177          }else drupal_set_message(t('There was some error with getting Product List from Magento'),'error');    }elseif($list === FALSE) drupal_set_message(t('There was some error with getting Product List from Magento'),'error');
178    
179    
180      // Synchronize Magento Offers
181      $list2 = magento_api_catalog_product_list(array('type_id' => array('like'=>'bundle')), $StoreView);
182      if (is_array($list2) && !empty($list2)) {
183        $new_offers = array();
184        $old_offers = magento_products_get_offer();
185        // Synchronize every offer
186        foreach ($list2 as $product)        {
187          magento_product_synchronize($product);
188          $new_offers[] = $product['entity_id'];
189        }
190        // Get offers that was deleted in Magento and delete it in Drupal too.
191        $deleted_offers = array_diff ($old_offers, $new_offers);
192        foreach ($deleted_offers as $item) {
193          $nid = magento_products_get_offer_nid($item);
194          node_delete($nid);
195        }
196      }elseif($list2 === FALSE) drupal_set_message(t('There was some error with getting Offer List from Magento'),'error');
197  }  }
198    
199  /* Synchronize Magento product to Drupal node  /* Synchronize Magento product to Drupal node
200   *   *
201   * @param $product   * @param $product
202   *   Array that contains information about product.   *   Array that contains information about product.
203   */   */
204  function magento_product_synchronize($product){  function magento_product_synchronize($product){
205          $node = new stdClass();    $node = new stdClass();
206          $nid = magento_products_get_nid($product['entity_id']);    $node->uid = 1;
207          // If this product is already in Drupal, get its ID    if($product['type_id'] == 'bundle') {
208          if ($nid) {    // @TODO: change this way of getting bundle info (add bundle info to return of product list function)
209                  $node->nid = $nid;    $StoreView = magento_stores_get_default_store_view(magento_stores_get_default_store(magento_stores_get_default_website()));
210                  $old_node = node_load(array('nid'=>$nid));    $product = magento_api_catalog_product_full_info($product['entity_id'], $StoreView);
211                  $node->vid = $old_node->vid;  
212          }        $nid = magento_products_get_offer_nid($product['entity_id']);
213          $node->type = 'product';        // If this offer is already in Drupal, get its ID
214          $node->uid = 1;        if ($nid) {
215          $node->status = 1;          $node->nid = $nid;
216          $node->promote = 1;          $old_node = node_load(array('nid'=>$nid));
217          // Set product data to Node fields          $node->vid = $old_node->vid;
218          $node->field_product_id[0]['value'] = $product['entity_id']; // product ID        }
219          $node->title = $product['name'];        // Name        // Set product visibility
220          $node->field_desc[0]['value'] = $product['description'];        // Description            if ($product['status'] == 2 || $product['visibility'] == 1) $node->status = 0;
221          $node->field_short_desc[0]['value'] = $product['short_description']; // Short Description            else {
222                  $node->status = 1;
223          $node->field_sku[0]['value'] = $product['sku']; // SKU                //$node->promote = 1;
224          $node->field_status[0]['value'] = $product['status'];   // Status            }
225          $node->field_weight[0]['value'] = $product['weight'];   // Weight            $node->title = $product['name'];      // Name
226          $node->field_visibility[0]['value'] = $product['visibility'];   // Visibility            if ($product['price']) $node->field_price[0]['value'] = $product['price'];
227          if ($product['news_from_date']) $node->field_new_from_date[0]['value'] = date(DATE_FORMAT,strtotime($product['news_from_date']));       // Set Product as New from Date            else $node->field_price[0]['value'] = 0;
228          else $node->field_new_from_date[0]['value'] = NULL;            // Special Price
229              $node->field_special_price[0]['value'] = $product['special_price'];
230          if ($product['news_to_date']) $node->field_new_to_date[0]['value'] = date(DATE_FORMAT,strtotime($product['news_to_date']));     // Set Product as New to Date  
231          else $node->field_new_to_date[0]['value'] = NULL;            if ($product['special_from_date']) $node->field_special_price_from_date[0]['value'] = date(DATE_FORMAT,strtotime($product['special_from_date']));     // Special Price From Date
232              else $node->field_special_price_from_date[0]['value'] = NULL;
233          $node->field_price[0]['value'] = $product['price'];     // Price  
234          $node->field_special_price[0]['value'] = $product['special_price'];     // Special Price            if ($product['special_to_date']) $node->field_special_price_to_date[0]['value'] = date(DATE_FORMAT,strtotime($product['special_to_date']));   // Special Price To Date
235          if ($product['special_from_date']) $node->field_special_price_from_date[0]['value'] = date(DATE_FORMAT,strtotime($product['special_from_date']));       // Special Price From Date            else $node->field_special_price_to_date[0]['value'] = NULL;
236          else $node->field_special_price_from_date[0]['value'] = NULL;  
237              // Tier prices
238          if ($product['special_to_date']) $node->field_special_price_to_date[0]['value'] = date(DATE_FORMAT,strtotime($product['special_to_date']));     // Special Price To Date            if ($product['tier_price']) $node->field_tier_price[0]['value'] = serialize($product['tier_price']);
239          else $node->field_special_price_to_date[0]['value'] = NULL;            else $node->field_tier_price[0]['value'] = NULL;
240    
241          $node->field_stock_availability[0]['value'] = $product['is_in_stock'];  // Stock Availability        $node->type = 'product_offer';
242          $node->body = $product['description'];    // Description
243          // RULES ID and DISCOUNT PRICES        $node->field_accroche[0]['value'] = $product['short_description']; // Short description
244          if ($product['rules']) {        $node->field_offer_id[0]['value'] = $product['entity_id']; // Offer ID
245                  $rules = array();        $node->field_price_type[0]['value'] = $product['price_type']; // 0 - Dynamic, 1 - Fixed
246                  $prices = array();  
247                  foreach ($product['rules'] as $item) {        if ($product['news_from_date']) {
248                          if (!in_array($item['rule_id'],$rules)) {          $node->field_new_from_date[0]['value'] = date(DATE_FORMAT,strtotime($product['news_from_date']));       // Set Offer Valid from date
249                                  $node->field_rules_id[] = array('value' => $item['rule_id']);          if (time() >= strtotime($product['news_from_date'])) $node->status = 1;
250                                  $rules[] = $item['rule_id'];          else $node->status = 0;
251                          }        }
252                          $prices[$item['customer_group_id']] = $item['rule_price'];        else $node->field_new_from_date[0]['value'] = NULL;
253                  }  
254                  $node->field_discount_price[0]['value'] = serialize($prices);       $node->field_stock_availability[0]['value'] = intval($product['is_in_stock']);
255          }else {       // Stock Availability
256                  $node->field_discount_price[0]['value'] = NULL;  
257                  $node->field_rules_id = NULL;        if ($product['news_to_date']) {
258          }          $node->field_new_to_date[0]['value'] = date(DATE_FORMAT,strtotime($product['news_to_date']));   // Set Offer Valid to date
259          // Tier prices          if (time() < strtotime($product['news_to_date']) && time() >= strtotime($product['news_from_date'])) $node->status = 1;
260          if ($product['tier_price']) $node->field_tier_price[0]['value'] = serialize($product['tier_price']);          else $node->status = 0;
261          else $node->field_tier_price[0]['value'] = NULL;        }
262          // Product image        else $node->field_new_to_date[0]['value'] = NULL;
263          if ($product['images']) {  
264                  // Copy image to Drupal and set it to CCK imagefield        // Offer image
265                  $image = magento_products_copy_image($product['images'][0]['url'],$product['images'][0]['file'],$nid);        if ($product['images']) {
266                  $node->field_image[0] =  array(          // Copy image to Drupal and set it to CCK imagefield
267                          'fid' => $image->fid,          $image = magento_products_copy_image($product['images'][0]['url'],$product['images'][0]['file'],$nid);
268                          'title' => $image->filename,          $node->field_image[0] =  array(
269                          'filename' => $image->filename,                  'fid' => $image->fid,
270                          'filepath' => $image->filepath,                  'title' => $image->filename,
271                          'filesize' => $image->filesize,                  'filename' => $image->filename,
272                          'list' => 1, // always list                  'filepath' => $image->filepath,
273                          'filemime' => $image->filemime,                  'filesize' => $image->filesize,
274                          'description' =>  $image->filename,                  'list' => 1, // always list
275                  );                  'filemime' => $image->filemime,
276          }                  'description' =>  $image->filename,
277          node_save($node);          );
278          if ($product['category_ids']) {        }
279                  // Save category information to taxomomy        // Process bundle items
280                  $terms = array();        if ($product['selected_products'][0] && is_array($product['selected_products'][0])) {
281                  $vocab = variable_get('magento_api_catalog_vocabulary_id', 0);                foreach ($product['selected_products'][0] as $key => $item) {
282                  foreach($product['category_ids'] as $category) {                  $node->field_items_option[$key]['value'] = serialize($item); // 0 - Dynamic, 1 - Fixed
283                          $term = magento_api_get_taxonomy_term_by_catalog_id($category);                  $node->field_linked_products[$key]['nid'] = magento_products_get_nid($item['product_id']);
284                          if ($term) $terms[$vocab][$term] = $term;                }
285                  }        }
286                  taxonomy_node_save($node, $terms);        node_save($node);
287          }    }
288          return $result;  
289      elseif($product['type_id'] == 'simple') {
290          $nid = magento_products_get_nid($product['entity_id']);
291          // If this product is already in Drupal, get its ID
292          if ($nid) {
293            $node->nid = $nid;
294            $old_node = node_load(array('nid'=>$nid));
295            $node->vid = $old_node->vid;
296          }
297          $node->type = 'product';
298          // Set product data to Node fields
299          // Set product visibility
300              if ($product['status'] == 2 || $product['visibility'] == 1) $node->status = 0;
301              else {
302                  $node->status = 1;
303                  //$node->promote = 1;
304              }
305              $node->title = $product['name'];      // Name
306    
307              if ($product['price']) $node->field_price[0]['value'] = $product['price'];
308              else $node->field_price[0]['value'] = 0;
309              // Special Price
310              $node->field_special_price[0]['value'] = $product['special_price'];
311    
312              if ($product['special_from_date']) $node->field_special_price_from_date[0]['value'] = date(DATE_FORMAT,strtotime($product['special_from_date']));     // Special Price From Date
313              else $node->field_special_price_from_date[0]['value'] = NULL;
314    
315              if ($product['special_to_date']) $node->field_special_price_to_date[0]['value'] = date(DATE_FORMAT,strtotime($product['special_to_date']));   // Special Price To Date
316              else $node->field_special_price_to_date[0]['value'] = NULL;
317    
318              // Tier prices
319              if ($product['tier_price']) $node->field_tier_price[0]['value'] = serialize($product['tier_price']);
320              else $node->field_tier_price[0]['value'] = NULL;
321    
322          $node->field_product_id[0]['value'] = $product['entity_id']; // product ID
323          $node->field_desc[0]['value'] = $product['description'];  // Description
324          $node->field_short_desc[0]['value'] = $product['short_description']; // Short Description
325    
326          $node->field_sku[0]['value'] = $product['sku']; // SKU
327          $node->field_status[0]['value'] = $product['status'];     // Status
328    
329          $node->field_weight[0]['value'] = $product['weight'];     // Weight
330          $node->field_visibility[0]['value'] = $product['visibility'];     // Visibility
331          if ($product['news_from_date']) $node->field_new_from_date[0]['value'] = date(DATE_FORMAT,strtotime($product['news_from_date'])); // Set Product as New from Date
332          else $node->field_new_from_date[0]['value'] = NULL;
333    
334          if ($product['news_to_date']) $node->field_new_to_date[0]['value'] = date(DATE_FORMAT,strtotime($product['news_to_date']));       // Set Product as New to Date
335          else $node->field_new_to_date[0]['value'] = NULL;
336    
337          $node->field_stock_availability[0]['value'] = intval($product['is_in_stock']);
338         // Stock Availability
339    
340          // Product image
341          if ($product['images']) {
342            // Copy image to Drupal and set it to CCK imagefield
343            $image = magento_products_copy_image($product['images'][0]['url'],$product['images'][0]['file'],$nid);
344            $node->field_image[0] =  array(
345                    'fid' => $image->fid,
346                    'title' => $image->filename,
347                    'filename' => $image->filename,
348                    'filepath' => $image->filepath,
349                    'filesize' => $image->filesize,
350                    'list' => 1, // always list
351                    'filemime' => $image->filemime,
352                    'description' =>  $image->filename,
353            );
354          }
355          // RULES ID and DISCOUNT PRICES
356          if ($product['rules']) {
357            $rules = array();
358            $prices = array();
359            foreach ($product['rules'] as $item) {
360              if (!in_array($item['rule_id'],$rules)) {
361                $node->field_rules_id[] = array('value' => $item['rule_id']);
362                $rules[] = $item['rule_id'];
363              }
364              $prices[$item['customer_group_id']] = $item['rule_price'];
365            }
366            $node->field_discount_price[0]['value'] = serialize($prices);
367          }else {
368            $node->field_discount_price[0]['value'] = NULL;
369            $node->field_rules_id = NULL;
370          }
371    
372          // store non magento fields
373          if ($nid) {
374                  foreach (get_object_vars($old_node) as $key=>$value) {
375                    if (!property_exists($node, $key)) {
376                      $node->{$key} = $value;
377                    }
378                  }
379          }
380          node_save($node);
381          if ($product['category_ids']) {
382            // Save category information to taxomomy
383            $vocab = intval(variable_get('magento_api_catalog_vocabulary_id', 0));
384            $terms = array();
385            // save old taxomony exept catalog vobabulary
386            if (!empty($node->taxonomy)) {
387              foreach ($node->taxonomy as $key => $term_obj) {
388                if (is_object($term_obj)) {
389                  if ($term_obj->vid != $vocab) {
390                    $terms[$term_obj->vid][$term_obj->tid] = $term_obj->tid;
391                  }
392                }
393                if (is_array($term_obj)) {
394                  foreach($term_obj as $tid) {
395                    $terms[$key][$tid] = $tid;
396                  }
397                }
398              }
399            }
400            // add catalog vobabulary terms
401            foreach($product['category_ids'] as $category) {
402              $term = magento_api_get_taxonomy_term_by_catalog_id($category);
403              if ($term) $terms[$vocab][$term] = $term;
404            }
405            taxonomy_node_save($node, $terms);
406          }
407      }
408      return $result;
409  }  }
410  /* Get node ID by product ID  /* Get node ID by product ID
411   *   *
# Line 244  function magento_product_synchronize($pr Line 416  function magento_product_synchronize($pr
416   *       Node ID.   *       Node ID.
417   */   */
418  function magento_products_get_nid($product_id) {  function magento_products_get_nid($product_id) {
419          $sql = db_fetch_array(db_query('SELECT nid FROM {content_type_product} WHERE field_product_id_value = %d',$product_id));    $sql = db_fetch_array(db_query('SELECT nid FROM {content_type_product} WHERE field_product_id_value = %d',$product_id));
420          return $sql['nid'];    return $sql['nid'];
421    }
422    /* Get node ID by offer ID
423     *
424     * @param $offer_id
425     *   Offer ID.
426     *
427     * @return
428     *       Node ID.
429     */
430    function magento_products_get_offer_nid($offer_id) {
431      $sql = db_fetch_array(db_query('SELECT nid FROM {content_type_product_offer} WHERE field_offer_id_value = %d',$offer_id));
432      return $sql['nid'];
433  }  }
434  /* Get product list from Drupal nodes  /* Get product list from Drupal nodes
435   *   *
# Line 253  function magento_products_get_nid($produ Line 437  function magento_products_get_nid($produ
437   *       Array that contains product ID from nodes.   *       Array that contains product ID from nodes.
438   */   */
439  function magento_products_get_product() {  function magento_products_get_product() {
440          $old_products = array();    $old_products = array();
441          $query = db_query('SELECT field_product_id_value FROM {content_type_product} ORDER BY field_product_id_value ASC');    $query = db_query('SELECT field_product_id_value FROM {content_type_product} ORDER BY field_product_id_value ASC');
442          while ($sql = db_fetch_array($query)) {    while ($sql = db_fetch_array($query)) {
443                  array_push($old_products,$sql['field_product_id_value']);      array_push($old_products,$sql['field_product_id_value']);
444          }    }
445          return $old_products;    return $old_products;
446    }
447    /* Get offer list from Drupal nodes
448     *
449     * @return
450     *       Array that contains offer ID from nodes.
451     */
452    function magento_products_get_offer() {
453      $old_offers = array();
454      $query = db_query('SELECT field_offer_id_value FROM {content_type_product_offer} ORDER BY field_offer_id_value ASC');
455      while ($sql = db_fetch_array($query)) {
456        array_push($old_offers,$sql['field_product_id_value']);
457      }
458      return $old_offers;
459  }  }
460  /* Copy image from outside URL to Drupal path  /* Copy image from outside URL to Drupal path
461   *   *
# Line 273  function magento_products_get_product() Line 470  function magento_products_get_product()
470   *       Image object.   *       Image object.
471   */   */
472  function magento_products_copy_image($url, $new_url, $nid = NULL) {  function magento_products_copy_image($url, $new_url, $nid = NULL) {
473          // Copy image from outside URL to Drupal    // Copy image from outside URL to Drupal
474          $field = content_fields('field_image', 'product');    $field = content_fields('field_image', 'product');
475          $files_path = filefield_widget_file_path($field);    $files_path = filefield_widget_file_path($field);
476    
477          // Create directory, if not exists    // Create directory, if not exists
478          $dir = $files_path . dirname($new_url);    $dir = $files_path . dirname($new_url);
479          field_file_check_directory($dir, FILE_CREATE_DIRECTORY);    field_file_check_directory($dir, FILE_CREATE_DIRECTORY);
480    
481          $image = new stdClass();    $image = new stdClass();
482          $name = $files_path . $new_url;    $name = $files_path . $new_url;
483          // Check if this file is already in Drupal    // Check if this file is already in Drupal
484          $sql = db_fetch_array(db_query('SELECT * FROM {files} WHERE filepath = "%s" AND filesize = %d', $name, getSizeFile($url)));    $sql = db_fetch_array(db_query('SELECT * FROM {files} WHERE filepath = "%s" AND filesize = %d', $name, getSizeFile($url)));
485          if ($sql) {    if ($sql) {
486                  // Check if this file was deleted from file system by some reason      // Check if this file was deleted from file system by some reason
487                  // and re-copy it      // and re-copy it
488                  if (is_file($name) == FALSE) {      if (is_file($name) == FALSE) {
489                          $file_temp = file_get_contents($url);        $file_temp = file_get_contents($url);
490                          $file_temp2 = file_save_data($file_temp, $name , FILE_EXISTS_REPLACE);        $file_temp2 = file_save_data($file_temp, $name , FILE_EXISTS_REPLACE);
491                  }      }
492                  $image->filename = $sql['filename'];      $image->filename = $sql['filename'];
493                  $image->filepath = $sql['filepath'];      $image->filepath = $sql['filepath'];
494                  $image->uid = $sql['uid'];      $image->uid = $sql['uid'];
495                  $image->fid = $sql['fid'];      $image->fid = $sql['fid'];
496                  $image->filemime = $sql['filemime'];      $image->filemime = $sql['filemime'];
497                  $image->filesize = $sql['filesize'];      $image->filesize = $sql['filesize'];
498                  $image->status = $sql['status'];      $image->status = $sql['status'];
499                  $image->timestamp = $sql['timestamp'];      $image->timestamp = $sql['timestamp'];
500                  return $image;      return $image;
501          }else {    }else {
502                  //Delete OLD Images      //Delete OLD Images
503                  $result = db_fetch_array(db_query('SELECT f.filepath FROM {content_type_product} AS ctp INNER JOIN {files} AS f ON f.fid = ctp.field_image_fid WHERE nid=%d',$nid));      if ($nid) {
504                  if ($result)  {        $node = node_load($nid);
505                          db_query('DELETE FROM {files} WHERE filepath = "%s"', $result['filepath']);        $result = filefield_get_node_files($node, 'field_image');
506                          file_delete($result['filepath']);        if (!empty($result))  {
507                  }          foreach ($result as $image_file) {
508                  //      Save file to file system and Drupal            db_query('DELETE FROM {files} WHERE filepath = "%s"', $image_file['filepath']);
509                  $file_temp = file_get_contents($url);            file_delete($image_file['filepath']);
510                  $file_temp2 = file_save_data($file_temp, $name , FILE_EXISTS_REPLACE);          }
511          }
512                  $image->filename = basename($file_temp2);        //        Save file to file system and Drupal
513                  $image->filepath = $file_temp2;        $file_temp = file_get_contents($url);
514                  $image->uid = 1;        $file_temp2 = file_save_data($file_temp, $name , FILE_EXISTS_REPLACE);
515                  $image->filemime = file_get_mimetype($file_temp2);  
516                  $image->filesize = filesize($file_temp2);        $image->filename = basename($file_temp2);
517                  $image->status = FILE_STATUS_TEMPORARY;        $image->filepath = $file_temp2;
518                  $image->timestamp = time();        $image->uid = 1;
519          $image->filemime = file_get_mimetype($file_temp2);
520                  drupal_write_record('files', $image);        $image->filesize = filesize($file_temp2);
521                  file_set_status($image,1);        $image->status = FILE_STATUS_TEMPORARY;
522          }        $image->timestamp = time();
523          return $image;  
524          drupal_write_record('files', $image);
525          file_set_status($image,1);
526        }
527      }
528      return $image;
529  }  }
530  /*  /*
531   *  Get filesize by outside URL   *  Get filesize by outside URL
# Line 332  function magento_products_copy_image($ur Line 534  function magento_products_copy_image($ur
534   *      filesize   *      filesize
535   */   */
536  function getSizeFile($url) {  function getSizeFile($url) {
537          if (substr($url, 0, 4) == 'http') {    if (substr($url, 0, 4) == 'http') {
538                  $filesize = array_change_key_case(get_headers($url, 1),CASE_LOWER);      $filesize = array_change_key_case(get_headers($url, 1),CASE_LOWER);
539                  if ( strcasecmp($filesize[0], 'HTTP/1.1 200 OK') != 0 ) {      if ( strcasecmp($filesize[0], 'HTTP/1.1 200 OK') != 0 ) {
540                          $filesize = $filesize['content-length'][1];        $filesize = $filesize['content-length'][1];
541                  } else {      } else {
542                          $filesize = $filesize['content-length'];        $filesize = $filesize['content-length'];
543                  }      }
544          } else {    } else {
545                  $filesize = @filesize($url);      $filesize = @filesize($url);
546          }    }
547          return $filesize;    return $filesize;
548  }  }
549  /*  /*
550   *  Get product actual price   *  Get product actual price
# Line 355  function getSizeFile($url) { Line 557  function getSizeFile($url) {
557   *      Actual product price   *      Actual product price
558   */   */
559  function magento_products_get_actual_price($node, $user){  function magento_products_get_actual_price($node, $user){
560          // Get customer group of current user    // Get customer group of current user
561          $group_id = magento_users_get_user_group($user);    $group_id = magento_users_get_user_group($user);
562          //return $group_id; break;    //return $group_id; break;
563          $price = $node->field_price[0]['value'];    $price = $node->field_price[0]['value'];
564          $time = time();    $time = time();
565          // Get special price and check if it is actual and less than original price    // Get special price and check if it is actual and less than original price
566          $special_price = $node->field_special_price[0]['value'];    $special_price = $node->field_special_price[0]['value'];
567          if ($special_price) {    if ($special_price) {
568                  if ($special_price < $price) {      if ($special_price < $price) {
569                          if (empty($node->field_special_price_from_date[0]['value'])) {        if (empty($node->field_special_price_from_date[0]['value'])) {
570                                  if ($time <= strtotime($node->field_special_price_to_date[0]['value'])) $price = $special_price;          if ($time <= strtotime($node->field_special_price_to_date[0]['value'])) $price = $special_price;
571                          }elseif (empty($node->field_special_price_to_date[0]['value'])) {        }elseif (empty($node->field_special_price_to_date[0]['value'])) {
572                                  if ($time >= strtotime($node->field_special_price_from_date[0]['value'])) $price = $special_price;          if ($time >= strtotime($node->field_special_price_from_date[0]['value'])) $price = $special_price;
573                          } else {        } else {
574                                  if ($time >= strtotime($node->field_special_price_from_date[0]['value']) && $time <= strtotime($node->field_special_price_to_date[0]['value'])) $price = $special_price;          if ($time >= strtotime($node->field_special_price_from_date[0]['value']) && $time <= strtotime($node->field_special_price_to_date[0]['value'])) $price = $special_price;
575                          }        }
576                  }      }
577          }    }
578          // Get discount price and check if it is actual for current customer group and less than original price    // Get discount price and check if it is actual for current customer group and less than original price
579          $discount_price = unserialize($node->field_discount_price[0]['value']);    $discount_price = unserialize($node->field_discount_price[0]['value']);
580          if ($discount_price) {    if ($discount_price) {
581                  if ($discount_price[$group_id] < $price) $price = $discount_price[$group_id];      if ($discount_price[$group_id] < $price) $price = $discount_price[$group_id];
582          }    }
583          return floatval($price);    return floatval($price);
584  }  }
585  /*  /*
586   *  Get information about Tier Prices   *  Get information about Tier Prices
# Line 391  function magento_products_get_actual_pri Line 593  function magento_products_get_actual_pri
593   *      Array that contains information about tier price and qty   *      Array that contains information about tier price and qty
594   */   */
595  function magento_products_get_tier_price($node, $price) {  function magento_products_get_tier_price($node, $price) {
596          global $user;    global $user;
597          $product_tier = array();    $product_tier = array();
598          $tier_price = unserialize($node->field_tier_price[0]['value']);    $tier_price = unserialize($node->field_tier_price[0]['value']);
599          if ($tier_price) {    if ($tier_price) {
600                  foreach ($tier_price as $tier) {      foreach ($tier_price as $tier) {
601                          // Check if tier price less that current product price        // Check if tier price less that current product price
602                          if ($tier['price'] <= $price) {        if ($tier['price'] <= $price) {
603                                  if ($tier['all_groups']) $product_tier[intval($tier['price_qty'])] = floatval($tier['price']);          if ($tier['all_groups']) $product_tier[intval($tier['price_qty'])] = floatval($tier['price']);
604                                  elseif($tier['cust_group'] == magento_users_get_user_group($user)) $product_tier[intval($tier['price_qty'])] = floatval($tier['price']);          elseif($tier['cust_group'] == magento_users_get_user_group($user)) $product_tier[intval($tier['price_qty'])] = floatval($tier['price']);
605                          }        }
606                  }      }
607      }
608      return $product_tier;
609    }
610    /*
611     * Get actual price for product offer
612     *  @param $node
613     *      Product node
614     *  @param $user
615     *      Current user
616     *
617     *  @return $price
618     *      Actual offer price
619     */
620    function magento_products_get_offer_price($node, $user, $selected_list = NULL) {
621        $price = $node->field_price[0]['value'];
622        $time = time();
623        // Get special price rate and check if it is actual
624        $rate = NULL;
625        $special_price = $node->field_special_price[0]['value'];
626        if ($special_price) {
627            if (empty($node->field_special_price_from_date[0]['value'])) {
628              if ($time <= strtotime($node->field_special_price_to_date[0]['value'])) $rate = $special_price;
629            }elseif (empty($node->field_special_price_to_date[0]['value'])) {
630              if ($time >= strtotime($node->field_special_price_from_date[0]['value'])) $rate = $special_price;
631            } else {
632              if ($time >= strtotime($node->field_special_price_from_date[0]['value']) && $time <= strtotime($node->field_special_price_to_date[0]['value'])) $rate = $special_price;
633            }
634        }
635        $StoreView = magento_stores_get_default_store_view(magento_stores_get_default_store(magento_stores_get_default_website()));
636        $info = magento_api_catalog_product_full_info(59, $StoreView);
637    
638        if($node->field_price_type[0]['value'] == 1) {// If bundle price is fixes
639            foreach($node->field_linked_products as $key => $item) {
640                $data = unserialize($node->field_items_option[$key]['value']);
641                $item_node = node_load(array('nid' => magento_products_get_nid($data['product_id'])));
642                // Add condition if Item if availible in stock
643                if ($item_node->status && $item_node->field_stock_availability[0]['value'] != 0) {
644                        if ($item['selection_price_type'] == 0) { //Fixed item cost
645                            $price = $price + $data['selection_price_value']*$data['selection_qty'];
646                        }elseif ($item['selection_price_type'] == 1) { // Item cost based on base bundle price
647                            $price = $price + $node->field_price[0]['value']*$data['selection_price_value']*$data['selection_qty']/100;
648                        }
649                }
650            }
651        }elseif($node->field_price_type[0]['value'] == 0) { //If bundle price is dynamic
652            foreach($node->field_linked_products as $key => $item) {
653                    $data = unserialize($node->field_items_option[$key]['value']);
654                    $item_node = node_load(array('nid' => magento_products_get_nid($data['product_id'])));
655                    // Add condition if Item if availible in stock
656                    if ($item_node->status && $item_node->field_stock_availability[0]['value'] != 0) {
657                        $item_price = magento_products_get_actual_price($item_node, $user);
658                        $item_tier = magento_products_get_tier_price($item_node, $item_price);
659                        if (!empty($item_tier)) {
660                            foreach($item_tier as $key => $tier) {
661                                if ($data['selection_qty'] >= $key) $item_price = $tier;
662                            }
663                        }
664                        $price = $price + $item_price*$data['selection_qty'];
665                    }
666            }
667        }
668    
669    
670        // If special price is actual - use it as multiplier for bundle total price
671        if ($rate) $price = $price*$rate/100;
672    
673    return $price;
674    }
675    /*
676     * Function that checks offer valid date
677     */
678    function magento_products_offer_valid_check() {
679        $query = db_query("SELECT node.nid, node.status, from_date.field_new_from_date_value, to_date.field_new_to_date_value
680                                            FROM {node} node
681                                            LEFT JOIN {content_field_new_from_date} from_date ON from_date.vid = node.vid
682                                            LEFT JOIN {content_field_new_to_date} to_date ON to_date.vid = node.vid
683                                            WHERE node.type = 'product_offer'");
684        while ($result = db_fetch_array($query)){
685            $status = $result['status'];
686            if ($result['field_new_from_date_value']) {
687                    if (time() >= strtotime($result['field_new_from_date_value'])) $status = 1;
688                    else $status = 0;
689            }
690            if ($result['field_new_to_date_value']) {
691                    if (time() < strtotime($result['field_new_to_date_value']) && time() >= strtotime($result['field_new_from_date_value'])) $status = 1;
692                    else $status = 0;
693            }
694            db_query("UPDATE {node} SET status = %d WHERE nid = %d", $status, $result['nid']);
695          }          }
         return $product_tier;  
696  }  }

Legend:
Removed from v.1.1  
changed lines
  Added in v.1.2

  ViewVC Help
Powered by ViewVC 1.1.3