geocoder.widget.inc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. <?php
  2. /**
  3. * Implements hook_field_widget_info().
  4. */
  5. function geocoder_field_widget_info() {
  6. return array(
  7. 'geocoder' => array(
  8. 'label' => t('Geocode from another field'),
  9. 'field types' => array('geofield', 'geolocation_latlng', 'location'),
  10. 'behaviors' => array(
  11. 'multiple values' => FIELD_BEHAVIOR_CUSTOM,
  12. 'default value' => FIELD_BEHAVIOR_NONE,
  13. ),
  14. ),
  15. );
  16. }
  17. /**
  18. * Implements field_widget_settings_form().
  19. */
  20. function geocoder_field_widget_settings_form($this_field, $instance) {
  21. $settings = $instance['widget']['settings'];
  22. $entity_fields = field_info_instances($instance['entity_type'], $instance['bundle']);
  23. $all_fields = field_info_fields();
  24. $supported_field_types = geocoder_supported_field_types();
  25. $processors = geocoder_handler_info();
  26. $handlers_by_type = array();
  27. $field_types = array();
  28. $valid_fields = array();
  29. $available_handlers = array();
  30. // Add in the title/name
  31. //@@TODO Do this programatically by getting entity_info
  32. switch ($instance['entity_type']) {
  33. case 'node':
  34. $all_fields['title'] = array(
  35. 'field_name' => 'title',
  36. 'type' => 'text',
  37. );
  38. $entity_fields['title']['label'] = t('Title');
  39. break;
  40. case 'taxonomy_term':
  41. $all_fields['name'] = array(
  42. 'field_name' => 'name',
  43. 'type' => 'text',
  44. );
  45. $entity_fields['name']['label'] = t('Name');
  46. break;
  47. }
  48. // Get a list of all valid fields that we both support and are part of this entity
  49. foreach ($all_fields as $field) {
  50. if (array_key_exists($field['field_name'], $entity_fields)) {
  51. if (in_array($field['type'], array_keys($supported_field_types)) && ($field['field_name'] != $this_field['field_name'])) {
  52. $valid_fields[$field['field_name']] = $entity_fields[$field['field_name']]['label'];
  53. foreach ($supported_field_types[$field['type']] as $handler) {
  54. $available_handlers[$handler] = $processors[$handler]['title'];
  55. $handlers_by_type[$field['type']][] = $handler;
  56. $field_types[$field['field_name']] = $field['type'];
  57. }
  58. }
  59. }
  60. }
  61. $form['geocoder_field'] = array(
  62. '#type' => 'select',
  63. '#title' => t('Geocode from field'),
  64. '#default_value' => isset($settings['geocoder_field']) ? $settings['geocoder_field']: '',
  65. '#options' => $valid_fields,
  66. '#description' => t('Select which field you would like to geocode from.'),
  67. '#required' => TRUE,
  68. '#attributes' => array('onchange' => 'geocoder_admin_field_selected();'),
  69. );
  70. $form['geocoder_handler'] = array(
  71. '#type' => 'select',
  72. '#title' => t('Geocoder'),
  73. '#prefix' => '<div id="geocoder-handler-div">',
  74. '#suffix' => '</div>',
  75. '#default_value' => isset($settings['geocoder_handler']) ? $settings['geocoder_handler']: '',
  76. '#options' => $available_handlers,
  77. '#description' => t('Select which type of geocoding handler you would like to use'),
  78. '#attributes' => array('onchange' => 'geocoder_admin_handler_selected();'),
  79. '#required' => TRUE,
  80. );
  81. $form['handler_settings'] = array(
  82. '#tree' => TRUE,
  83. );
  84. // Add the handler settings forms
  85. foreach ($processors as $handler_id => $handler) {
  86. if (isset($handler['settings_callback']) || isset($handler['terms_of_service'])) {
  87. $default_values = isset($settings['handler_settings'][$handler_id]) ? $settings['handler_settings'][$handler_id] : array();
  88. $form['handler_settings'][$handler_id] = array();
  89. $form['handler_settings'][$handler_id]['#type'] = 'fieldset';
  90. $form['handler_settings'][$handler_id]['#attributes'] = array('class' => array('geocoder-handler-setting', 'geocoder-handler-setting-' . $handler_id));
  91. $form['handler_settings'][$handler_id]['#title'] = $handler['title'] . ' Settings';
  92. if (isset($handler['terms_of_service'])) {
  93. $form['handler_settings'][$handler_id]['tos'] = array(
  94. '#type' => 'item',
  95. '#markup' => t('This handler has terms of service. Click the following link to learn more.') . ' ' . l($handler['terms_of_service'], $handler['terms_of_service']),
  96. );
  97. }
  98. if (isset($handler['settings_callback'])) {
  99. $settings_callback = $handler['settings_callback'];
  100. $form['handler_settings'][$handler_id] = array_merge($form['handler_settings'][$handler_id], $settings_callback($default_values));
  101. }
  102. }
  103. }
  104. $form['delta_handling'] = array(
  105. '#type' => 'select',
  106. '#title' => t('Multi-value input handling'),
  107. '#description' => t('Should geometries from multiple inputs be: <ul><li>Matched with each input (e.g. One POINT for each address field)</li><li>Aggregated into a single MULTIPOINT geofield (e.g. One MULTIPOINT polygon from multiple address fields)</li><li>Broken up into multiple geometries (e.g. One MULTIPOINT to multiple POINTs.)</li></ul>'),
  108. '#default_value' => isset($settings['delta_handling']) ? $settings['delta_handling']: 'default',
  109. '#options' => array(
  110. 'default' => 'Match Multiples (default)',
  111. 'm_to_s' => 'Multiple to Single',
  112. 's_to_m' => 'Single to Multiple',
  113. 'c_to_s' => 'Concatenate to Single',
  114. 'c_to_m' => 'Concatenate to Multiple',
  115. ),
  116. '#required' => TRUE,
  117. );
  118. drupal_add_js(array('geocoder_widget_settings' => array('handlers' => $handlers_by_type, 'types' => $field_types)), 'setting');
  119. drupal_add_js(drupal_get_path('module', 'geocoder') . '/geocoder.admin.js', 'file');
  120. return $form;
  121. }
  122. /**
  123. * Implements hook_field_attach_presave().
  124. *
  125. * Geocoding for the geocoder widget is done here to ensure that only validated
  126. * and fully processed fields values are accessed.
  127. */
  128. function geocoder_field_attach_presave($entity_type, $entity) {
  129. // Loop over any geofield using our geocode widget
  130. $entity_info = entity_get_info($entity_type);
  131. $bundle_name = empty($entity_info['entity keys']['bundle']) ? $entity_type : $entity->{$entity_info['entity keys']['bundle']};
  132. foreach (field_info_instances($entity_type, $bundle_name) as $field_instance) {
  133. if ($field_instance['widget']['type'] === 'geocoder') {
  134. // Required settings
  135. if (isset($field_instance['widget']['settings']['geocoder_handler']) && isset($field_instance['widget']['settings']['geocoder_field'])) {
  136. $handler = geocoder_get_handler($field_instance['widget']['settings']['geocoder_handler']);
  137. $field_name = is_array($field_instance['widget']['settings']['geocoder_field']) ? reset($field_instance['widget']['settings']['geocoder_field']) : $field_instance['widget']['settings']['geocoder_field'];
  138. $target_info = field_info_field($field_instance['field_name']);
  139. $target_type = $target_info['type'];
  140. // Get the handler-specific-settings
  141. if (isset($field_instance['widget']['settings']['handler_settings'][$handler['name']])) {
  142. $handler_settings = $field_instance['widget']['settings']['handler_settings'][$handler['name']];
  143. }
  144. // Determine how we deal with deltas (multi-value fields)
  145. if (empty($field_instance['widget']['settings']['delta_handling'])) {
  146. $delta_handling = 'default';
  147. }
  148. else {
  149. $delta_handling = $field_instance['widget']['settings']['delta_handling'];
  150. }
  151. list($field_info, $items) = geocoder_widget_get_field_data($entity_type, $entity, $field_name, $delta_handling);
  152. if (is_array($items) && count($items)) {
  153. $values = array();
  154. // Geocode geometries
  155. $geometries = array();
  156. foreach ($items as $delta => $item) {
  157. // Geocode any value from our source field.
  158. try {
  159. if (isset($handler_settings)) {
  160. $geometry = call_user_func($handler['field_callback'], $field_info, $item, $handler_settings);
  161. }
  162. else {
  163. $geometry = call_user_func($handler['field_callback'], $field_info, $item);
  164. }
  165. if ($geometry instanceof Geometry) {
  166. $geometries[] = $geometry;
  167. }
  168. }
  169. catch (Exception $e) {
  170. drupal_set_message($e->getMessage(), 'error');
  171. }
  172. }
  173. if (empty($geometries)) $values = array(NULL);
  174. else {
  175. // Resolve multiple-values - get back values from our delta-resolver
  176. $values = geocoder_widget_resolve_deltas($geometries, $delta_handling, $target_type);
  177. }
  178. // Set the values - geofields do not support languages
  179. $entity->{$field_instance['field_name']}[LANGUAGE_NONE] = $values;
  180. }
  181. }
  182. }
  183. }
  184. }
  185. /**
  186. * Get field items and info
  187. *
  188. * We always pass the full field-item array (with all columns) to the handler, but there is some preprocessing
  189. * that we need to do for the special case of entity-labels and multi-field contactenation
  190. * For these two special cases we "mock-up" a text-field and pass it back for geocoding
  191. */
  192. function geocoder_widget_get_field_data($entity_type, $entity, $field_name, $delta_handling) {
  193. $entity_info = entity_get_info($entity_type);
  194. // First check to see if it's an entity field
  195. if (in_array($field_name, $entity_info['entity keys'])) {
  196. $items[]['value'] = $entity->$field_name;
  197. $field_info = array(
  198. 'type' => 'text',
  199. 'entity key' => TRUE,
  200. );
  201. }
  202. else {
  203. // It's a normal field-api field
  204. $field_info = field_info_field($field_name);
  205. $langcode = field_language($entity_type, $entity, $field_name);
  206. $items = field_get_items($entity_type, $entity, $field_name, $langcode);
  207. }
  208. // Check if we should concatenate
  209. if ($delta_handling == 'c_to_s' || $delta_handling == 'c_to_m') {
  210. $support_concat = array('text', 'text_long', 'computed', 'text_with_summary', 'computed');
  211. if (!in_array($field_info['type'], $support_concat)) {
  212. drupal_set_message(t('Trying to concatenate a non-text field'));
  213. return;
  214. }
  215. $concat = '';
  216. foreach ($items as $item) {
  217. $concat .= trim($item['value']) . ', ';
  218. }
  219. $concat = trim($concat, ', ');
  220. $items = array(array('value' => $concat));
  221. $field_info = array(
  222. 'type' => 'text',
  223. 'concated' => TRUE,
  224. );
  225. }
  226. return array(
  227. $field_info,
  228. $items,
  229. );
  230. }
  231. /**
  232. * Geocder Widget - Resolve Deltas
  233. *
  234. * Given a list of geometries, and user configuration on how to handle deltas,
  235. * we created a list of items to be inserted into the fields.
  236. */
  237. function geocoder_widget_resolve_deltas($geometries, $delta_handling = 'default', $field_type) {
  238. $values = array();
  239. // Default delta handling: just pass one delta to the next
  240. if ($delta_handling == 'default') {
  241. foreach ($geometries as $geometry) {
  242. $values[] = geocoder_widget_values_from_geometry($geometry, $field_type);
  243. }
  244. }
  245. // Single-to-multiple handling - if we can, explode out the component geometries
  246. if ($delta_handling == 's_to_m' || $delta_handling = 'c_to_m') {
  247. $type = $geometries[0]->geometryType();
  248. if (in_array($type, array('MultiPoint', 'MultiLineString', 'MultiPolygon', 'GeometryCollection'))) {
  249. $components = $geometries[0]->getComponents();
  250. foreach ($components as $component) {
  251. $values[] = geocoder_widget_values_from_geometry($component, $field_type);
  252. }
  253. }
  254. else {
  255. $values[] = geocoder_widget_values_from_geometry($geometries[0], $field_type);
  256. }
  257. }
  258. // For multiple-to-single handling, run it though geometryReduce
  259. if ($delta_handling == 'm_to_s' || $delta_handling = 'c_to_s') {
  260. $reduced_geom = geoPHP::geometryReduce($geometries);
  261. $values[] = geocoder_widget_values_from_geometry($reduced_geom, $field_type);
  262. }
  263. return $values;
  264. }
  265. /**
  266. * Geocder Widget - Field values from geometry
  267. *
  268. * Given a geometry and the field type, return back a values array for that field.
  269. * The passed back array represents a single delta.
  270. */
  271. function geocoder_widget_values_from_geometry($geometry, $field_type) {
  272. if ($field_type == 'geofield') return geofield_get_values_from_geometry($geometry);
  273. if ($field_type == 'geolocation_latlng') {
  274. $centroid = $geometry->centroid();
  275. $lat = $centroid->y();
  276. $lng = $centroid->x();
  277. return array(
  278. 'lat' => $lat,
  279. 'lng' => $lng,
  280. 'lat_sin' => sin(deg2rad($lat)),
  281. 'lat_cos' => cos(deg2rad($lng)),
  282. 'lng_rad' => deg2rad($lng),
  283. );
  284. }
  285. if ($field_type == 'location') {
  286. $centroid = $geometry->centroid();
  287. return array(
  288. 'latitude' => $centroid->y(),
  289. 'longitude' => $centroid->x(),
  290. 'source' => 2,
  291. );
  292. }
  293. }
  294. /**
  295. * Geocoder Widget - Parse an address field
  296. */
  297. function geocoder_widget_parse_addressfield($field_item) {
  298. $address = '';
  299. if (!empty($field_item['premise'])) $address .= $field_item['premise'] . ',';
  300. if (!empty($field_item['thoroughfare'])) $address .= $field_item['thoroughfare'] . ',';
  301. if (!empty($field_item['locality'])) $address .= $field_item['locality'] . ',';
  302. if (!empty($field_item['administrative_area'])) $address .= $field_item['administrative_area'] . ',';
  303. if (!empty($field_item['sub_administrative_area'])) $address .= $field_item['sub_administrative_area'] . ',';
  304. if (!empty($field_item['country'])) $address .= $field_item['country'] . ',';
  305. if (!empty($field_item['postal_code'])) $address .= $field_item['postal_code'] . ',';
  306. $address = rtrim($address, ', ');
  307. return $address;
  308. }