<?php

/**
 * @file
 *
 */

function incubator_gallery_token_info() {
  $return = array(
    'tokens' => array()
  );
  
  $all_fields = field_info_field_map();
  if (!empty($all_fields['field_gallery_images'])) {
    $entity_types = array_keys($all_fields['field_gallery_images']['bundles']);
    foreach ($entity_types as $type) {
      $return['tokens'][$type]['field_gallery_images'] = array(
        'name' => 'Gallery images',
        'description' => t('Images in a photo gallery.'),
        'type' => 'array',
      );
    }
  }
  
  return $return;
}

function incubator_gallery_tokens($type, $tokens, $data = array(), $options = array()) {
  $replacements = array();
  
  if ($type == 'entity' && !empty($data['entity']) && !empty($data['entity']->field_gallery_images)) {
    foreach ($tokens as $name => $original) {
      if ($name == 'field_gallery_images') {
        return _incubator_social_field_tokens($type, $tokens, $data, $options);
      }
      elseif (stripos($name, 'field_gallery_images') === 0) {
        $langcode = isset($options['language']) ? $options['language']->language : 'und';
        $files = !empty($data['entity']->field_gallery_images[$langcode]) ? $data['entity']->field_gallery_images[$langcode] : $data['entity']->field_gallery_images['und'];
        foreach ($files as $i => $file) {
          $images[$i] = file_create_url($file['uri']);
        }
        $replacements += token_generate('array', token_find_with_prefix($tokens, 'field_gallery_images'), array('array' => $images), $options);
      }
    }
    return $replacements;
  }
}
