You are here

globallink_commerce.inc in GlobalLink Connect for Drupal 7.7

File

globallink_commerce/globallink_commerce.inc
View source
<?php

/**
 * Sends commerce for translation.
 *
 * @param array $pids
 *   The array of commerce products IDs.
 * @param string $pd4
 *   The project director details.
 * @param string $submission_name
 *   The name of the submission.
 * @param string $due_date
 *   When the translation is due.
 * @param string $project_code
 *   The project's registered code.
 * @param string $source_locale
 *   The locale of the content being translated.
 * @param array $target_locale_arr
 *   Array of desired locales to translate into.
 * @param array $submission_details
 *   Associative array of details about the submission.
 *
 * @return object
 *   GlobalLink object that represents active translation.
 */
function globallink_commerce_send_for_translations($pids, $pd4, $submission_name, $due_date, $project_code, $source_locale, $target_locale_arr, $submission_details, $submission_priority) {
  module_load_include('inc', 'globallink', 'gl_ws/gl_ws_send_translations');
  module_load_include('inc', 'globallink', 'globallink');
  $submitter = $submission_details['submitter'];
  $globallink_arr = array();
  foreach ($pids as $pid) {
    $rows = globallink_commerce_get_sent_rows_by_pid($pid);
    $target_arr = $target_locale_arr;
    $cp_info = globallink_commerce_get_info($pid);
    $title = $cp_info->title;
    foreach ($rows as $row) {
      if (array_search($row->target_lang_code, $target_locale_arr)) {
        unset($target_arr[$row->target_lang_code]);
        watchdog(GLOBALLINK_MODULE, 'Skipping CP Id - %id for locales %locale', array(
          '%id' => $pid,
          '%locale' => $row->target_lang_code,
        ), WATCHDOG_DEBUG);
      }
    }
    if (empty($target_arr)) {
      continue;
    }
    $xml = globallink_commerce_get_xml($pid, $target_arr);
    $name = 'Commerce_Product_' . $pid . '.xml';
    $globallink = new GlobalLink();
    $globallink->type = GLOBALLINK_ENTITY_TYPE_COM;
    $globallink->metadata = GLOBALLINK_ENTITY_TYPE_COM;
    $globallink->title = $title;
    $globallink->sourceLocale = $source_locale;
    $globallink->targetLocale = $target_arr;
    $globallink->sourceXML = $xml;
    $globallink->sourceFileName = $name;
    $globallink->submissionName = $submission_name;
    $globallink->submissionPriority = $submission_priority;
    $globallink->dueDate = $due_date;
    $globallink->otherObjectId = $pid;
    $globallink->submissionInstructions = $submission_details['instructions'] . "\nSubmitter: " . $submitter;
    $globallink_arr[GLOBALLINK_ENTITY_TYPE_COM][] = $globallink;
  }
  return $globallink_arr;
}

/**
 * Gets XML data from specific commerce product.
 *
 * @param string $pid
 *   The commerce product ID.
 *
 * @return array
 *   Associative array of commerce product XML data.
 */
function globallink_commerce_get_xml($pid, $target_arr) {
  $dom = new DOMDocument('1.0', 'UTF-8');
  $dom->formatOutput = TRUE;
  $root = $dom
    ->createElement('content');
  $dom
    ->appendChild($root);
  $id = $dom
    ->createAttribute('pid');
  $id->value = $pid;
  $root
    ->appendChild($id);
  $commerce_product = commerce_product_load($pid);
  $language = $commerce_product->language;
  if (module_exists('metatag')) {
    $lang = entity_language('commerce_product', $commerce_product);
    if (isset($commerce_product->metatags)) {
      if (globallink_is_field_configured_for_translation('commerce_product', 'cp:' . $commerce_product->type, 'metatags', 'cp:' . $commerce_product->type)) {
        if (!empty($commerce_product->metatags[$lang])) {
          $metatags = $commerce_product->metatags[$lang];
          foreach ($metatags as $name => $value) {
            if (isset($value['value'])) {
              globallink_insert_child_element($dom, $root, 'metatag', $value['value'], array(
                'entity_type' => 'commerce_product',
                'name' => $name,
                'label' => 'Metatag - ' . ucwords($name),
              ));
            }
          }
        }
      }
    }
  }
  $fields = globallink_commerce_get_fields($commerce_product->type);
  $configured_fields = globallink_get_configured_fields_for_cp($commerce_product->type);
  foreach ($fields as $field) {
    if (empty($commerce_product->{$field})) {
      continue;
    }
    $language = field_language('commerce_product', $commerce_product, $field, NULL);
    $field_values = field_get_items('commerce_product', $commerce_product, $field, $language);
    $field_info = field_info_field($field);
    if ($field_values) {
      $parent_fc = '';
      if ($field_info['type'] == 'field_collection') {
        $parent_fc = $field;
        if (isset($field_values[0]['revision_id'])) {
          $field_collection_item_entity = entity_load('field_collection_item', array(
            $field_values[0]['value'],
          ), array(
            'revision_id' => $field_values[0]['revision_id'],
          ));
        }
        globallink_commerce_traverse_fields_and_field_collections('commerce_product', $commerce_product->type, $parent_fc, $commerce_product->type, $commerce_product->pid, $field_values, $field, $dom, $root, $commerce_product, $target_arr, $language);
      }
    }
    if (array_key_exists($field, $configured_fields) && $configured_fields[$field]->translatable == 1) {
      $field_values = field_get_items('commerce_product', $commerce_product, $field, $language);
      $field_info = field_info_field($field);
      if (is_array($field_values) && !empty($field_values)) {
        foreach ($field_values as $delta => $values) {
          if ($field_info['type'] == 'link_field') {
            globallink_insert_child_element($dom, $root, 'field', $values['title'], array(
              'field_name' => $field,
              'delta' => $delta,
              'langcode' => $language,
            ));
          }
          elseif ($field_info['type'] == 'image') {
            if (isset($values['alt'])) {
              globallink_insert_child_element($dom, $root, 'field_image', $values['alt'], array(
                'field_name' => $field,
                'type' => 'alt',
                'delta' => $delta,
                'langcode' => $language,
              ));
            }
            if (isset($values['title'])) {
              globallink_insert_child_element($dom, $root, 'field_image', $values['title'], array(
                'field_name' => $field,
                'type' => 'title',
                'delta' => $delta,
                'langcode' => $language,
              ));
            }
          }
          elseif (!empty($values['value'])) {
            globallink_insert_child_element($dom, $root, 'field', $values['value'], array(
              'field_name' => $field,
              'delta' => $delta,
              'langcode' => $language,
            ));
          }
        }
      }
      elseif (!empty($field_values) && is_string($field_values)) {

        // Test this without field translation
        globallink_insert_child_element($dom, $root, 'field', $field_values, array(
          'field_name' => $field,
        ));
      }
    }
  }
  $xml = $dom
    ->saveXML();
  return $xml;
}

/**
 * Gets commerce product fields based on bundle.
 *
 * @param string $bundle
 *   The bundle.
 *
 * @return array
 *   Array of fields.
 */
function globallink_commerce_get_fields($bundle) {
  $fields = array();
  $info = entity_get_info('commerce_product');
  foreach ($info['bundles'] as $bundle_name => $bundle_info) {
    if ($bundle_name == $bundle) {
      foreach (field_info_instances('commerce_product', $bundle_name) as $field) {
        $fields[] = $field['field_name'];
      }
    }
  }
  return $fields;
}

/**
 * Gets commerce product translation status.
 *
 * @param string $pid
 *   The commerce product ID.
 * @param string $tgt_locale
 *   The target locale.
 * @param string $title
 *   The translation title.
 *
 * @return string
 *   Status message.
 */
function globallink_commerce_check_delete($pid) {
  $entity = commerce_product_load($pid);
  if (empty($entity)) {
    return TRUE;
  }
  return FALSE;
}

/**
 * Gets sent commerce product rows by product ID.
 *
 * @param string $pid
 *   The commerce product ID.
 *
 * @return array
 *   Array of commerce product rows.
 */
function globallink_commerce_get_sent_rows_by_pid($pid) {
  $result = db_select('globallink_document', 'tc')
    ->fields('tc')
    ->condition('object_id', $pid, '=')
    ->condition('entity_type', GLOBALLINK_ENTITY_TYPE_COM, '=')
    ->condition('target_status', array(
    GLOBALLINK_STATUS_TRANSLATION_SENT,
    GLOBALLINK_STATUS_TRANSLATION_ERROR,
    GLOBALLINK_STATUS_TRANSLATION_COMPLETED,
  ), 'IN')
    ->execute();
  $rows = array();
  foreach ($result as $row) {
    $rows[] = $row;
  }
  return $rows;
}

/**
 * Gets array of translated commerce products.
 *
 * @param object $xml
 *   XML representation of commerce product.
 *
 * @return array
 *   Associative array of translated comemrce products.
 */
function globallink_commerce_get_translated_array($xml) {
  if (is_null($xml) || !is_string($xml) || $xml == '') {
    return array();
  }
  $dom = new DomDocument();
  $dom->preserveWhiteSpace = FALSE;
  $dom
    ->loadXML($xml);
  $arr = array();
  $titles = $dom
    ->getElementsByTagName('title');
  foreach ($titles as $title) {
    $arr['title'] = $title->nodeValue;
  }
  $contents = $dom
    ->getElementsByTagName('content');
  $pid = '';
  foreach ($contents as $content) {
    if (!is_null($content->attributes)) {
      foreach ($content->attributes as $attr_name => $attr_node) {
        if ($attr_name == 'pid') {
          $pid = $attr_node->value;
        }
      }
    }
  }
  if ($pid == '') {
    return array();
  }
  $arr['pid'] = $pid;
  $field_image = $dom
    ->getElementsByTagName('field_image');
  foreach ($field_image as $attr) {
    $field_image_object = new GLFieldImage();
    if (!is_null($attr->attributes)) {
      foreach ($attr->attributes as $attr_name => $attr_node) {
        switch ($attr_name) {
          case 'type':
            if ($attr_node->value == 'title') {
              $field_image_object->title = $attr->nodeValue;
            }
            elseif ($attr_node->value == 'alt') {
              $field_image_object->alt = $attr->nodeValue;
            }
            continue 2;
          case 'delta':
            $field_image_object->delta = $attr_node->value;
            continue 2;
          case 'field_name':
            $field_image_object->field_name = $attr_node->value;
            continue 2;
          case 'subfield':
            $field_image_object->subfield = $attr_node->value;
            $field_image_object->{$field_image_object->subfield} = $attr->nodeValue;
            $field_image_object->type = 'file_entity';
            continue 2;
          case 'langcode':
            $field_image_object->langcode = $attr_node->value;
            continue 2;
          case 'label':
          case 'subfield_label':
            $field_image_object->{$attr_name} = $attr_node->value;
            continue 2;
        }
      }
      if (is_null($field_image_object->delta)) {
        $field_image_object->delta = '0';
      }
      if (isset($field_image_object->field_name)) {
        if (!isset($arr[$field_image_object->field_name][$field_image_object->langcode][$field_image_object->delta])) {
          $arr[$field_image_object->field_name][$field_image_object->langcode][$field_image_object->delta] = new GLFieldImage();
        }
        if (isset($field_image_object->title)) {
          $arr[$field_image_object->field_name][$field_image_object->langcode][$field_image_object->delta]->title = $field_image_object->title;
        }
        if (isset($field_image_object->alt)) {
          $arr[$field_image_object->field_name][$field_image_object->langcode][$field_image_object->delta]->alt = $field_image_object->alt;
        }
      }
      else {
        $arr[$field_image_object->field_name][$field_image_object->langcode][$field_image_object->delta] = $field_image_object;
      }
    }
  }
  $fields = $dom
    ->getElementsByTagName('field');
  foreach ($fields as $field) {
    $field_obj = new GLField();
    $field_obj->type = 'field';
    $field_obj->translatedContent = $field->nodeValue;
    if (is_null($field->attributes)) {
      continue;
    }
    foreach ($field->attributes as $attr_name => $attr_node) {
      switch ($attr_name) {
        case 'field_name':
          $field_obj->fieldName = $attr_node->value;
          continue 2;
        case 'delta':
          $field_obj->delta = $attr_node->value;
          continue 2;
        case 'langcode':
          $field_obj->langcode = $attr_node->value;
          continue 2;
        case 'parent_fc':
          $field_obj->parentFCName = $attr_node->value;
          continue 2;
        case 'bundle':
          $field_obj->bundle = $attr_node->value;
          continue 2;
        case 'entity_id':
          $field_obj->entityId = $attr_node->value;
          continue 2;
        case 'entity_type':
          $field_obj->entityType = $attr_node->value;
          continue 2;
      }
    }
    if (is_null($field_obj->langcode)) {
      $field_obj->langcode = LANGUAGE_NONE;
    }
    if (is_null($field_obj->delta)) {
      $field_obj->delta = '0';
    }
    if ($field_obj->entityType == 'field_collection_item') {
      $arr['field_collection'][$field_obj->parentFCName][$field_obj->bundle][$field_obj->entityId][$field_obj->fieldName][$field_obj->langcode][$field_obj->delta] = $field_obj;
    }
    else {
      $arr[$field_obj->fieldName][$field_obj->langcode][$field_obj->delta] = $field_obj;
    }
  }
  $metatags = $dom
    ->getElementsByTagName('metatag');
  foreach ($metatags as $metatag) {
    $metatag_obj = new GLField();
    $metatag_obj->type = 'metatag';
    $metatag_obj->translatedContent = $metatag->nodeValue;
    if (is_null($metatag->attributes)) {
      continue;
    }
    foreach ($metatag->attributes as $attr_name => $attr_node) {
      switch ($attr_name) {
        case 'entity_type':
          $metatag_obj->entityType = $attr_node->value;
          continue 2;
        case 'content_type':
          $field_obj->contentType = $attr_node->value;
          continue 2;
        case 'bundle':
          $field_obj->bundle = $attr_node->value;
          continue 2;
        case 'entity_id':
          $metatag_obj->entityId = $attr_node->value;
          continue 2;
        case 'name':
          $metatag_obj->fieldName = $attr_node->value;
          continue 2;
        case 'label':
          $metatag_obj->fieldLabel = $attr_node->value;
          continue 2;
      }
    }
    if (is_null($metatag_obj->entityId)) {
      $metatag_obj->entityId = '0';
    }
    if (is_null($metatag_obj->bundle)) {
      $metatag_obj->bundle = $metatag_obj->fieldName;
    }
    $arr['metatag'][$metatag_obj->bundle][$metatag_obj->entityId] = $metatag_obj;
  }
  return $arr;
}
function globallink_commerce_import(&$globallink) {
  module_load_include('inc', 'globallink', 'globallink');
  $target_xml = $globallink->targetXML;
  try {
    if (empty($target_xml)) {
      throw new Exception("Target XML is missing.");
    }
    $target_locale = globallink_get_drupal_locale_code($globallink->targetLocale);
    $source_locale = globallink_get_drupal_locale_code($globallink->sourceLocale);
    $translated_arr = globallink_commerce_get_translated_array($target_xml);
    $pid = $translated_arr['pid'];
    unset($translated_arr['pid']);
    $product = commerce_product_load($pid);
    if (empty($product)) {
      $globallink->status = GLOBALLINK_STATUS_TRANSLATION_SOURCE_DELETED;
      $globallink->sourceDeleted = TRUE;
      return;
    }
    if (module_exists('metatag')) {
      if (isset($translated_arr['metatag'])) {
        $lang = entity_language('commerce_product', $product);
        $target_metatag_arr = $translated_arr['metatag'];
        if (!empty($product->metatags[$lang])) {
          $metatags_names = array_keys($product->metatags[$lang]);
          $n_metatag =& $product->metatags;
          foreach ($metatags_names as $name) {
            if (isset($target_metatag_arr[$name]) && isset($target_metatag_arr[$name][0])) {
              $gl_obj = $target_metatag_arr[$name]['0'];
              if (is_object($gl_obj)) {
                $translated_content = $gl_obj->translatedContent;
              }
              else {
                $translated_content = $gl_obj;
              }
              $n_metatag[$target_locale][$name] = array(
                'value' => $translated_content,
              );
            }
          }
        }
      }
    }
    $fields = globallink_commerce_get_fields($product->type);
    foreach ($fields as $field) {
      $field_def = field_read_field($field);
      $t_field_lang = LANGUAGE_NONE;
      if ($field_def['type'] == 'image') {
        if (isset($product->{$field}[$source_locale])) {
          $product->{$field}[$target_locale] = $product->{$field}[$source_locale];
          $delta = key($product->{$field}[$target_locale]);
          $obj = $translated_arr[$field][$source_locale][$delta];
          if (is_object($obj)) {
            if (isset($obj->title)) {
              $product->{$field}[$target_locale][$delta]['title'] = $obj->title;
            }
            if (isset($obj->alt)) {
              $product->{$field}[$target_locale][$delta]['alt'] = $obj->alt;
            }
          }
        }
      }
      else {
        if (empty($translated_arr[$field])) {
          if (isset($product->{$field}[$source_locale])) {
            $product->{$field}[$target_locale] = $product->{$field}[$source_locale];
          }
          continue;
        }
        if (key($translated_arr[$field]) !== LANGUAGE_NONE) {
          $t_field_lang = key($translated_arr[$field]);
        }
        if (empty($product->{$field}[$target_locale]) && $target_locale != LANGUAGE_NONE) {
          $product->{$field}[$target_locale] = $product->{$field}[$t_field_lang];
        }
        $t_field_arr = $translated_arr[$field][$source_locale];
        foreach ($product->{$field}[$target_locale] as $delta => $fp_field) {
          if (empty($t_field_arr[$delta])) {
            continue;
          }
          $translation = $t_field_arr[$delta]->translatedContent;
          if ($field_def['type'] == 'link_field') {
            $product->{$field}[$target_locale][$delta]['title'] = $translation;
          }
          else {
            $product->{$field}[$target_locale][$delta]['value'] = $translation;
          }
        }
      }
    }
    $product->revision = 1;
    $product->translations->data[$target_locale] = array(
      'language' => $target_locale,
      // Target language
      'source' => $source_locale,
      // Source language
      'uid' => $product->uid,
      'status' => variable_get('globallink_publish_node', 0),
      // publish translation
      'translate' => 0,
      // Translation out of date
      'created' => $product->created,
    );
    $product->translations->hook[$target_locale] = array(
      'hook' => 'insert',
      'date' => NULL,
    );
    $result = commerce_product_save($product);
    if ($result != FALSE) {
      if (module_exists('field_collection') && isset($translated_arr['field_collection'])) {
        globallink_commerce_save_field_collections($product, $translated_arr, $target_locale);
      }
    }
  } catch (Exception $e) {
    $globallink->status = GLOBALLINK_STATUS_TRANSLATION_ERROR;
    watchdog(GLOBALLINK_MODULE, 'Exception - %function - File[%file], Line[%line], Code[%code], Message[%message]', array(
      '%function' => __FUNCTION__,
      '%file' => $e
        ->getFile(),
      '%line' => $e
        ->getLine(),
      '%code' => $e
        ->getCode(),
      '%message' => $e
        ->getMessage(),
    ), WATCHDOG_ERROR);
  }
  if ($globallink->status != GLOBALLINK_STATUS_TRANSLATION_ERROR) {
    $globallink->status = GLOBALLINK_STATUS_TRANSLATION_IMPORTED;
  }
  return;
}
function globallink_get_all_translatable_cp_types_and_names() {
  $product_info = entity_get_info('commerce_product');
  $arr = array();
  if (isset($product_info) && isset($product_info['bundles'])) {
    $bundles = $product_info['bundles'];
    foreach ($bundles as $key => $bundle) {
      $arr['cp:' . $key] = $bundle['label'];
    }
    asort($arr);
  }
  return $arr;
}
function globallink_get_configured_fields_for_cp($cp_type) {
  $result = db_select('globallink_field_config', 'tfg')
    ->fields('tfg')
    ->condition('content_type', 'cp:' . $cp_type, '=')
    ->condition('entity_type', 'commerce_product', '=')
    ->execute();
  $arr = array();
  foreach ($result as $row) {
    $arr[$row->field_name] = $row;
  }
  return $arr;
}
function globallink_commerce_get_info($pid) {
  $results = db_select(GLOBALLINK_ENTITY_TYPE_COM, 'cp')
    ->fields('cp')
    ->condition('product_id', $pid, '=')
    ->execute();
  $arr = new stdClass();
  foreach ($results as $result) {
    $arr = $result;
  }
  return $arr;
}
function globallink_cp_get_active_submission_by_id($id) {
  $query = db_select('globallink_document', 'gd');
  $query
    ->join('globallink_submission', 'gs', 'gd.submission_rid = gs.rid');
  $query
    ->condition('gd.object_id', $id, '=');
  $query
    ->condition('gd.entity_type', GLOBALLINK_ENTITY_TYPE_COM, '=');
  $or = db_or();
  $or
    ->condition('gd.target_status', GLOBALLINK_STATUS_TRANSLATION_SENT, '=');
  $or
    ->condition('gd.target_status', GLOBALLINK_STATUS_TRANSLATION_COMPLETED, '=');
  $or
    ->condition('gd.target_status', GLOBALLINK_STATUS_TRANSLATION_ERROR, '=');
  $query
    ->condition($or);
  $query
    ->fields('gd');
  $query
    ->fields('gs', array(
    'submission',
    'source_lang_code',
    'source_lang_name',
    'sub_target_lang_code',
    'sub_target_lang_name',
  ));
  $results = $query
    ->execute()
    ->fetchAll();
  return $results;
}
function globallink_commerce_traverse_fields_and_field_collections($entity_type, $content_type, $parent_fc, $bundle, $entity_id, $items, $field, $dom, $root, $source_node, $target_arr, $langcode = LANGUAGE_NONE) {
  if (!$items) {
    return;
  }
  $field_def = field_read_field($field);
  $max_length = '0';
  if (isset($field_def['settings']) && isset($field_def['settings']['max_length'])) {
    $max_length = $field_def['settings']['max_length'];
  }
  switch ($field_def['type']) {
    case 'list_boolean':
    case 'file':
    case 'taxonomy_term_reference':
    case 'field_collection':
      if (!module_exists('field_collection')) {
        break;
      }

      // Field Collection field, read the entity id from item and load
      // Entity object and then do recursion for nested field collections.
      foreach ($items as $entity_id_arr) {
        if (!isset($entity_id_arr['value'])) {
          continue;
        }
        $fc_entity_id = $entity_id_arr['value'];
        $field_collection_item_entity_arr = array();
        if (isset($entity_id_arr['revision_id'])) {
          $field_collection_item_entity_arr = entity_load('field_collection_item', array(
            $fc_entity_id,
          ), array(
            'revision_id' => $entity_id_arr['revision_id'],
          ));
        }
        else {
          $field_collection_item_entity_arr = entity_load('field_collection_item', array(
            $fc_entity_id,
          ));
        }
        if (!$field_collection_item_entity_arr || !is_array($field_collection_item_entity_arr) || sizeof($field_collection_item_entity_arr) < 1) {
          continue;
        }
        $field_collection_item_entity = $field_collection_item_entity_arr[$fc_entity_id];
        $field_collection_name = $field_collection_item_entity->field_name;
        $field_collection_item_array = get_object_vars($field_collection_item_entity);
        $arr = array_keys($field_collection_item_array);
        foreach ($arr as $key) {

          // Check if this key exists; If true then read this.
          $fc_field_def = field_read_field($key);
          if ($fc_field_def && !empty($fc_field_def) && isset($fc_field_def['type'])) {
            if ($fc_field_def['type'] != 'list_boolean' && $fc_field_def['type'] != 'file' && $fc_field_def['type'] != 'taxonomy_term_reference') {
              $fc_item = field_get_items('field_collection_item', $field_collection_item_entity, $key);
              if ($fc_item) {
                globallink_commerce_traverse_fields_and_field_collections('field_collection_item', $content_type, $parent_fc, $field_collection_name, $fc_entity_id, $fc_item, $key, $dom, $root, $source_node, $target_arr);
              }
            }
          }
        }
      }
      break;
    default:
      if (!globallink_is_field_configured_for_translation($entity_type, $bundle, $field, 'cp:' . $content_type)) {
        break;
      }

      // Regular Text Field, get the content directly from items array
      foreach ($items as $delta => $item) {
        if (isset($item['value']) && is_string($item['value'])) {
          $f_label = field_info_instance($entity_type, $field, $bundle);
          $f_value = $item['value'];
          $f_format = isset($item['format']) && !is_null($item['format']) ? $item['format'] : '';
          globallink_insert_child_element($dom, $root, 'field', $f_value, array(
            'entity_type' => $entity_type,
            'content_type' => $content_type,
            'parent_fc' => $parent_fc,
            'bundle' => $bundle,
            'entity_id' => $entity_id,
            'field_name' => $field,
            'label' => $f_label['label'],
            'delta' => $delta,
            'format' => $f_format,
            'langcode' => $langcode,
            'max_length' => $max_length,
          ));
          $field_info_all = field_info_field($field);
          $sum_field = '';
          if ($field_info_all['type'] == 'text_with_summary' && globallink_is_field_configured_for_translation($entity_type, $bundle, $field . '@summary', $content_type)) {
            $sum_field = $field . '@summary';
          }
          if (isset($item['summary']) && is_string($item['summary']) && !empty($sum_field)) {
            if (globallink_is_field_configured_for_translation($entity_type, $bundle, $field, $content_type)) {
              $f_label = $field . ' Summary';
              $f_value = $item['summary'];
              $f_format = isset($item['format']) && !is_null($item['format']) ? $item['format'] : '';
              globallink_insert_child_element($dom, $root, 'field', $f_value, array(
                'entity_type' => $entity_type,
                'content_type' => $content_type,
                'parent_fc' => $parent_fc,
                'bundle' => $bundle,
                'entity_id' => $entity_id,
                'field_name' => $sum_field,
                'label' => $f_label,
                'delta' => $delta,
                'format' => $f_format,
                'langcode' => $langcode,
                'max_length' => $max_length,
              ));
            }
          }
        }
        elseif ($field_def['type'] == 'link_field' && isset($item['title']) && is_string($item['title'])) {
          $f_label = field_info_instance($entity_type, $field, $bundle);
          $f_value = $item['title'];
          $f_format = isset($item['format']) && !is_null($item['format']) ? $item['format'] : '';
          globallink_insert_child_element($dom, $root, 'field', $f_value, array(
            'entity_type' => $entity_type,
            'content_type' => $content_type,
            'parent_fc' => $parent_fc,
            'bundle' => $bundle,
            'entity_id' => $entity_id,
            'field_name' => $field,
            'label' => $f_label['label'],
            'delta' => $delta,
            'format' => $f_format,
            'langcode' => $langcode,
            'max_length' => $max_length,
          ));
        }
      }
  }
}
function globallink_commerce_save_field_collections($entity, $translated_arr, $target_locale) {
  $field_arr = field_info_instances('commerce_product', $entity->type);
  $keys = array_keys($field_arr);
  foreach ($keys as $field) {
    $language = field_language('commerce_product', $entity, $field, NULL);
    $field_values = field_get_items('commerce_product', $entity, $field, $language);
    if (isset($translated_arr['field_collection'][$field])) {
      foreach ($field_values as $entity_id_arr) {
        if (isset($entity_id_arr['value'])) {
          $fc_entity_id = $entity_id_arr['value'];
          globallink_commerce_save_field_collections_recursively('commerce_product', $entity, $fc_entity_id, $translated_arr['field_collection'][$field], $target_locale);
        }
      }
    }
  }
}

/**
 * Saves field collections recursively.
 *
 * @param string $entity_type
 *   The type of entity.
 * @param string $host_entity
 *   The host entity.
 * @param string $fc_entity_id
 *   The id of the field collection.
 * @param array $translated_fc_arr
 *   The array of translated field collections.
 */
function globallink_commerce_save_field_collections_recursively($entity_type, $host_entity, $fc_entity_id, $translated_fc_arr, $target_locale) {
  $field_collection_item_entity = entity_load_unchanged('field_collection_item', $fc_entity_id);
  if (!$field_collection_item_entity) {
    return;
  }
  $field_collection_name = $field_collection_item_entity->field_name;
  $field_collection_item_array = get_object_vars($field_collection_item_entity);
  $arr = array_keys($field_collection_item_array);
  $new_field_collection_arr = array(
    'field_name' => $field_collection_name,
  );
  foreach ($arr as $key) {

    // Check if this key exists; If true then read this.
    $fc_field_def = field_read_field($key);
    if (!$fc_field_def || empty($fc_field_def) || !isset($fc_field_def['type'])) {
      continue;
    }
    switch ($fc_field_def['type']) {
      case 'list_boolean':
      case 'file':
      case 'taxonomy_term_reference':
        continue 2;
      case 'field_collection':
        $lang = key($field_collection_item_array[$key]);
        if (isset($field_collection_item_array[$key]) && isset($field_collection_item_array[$key][$lang])) {
          $field_data_arr = $field_collection_item_array[$key][$lang];
          $new_field_collection_arr[$key][$target_locale] = $field_data_arr;
        }
        break;
      default:
        $lang = key($field_collection_item_array[$key]);
        if (!isset($field_collection_item_array[$key]) || !isset($field_collection_item_array[$key][$lang])) {
          continue 2;
        }
        $field_data_arr = $field_collection_item_array[$key][$lang];
        foreach ($field_data_arr as $delta => $field_data) {
          if (isset($translated_fc_arr[$field_collection_name][$fc_entity_id][$key][LANGUAGE_NONE][$delta])) {
            $gl_obj = $translated_fc_arr[$field_collection_name][$fc_entity_id][$key][LANGUAGE_NONE][$delta];
            if (is_object($gl_obj)) {
              $translated_content = $gl_obj->translatedContent;
            }
            else {
              $translated_content = $gl_obj;
            }
            if (isset($field_data['format'])) {
              $format = $field_data['format'];
              $new_field_collection_arr[$key][$target_locale][$delta] = array(
                'value' => $translated_content,
                'format' => $format,
              );
            }
            else {
              $new_field_collection_arr[$key][$target_locale][$delta] = array(
                'value' => $translated_content,
              );
            }
          }
          else {
            $new_field_collection_arr[$key][$target_locale][$delta] = $field_data;
          }
        }
    }
  }
  if ($entity_type != 'node') {
    $host_entity->tpt_skip = TRUE;
  }
  $field_collection_item = entity_create('field_collection_item', $new_field_collection_arr);

  // Create new field collection item.
  $field_collection_item
    ->setHostEntity($entity_type, $host_entity, $target_locale);

  // Attach it to the commerce product.
  $field_collection_item
    ->save(TRUE);

  // Save field-collection item.
  $host_entity->{$new_field_collection_arr['field_name']}[$target_locale][0] = array(
    'value' => $field_collection_item->item_id,
    'revision_id' => $field_collection_item->revision_id,
  );
  entity_save($entity_type, $host_entity);
  field_attach_presave($entity_type, $host_entity);
  field_attach_update($entity_type, $host_entity);

  // Now set the child FC if any
  foreach ($arr as $key) {

    // Check if this key exists; if true then read this.
    $fc_field_def = field_read_field($key);
    if ($fc_field_def && !empty($fc_field_def) && isset($fc_field_def['type'])) {
      if ($fc_field_def['type'] == 'field_collection') {
        $items = field_get_items('field_collection_item', $field_collection_item_entity, $key);
        if ($items) {
          foreach ($items as $entity_id_arr) {
            if (isset($entity_id_arr['value'])) {
              $fc_entity_id = $entity_id_arr['value'];
              globallink_commerce_save_field_collections_recursively('field_collection_item', $field_collection_item, $fc_entity_id, $translated_fc_arr, $target_locale);
            }
          }
        }
      }
    }
  }
}