summaryrefslogtreecommitdiffstats
path: root/contrib/location_autofill/la.module
blob: dd8bbfbc317f8907ae40c6ae370ae01328fe35e6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
<?php

/**
 * @file
 * Location autofill routines.
 */

/**
 * Implements hook_menu().
 */
function la_menu() {
  $items['admin/config/services/la'] = array(
    'title' => 'Autofill empty locations',
    'description' => 'Find and fill all empty locations with latitude and longtitude data',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('la_admin'),
    'access arguments' => array('administer site configuration'),
    'file' => 'la.admin.inc',
  );

  return $items;
}

/**
 * Implements hook_cron().
 */
function la_cron() {

}


/**
 * Get information about non filled locations.
 */
function la_info() {
  $empty_locations = db_select('location', 'l')
    ->fields('l', array('lid'))
    ->condition('latitude', '0.000000')
    ->condition('longitude', '0.000000')
    ->execute()
    ->rowCount();
  if ($empty_locations > 0) {
    drupal_set_message(
      t(
        'There are empty locations (latitude and longitude) within your database: !count',
        array('!count' => $empty_locations)
      ),
      'warning',
      FALSE
    );
    return $empty_locations;
  }
  return NULL;
}

/**
 * Fill all locations using google geocode.
 */
function la_batch() {
  $empty_locations = db_select('location', 'l')
    ->fields('l', array('lid'))
    ->condition('latitude', '0.000000')
    ->condition('longitude', '0.000000')
    ->execute()
    ->rowCount();
  if ($empty_locations = 0) {
    return;
  }

  // Reset counter for debug information.
  $_SESSION['http_request_count'] = 0;
  // Execute the function named la_batch_run.
  $function = 'la_batch_run';
  $batch = $function();
  batch_set($batch);
}

/**
 * Helper function for batch creation.
 *
 * @return array
 *   Batch array for processing.
 */
function la_batch_run() {

  $empty_locations = db_select('location', 'l')
    ->fields('l', array('lid'))
    ->condition('latitude', '0.000000')
    ->condition('longitude', '0.000000')
    ->execute()
    ->fetchAll();

  foreach ($empty_locations as $lid) {
    $operations[] = array(
      'la_geocode_worker',
      array(
        $lid->lid,
        t('(Processing location: @location)', array('@location' => $lid->lid)),
      ),
    );
  }

  $batch = array(
    'operations' => $operations,
    'finished' => 'la_batch_finished',
  );
  return $batch;
}

/**
 * Handler to process single location per batch run.
 *
 * @param $lid
 *   Location ID to process.
 * @param $operation_details
 *   Details, passed to batch.
 * @param $context
 *   Context, that stores interbatch data.
 */
function la_geocode_worker($lid, $operation_details, &$context) {
  $l = location_load_location($lid);
  module_load_include('inc', 'location', 'geocoding/google');
  $r = google_geocode_location($l);
  if ($r != NULL) {
    $l['latitude'] = $r['lat'];
    $l['longitude'] = $r['lon'];
    location_save($l, FALSE);
  }

  // Inform the batch engine that we are not finished,
  // and provide an estimation of the completion level we reached.
  if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
    $context['finished'] = ($context['sandbox']['progress'] >= $context['sandbox']['max']);
  }
  // Store some results for post-processing in the 'finished' callback.
  // The contents of 'results' will be available as $results in the
  // 'finished' function (currently, la_batch_finished()).
  $context['results'][] = is_null(
    $r
  ) ? 'error' : $lid . ' : ' . $l['latitude'] . ':' . $l['longitude'];

  // Optional message displayed under the progressbar.
  $context['message'] = is_null($r) ? t(
      'Error obtaining location: !lid',
      array('!lid' => $lid)
    ) . ' ' . $operation_details : t(
      'Updating location "@lid"',
      array('@lid' => $lid)
    ) . ' ' . $operation_details;

  la_update_http_requests();
}

/**
 * Batch finished callback.
 *
 * @param bool $success
 *   TRUE if success.
 * @param array $results
 *   Array of results.
 * @param $operations
 *   List of operations that remained unprocessed.
 */
function la_batch_finished($success, $results, $operations) {
  if ($success) {
    $counts = array_count_values($results);
    // Here we could do something meaningful with the results.
    // We just display the number of nodes we processed...
    $cresults = count($results);
    $csuccess = count($counts);
    $cerrors = $counts['error'];
    drupal_set_message(
      t(
        '@count locations processed in @requests HTTP requests with @errors errors.',
        array(
          '@count' => $cresults,
          '@requests' => la_get_http_requests(),
          '@errors' => $cerrors
        )
      )
    );
  }
  else {
    // An error occurred.
    // $operations contains the operations that remained unprocessed.
    $error_operation = reset($operations);
    drupal_set_message(
      t(
        'An error occurred while processing @operation with arguments : @args',
        array(
          '@operation' => $error_operation[0],
          '@args' => print_r($error_operation[0], TRUE),
        )
      )
    );
  }
}

/**
 * Utility function to count the HTTP requests in a session variable.
 *
 * @return int
 *   Number of requests.
 */
function la_get_http_requests() {
  return !empty($_SESSION['http_request_count']) ? $_SESSION['http_request_count'] : 0;
}

/**
 * Utility function to increment HTTP requests in a session variable.
 */
function la_update_http_requests() {
  $_SESSION['http_request_count']++;
}