<?php

/**
 * @file
 * Export / import functions.
 *
 * The file is not included by default. The import / export process is run using
 * drush php-eval.
 */

/**
 * Export objects the fgcf_data_import table.
 *
 * Objects must be exported in the order in which they need to be imported,
 * with respect to dependencies order (terms, files, noderef fields...).
 */
function fgcf_export() {
  // Export terms.
  foreach (taxonomy_get_vocabularies() as $vocab) {
    $tree = taxonomy_get_tree($vocab->vid);
    foreach ($tree as $term) {
      fgcf_export_term($term->tid);
    }
  }

  // Export files.
  $result = db_query("SELECT fid FROM {files}");
  while ($row = db_fetch_array($result)) {
    fgcf_export_file($row['fid']);
  }

  // Export nodes.
  $types = array('fgcf_thematique', 'fgcf_prestataire', 'fgcf_fiche');
  foreach ($types as $type) {
    $result = db_query("SELECT nid FROM {node} WHERE type='%s'", $type);
    while ($row = db_fetch_array($result)) {
      fgcf_export_node($row['nid']);
    }
  }
}

/**
 * Export a term in the fgcf_data_import table.
 */
function fgcf_export_term($tid) {
  if ($term = taxonomy_get_term($tid)) {
    // Add parenting information.
    $term->parent = 0;
    if ($parents = taxonomy_get_parents($tid)) {
      $parent = current($parents);
      $term->parent = $parent->tid;
    }
    db_query("INSERT INTO {fgcf_data_import} (drupal_id, data, type) VALUES (%d, '%s', '%s')", $term->tid, serialize($term), 'term');
  }
}

/**
 * Export a file in the fgcf_data_import table.
 */
function fgcf_export_file($fid) {
  if ($file = (object) field_file_load($fid)) {
    db_query("INSERT INTO {fgcf_data_import} (drupal_id, data, type) VALUES (%d, '%s', '%s')", $file->fid, serialize($file), 'file');
  }
}

/**
 * Export a node in the fgcf_data_import table.
 */
function fgcf_export_node($nid) {
  if ($node = node_load($nid)) {
    db_query("INSERT INTO {fgcf_data_import} (drupal_id, data, type) VALUES (%d, '%s', '%s')", $node->nid, serialize($node), 'node');
  }
}

function fgcf_import() {
  $result = db_query("SELECT * FROM {fgcf_data_import} ORDER BY id ASC");
  while ($row = db_fetch_object($result)) {
    $function = 'fgcf_import_' .$row->type;
    $data = unserialize($row->data);
    $function($data);

    db_query("DELETE FROM {fgcf_data_import} WHERE id=%d", $row->id);
  }
}

/**
 * Import one term.
 */
function fgcf_import_term($term) {
  // Replace vocabulary.
  // Those mappings have been initialized manually after the creation of the
  // vocabs.
  $term->vid = fgcf_map_get('vocabulary', $term->vid);

  // Replace parent.
  if ($term->parent) {
    $term->parent = fgcf_map_get('term', $term->parent);
  }

  $old_id = $term->tid;
  unset($term->tid);
  // taxonomy_save_term() takes an array of 'form values'...
  $term = (array) $term;
  taxonomy_save_term($term);
  $term = (object) $term;

  // Save mapping.
  fgcf_map_set('term', $old_id, $term->tid);

  return $term;
}

/**
 * Import one file.
 */
function fgcf_import_file($file) {
  // Replace filepath.
  $file->filepath = preg_replace('|^sites/fg.local/files/|', file_directory_path() .'/', $file->filepath);

  $old_id = $file->fid;
  unset($file->fid);
  drupal_write_record('files', $file);

  // Save mapping.
  fgcf_map_set('file', $old_id, $file->fid);

  return $term;
}

/**
 * Import one node.
 */
function fgcf_import_node($node) {
  switch ($node->type) {
    case 'fgcf_thematique':
      // Translate NAT associations.
      if (!empty($node->nat)) {
        $old_nat_term = current($node->nat);
        $nat_tid = fgcf_map_get('term', $old_nat_term->tid);
        $nat_term = taxonomy_get_term($nat_tid);
        // Just replace the $node property (probably useless), the association
        // will be saved after node creation.
        $node->nat = array($nat_term->tid => $nat_term);
      }
      // Translate file
      if (!empty($node->field_fgcf_thematique_logo)) {
        foreach ($node->field_fgcf_thematique_logo as &$item) {
          if (!empty($item['fid'])) {
            $item = array('fid' => fgcf_map_get('file', $item['fid']));
          }
        }
      }
      break;

    case 'fgcf_prestataire':
      // Translate file
      if (!empty($node->field_fgcf_prestataire_logo)) {
        foreach ($node->field_fgcf_prestataire_logo as &$item) {
          if (!empty($item['fid'])) {
            $item = array('fid' => fgcf_map_get('file', $item['fid']));
          }
        }
      }
    case 'fgcf_fiche':
      // Translate nodereference
      if (!empty($node->field_fgcf_fiche_organisme)) {
        foreach ($node->field_fgcf_fiche_organisme as &$item) {
          if (!empty($item['nid'])) {
            $item = array('nid' => fgcf_map_get('node', $item['nid']));
          }
        }
      }
      // Translate taxo fields.
      $fields = array('field_fgcf_fiche_format', 'field_fgcf_fiche_supports', 'field_fgcf_fiche_sanction', 'field_fgcf_fiche_public');
      foreach ($fields as $field) {
        if (!empty($node->$field)) {
          foreach ($node->$field as &$item) {
            if (!empty($item['value'])) {
              $item = array('value' => fgcf_map_get('term', $item['value']));
            }
          }
        }
      }
      // Translate regular taxonomy.
      if (!empty($node->taxonomy)) {
        $terms = array();
        foreach ($node->taxonomy as $old_term) {
          $tid = fgcf_map_get('term', $old_term->tid);
          $term = taxonomy_get_term($tid);
          $terms[$tid] = $term;
        }
        $node->taxonomy = $terms;
      }
      break;
  }
  $old_id = $node->nid;
  unset($node->nid, $node->vid);
  node_save($node);

  // Record NAT association if needed.
  if (isset($nat_term)) {
    // Pas de drupal_write_record() : NAT est désactivé pour éviter qu'il crée
    // un terme.
    db_query('INSERT INTO {nat} (nid, tid, vid) VALUES (%d, %d, %d)', $node->nid, $nat_term->tid, $nat_term->vid);
  }

  // Save mapping.
  fgcf_map_set('node', $old_id, $node->nid);

  return $node;
}

/**
 * Stores a mapping for imported data.
 *
 * @param $type
 *   A string: 'vocabulary', 'term', 'node', 'file'
 * @param $old_id
 *   The id of the original object.
 * @param $new_id
 *   The id of the corresponding imported object.
 */
function fgcf_map_set($type, $old_id, $new_id) {
  $map = variable_get('fgcf_map', array());

  if (is_null($new_id)) {
    // Read.
    if (isset($map[$type][$old_id])) {
      return $map[$type][$old_id];
    }
    else {
      // dsm("unknown mapping: $type $old_id");
    }
  }
  else {
    // Write.
    $map[$type][$old_id] = $new_id;
    variable_set('fgcf_map', $map);
  }
}

/**
 * Raads a mapping for imported data.
 *
 * @param $type
 *   A string: 'vocabulary', 'term', 'node', 'file'
 * @param $old_id
 *   The id of the original object.
 *
 * @return
 *   The id of the corresponding imported object, or NULL if unknown.
 */
function fgcf_map_get($type, $old_id) {
  return fgcf_map_set($type, $old_id, NULL);
}