You are here

function farm_map_kml_action in farmOS 7

Action function for farm_map_kml_action.

Creates a KML file containing shapes from selected entities.

Parameters

array $entities: An array of entities.

array $context: Array with parameters for this action.

File

modules/farm/farm_map/farm_map_kml/farm_map_kml.module, line 60
Farm map KML.

Code

function farm_map_kml_action(array $entities, $context = array()) {

  // Iterate through the entities to generate placemarks.
  $placemarks = array();
  foreach ($entities as $entity) {

    // Ask modules to extract geometries from this entity.
    $geometries = farm_map_entity_geometries($context['entity_type'], $entity);

    // Get the entity id and label.
    list($id, $rid, $bundle) = entity_extract_ids($context['entity_type'], $entity);
    $label = entity_label($context['entity_type'], $entity);

    // Create a placemark for each geometry.
    foreach ($geometries as $key => $geometry) {

      // Create a placemark.
      $placemark = array(
        'pid' => $id,
        // We use htmlspecialchars() so that apostrophes are not escaped.
        'name' => htmlspecialchars($label),
        'geometry' => $geometry,
      );

      // If a non-numeric key is set, tag the ID and label with it.
      if (!is_numeric($key)) {
        $placemark['pid'] .= '-' . check_plain($key);
        $placemark['name'] .= ' (' . check_plain($key) . ')';
      }

      // If this is an area entity (taxonomy_term), add the description.
      if ($context['entity_type'] == 'taxonomy_term' && $entity->vocabulary_machine_name == 'farm_areas') {
        if (!empty($entity->description)) {
          $placemark['description'] = check_plain($entity->description);
        }
      }

      // Add the placemark to the list.
      $placemarks[] = $placemark;
    }
  }

  // If there are no placemarks, bail with a warning.
  if (empty($placemarks)) {
    drupal_set_message(t('No placemarks were found.'), 'warning');
    return;
  }

  // Create KML output.
  $kml = theme('farm_map_kml', array(
    'placemarks' => $placemarks,
  ));

  // Ensure that a directory exists to store the KML file in.
  $scheme = variable_get('file_default_scheme', 'public');
  $directory = $scheme . '://kml';
  file_prepare_directory($directory, FILE_CREATE_DIRECTORY);

  // Create the temporary KML file.
  $filename = 'kml_export-' . date('c') . '.kml';
  $destination = $directory . '/' . $filename;
  $file = file_save_data($kml, $destination);

  // Make the file temporary.
  $file->status = 0;
  file_save($file);

  // Show a link to the file.
  $message = 'KML file created: <a href="!path">%filename</a>';
  $args = array(
    '!path' => file_create_url($file->uri),
    '%filename' => $file->filename,
  );
  drupal_set_message(t($message, $args));
}