forked from asmallwebfirm/scale_addressfield
-
Notifications
You must be signed in to change notification settings - Fork 0
/
scale_addressfield.module
485 lines (435 loc) · 16.2 KB
/
scale_addressfield.module
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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
<?php
/**
* @file
* Hooks and functions for the Scale Addressfield module.
*/
/**
* Implements hook_ctools_plugin_post_alter().
*/
function scale_addressfield_ctools_plugin_post_alter(&$plugin, &$info) {
if ($info['type'] == 'format' && $info['module'] == 'addressfield') {
// Limit ourselves to only the dynamic country-specific addressfield.
if ($plugin['format callback'] == 'addressfield_format_address_generate') {
$plugin['format callback'] = 'scale_addressfield_override_format';
$plugin['path'] = drupal_get_path('module', 'scale_addressfield');
$plugin['file'] = 'scale_addressfield.address.inc';
}
}
}
/**
* Element validation handler for address field form elements that conditionally
* exist.
*/
function scale_addressfield_validate_conditional_element($element, &$form, &$form_state) {
// Get the submitted country value from the current form submission.
$country_parents = $element['#parents'];
$current_field = array_pop($country_parents);
$country_parents[] = 'country';
$country_parents[] = '#value';
$country = drupal_array_get_nested_value($form_state, $country_parents);
// Check if this field is even a thing for this country.
if (!scale_addressfield_country_has_field($country, $current_field)) {
// Determine what the error message likely says.
$message = '!name field is required.';
// Get rid of the error message.
scale_addressfield_remove_element_form_error($element, $message, array('!name' => $element['#title']));
}
}
/**
* Element validation handler for address field form elements that include a
* defined "format."
*/
function scale_addressfield_validate_field_format($element, &$form, &$form_state) {
// Get the submitted country value from the current form submission.
$country_parents = $element['#parents'];
$current_field = array_pop($country_parents);
$country_parents[] = 'country';
$country_parents[] = '#value';
$country = drupal_array_get_nested_value($form_state, $country_parents);
// Preconditions for this validation handler.
$definition = scale_addressfield_get_field($country, $current_field);
$format = isset($definition['format']) ? $definition['format'] : FALSE;
$required = isset($element['#required']) && $element['#required'];
// If the field is not required and the value is empty, do not validate.
if (!$required && empty($element['#value'])) {
return;
}
// Check if this field is even a thing for this country.
if ($definition && $format) {
// If the field value does not match the expected format, set a validation
// error on the field.
if (!preg_match('/' . $format . '/', $element['#value'])) {
// Provide more meaningful validation if possible.
if (isset($definition['eg'])) {
$message = t('Please check your formatting.') . ' ';
$message .= t('The @field_label field should resemble %example_value.', array(
'@field_label' => $definition['label'],
'%example_value' => $definition['eg'],
));
}
else {
$message = t('Please check your formatting.');
}
// Set the error.
form_set_error(implode('][', $element['#parents']), $message);
}
}
}
/**
* Implements hook_menu().
*/
function scale_addressfield_menu() {
$menu['addressfield/config.json'] = array(
'title' => 'Address field configuration JSON',
'type' => MENU_CALLBACK,
'page callback' => 'scale_addressfield_get_address_configuration',
'page arguments' => array('json'),
'delivery callback' => 'scale_addressfield_deliver_json',
'access callback' => TRUE,
);
return $menu;
}
/**
* Implements hook_library().
*/
function scale_addressfield_library() {
$path = drupal_get_path('module', 'scale_addressfield');
$items['jquery.addressfield'] = array(
'title' => 'jquery.addressfield',
'version' => '1.0.2',
'js' => array(
$path . '/js/jquery.addressfield/jquery.addressfield.min.js' => array(
'group' => JS_LIBRARY,
'weight' => -18,
),
),
);
return $items;
}
/**
* Packages and sends the result of a page callback to the browser as JSON.
*/
function scale_addressfield_deliver_json($page_callback_result) {
drupal_add_http_header('Content-Type', 'application/json; charset=utf-8');
drupal_add_http_header('Content-Language', $GLOBALS['language']->language);
print $page_callback_result;
drupal_page_footer();
}
/**
* Returns the fully altered, localized configuration for the address field in a
* specified format and language.
*
* @param string $format
* The format in which to return configurations. One of "php" or "json".
*
* @param string $language
* (Optional) A language code specifying the language in which configs (and
* more importantly, labels) should be returned. Defaults to the current
* language configured in the global scope.
*
* @param bool $refresh
* (Optional) TRUE if you want to manually regenerate the strings, rather than
* pulling them from cache. Defaults to FALSE.
*
* @return mixed
* If the "PHP" format is specified, an associated array of configurations is
* returned. If "JSON" is specified, the same will be returned, but in JSON.
*/
function scale_addressfield_get_address_configuration($format, $language = NULL, $refresh = FALSE) {
$return = &drupal_static(__FUNCTION__, array());
$lang = isset($language) ? $language : $GLOBALS['language']->language;
if ($refresh || !isset($return[$lang][$format])) {
$cid = implode(':', array('scale_addressfield', 'address_config', $lang));
if ($refresh || !$data = cache_get($cid, 'cache')) {
// Load default configurations and decode them.
$json = scale_addressfield_get_default_address_configuration();
$return[$lang]['php'] = drupal_json_decode($json);
// Run the configuration through a Drupal alter prior to processing.
drupal_alter('addressfield_config_pre', $return[$lang]['php']);
// To reduce iterations over the whole config array, perform all process
// steps in a single loop in a single callback.
scale_addressfield_process_country_configuration($return[$lang]['php'], $lang);
// Run the configuration through a Drupal alter after processing.
drupal_alter('addressfield_config_post', $return[$lang]['php']);
// Copy all changes back over to the JSON side.
$return[$lang]['json'] = drupal_json_encode($return[$lang]['php']);
// Stash a copy in cache.
cache_set($cid, $return[$lang], 'cache', CACHE_PERMANENT);
}
else {
$return[$lang] = $data->data;
}
}
return $return[$lang][$format];
}
/**
* Applies processing steps against an address configuration, including any
* required localization.
*
* @param array $configs
* The full address configuration, represented as a PHP array. The "label" and
* "options" properties should be at the root of the array.
*
* @param string $lang
* The language with which processing should be performed.
*/
function scale_addressfield_process_country_configuration(&$configs, $lang) {
include_once DRUPAL_ROOT . '/includes/locale.inc';
$countries = country_get_list();
$lang_default = language_default('language');
$should_localize = $lang !== $lang_default;
// Localize the country label itself.
if ($should_localize) {
module_load_include('inc', 'scale_addressfield', 'scale_addressfield.loc');
$context = scale_addressfield_i18n_context(array('country', 'label'));
$configs['label'] = scale_addressfield_translate($context, $configs['label'], $lang);
}
// Process each country's configuration individually.
foreach ($configs['options'] as $key => &$config) {
// Respect hook_countries_alter() / configured countries in Drupal.
if (!isset($countries[$config['iso']])) {
unset ($configs['options'][$key]);
continue;
}
// Do not run through localization for the site default language.
if ($should_localize) {
// We're dealing with end-user strings that we need to localize.
scale_addressfield_localize_country_config($config, $lang);
}
// Provide a global translation via t() for the none selected label.
foreach ($config['fields'] as &$field) {
if (isset($field['locality'])) {
foreach ($field['locality'] as &$loc_field) {
if (isset($loc_field['administrativearea']['options'])) {
$loc_field['administrativearea']['options'][0][''] = t('--');
break 2;
}
}
}
}
}
// Assume the default language version is in the correct sort order.
if ($should_localize && extension_loaded('intl')) {
scale_addressfield_current_locale($lang);
usort($configs['options'], 'scale_addressfield_localize_country_sort');
}
}
/**
* Returns the contents of the JSON file containing address configurations.
*
* @return string
* The full contents of the default address configuration JSON file.
*/
function scale_addressfield_get_default_address_configuration() {
$default = drupal_get_path('module', 'scale_addressfield');
$default .= DIRECTORY_SEPARATOR . 'json' . DIRECTORY_SEPARATOR;
$default .= 'addressfield.min.json';
$json_file = variable_get('scale_addressfield_config_json', $default);
return file_get_contents($json_file);
}
/**
* Returns country configurations as an array, keyed by country ISO code.
*
* @param string $country
* (Optional) The country code for a specific configuration to return.
*
* @param string $language
* (Optional) The language code for the configuration. If empty, the global
* language will be assumed.
*
* @return array
* If a country is provided, a country configuration array will be returned.
* If none is provided, all country configurations will be returned, keyed by
* ISO code.
*/
function scale_addressfield_get_address_configuration_by_country($country = NULL, $language = NULL) {
$countries = &drupal_static(__FUNCTION__, array());
$lang = isset($language) ? $language : $GLOBALS['language']->language;
if (!isset($countries[$lang])) {
$configs = scale_addressfield_get_address_configuration('php', $lang);
foreach ($configs['options'] as $config) {
$countries[$lang][$config['iso']] = $config;
}
}
return $country ? $countries[$lang][$country] : $countries[$lang];
}
/**
* Helper function to return an associative array of localized country names,
* keyed by ISO code.
*/
function scale_addressfield_get_country_options_list() {
$countries = scale_addressfield_get_address_configuration_by_country();
$return = array();
foreach ($countries as $iso => $config) {
$return[$iso] = $config['label'];
}
return $return;
}
/**
* Helper function to return a field label for a given country in a given
* language. If no field or label exists, FALSE will be returned.
*
* @param string $country
* The country code of the given country.
*
* @param string $field
* The xNAL name of the given field.
*
* @param string $language
* (Optional) The language code for the desired field label.
*
* @return string|bool
* Returns the localized label for the given field and country. FALSE if no
* field or field label is found.
*/
function scale_addressfield_get_field_label($country, $field, $language = NULL) {
$config = scale_addressfield_get_field($country, $field, $language);
return isset($config['label']) ? $config['label'] : FALSE;
}
/**
* Helper function that checks if a given country uses the given field in their
* addresses.
*
* @param string $country
* The country code of the given country.
*
* @param string $field
* The xNAL name of the given field.
*
* @return bool
* TRUE if the country uses the field in their addresses. FALSE otherwise.
*/
function scale_addressfield_country_has_field($country, $field) {
return (bool) scale_addressfield_get_field($country, $field);
}
/**
* Helper function that gets the definition of a field for a given country.
*
* @param string $country
* The country code of the given country.
*
* @param string $field
* The xNAL name of the given field.
*
* @param string $language
* (Optional) The language code for the desired configuration.
*
* @return array|bool
* Returns the field configuration array for the provided field/country or
* FALSE if the field does not exist.
*/
function scale_addressfield_get_field($country, $field, $language = NULL) {
$lang = isset($language) ? $language : $GLOBALS['language']->language;
// Get the configs for this country.
$config = scale_addressfield_get_address_configuration_by_country($country, $lang);
$parents = array('fields');
// Run the field through our map.
$field = scale_addressfield_get_xnal_field_name($field);
foreach ($config['fields'] as $fkey => $field_obj) {
$xnal = key($field_obj);
if ($xnal === $field) {
$parents[] = $fkey;
$parents[] = $xnal;
break;
}
elseif ($xnal === 'locality') {
$parents[] = $fkey;
$parents[] = $xnal;
foreach ($field_obj[$xnal] as $skey => $sub_field) {
$xnal = key($sub_field);
if ($xnal === $field) {
$parents[] = $skey;
$parents[] = $xnal;
break 2;
}
}
}
}
if (count($parents) === 1 || (count($parents) === 3 && $parents[2] === 'locality')) {
return FALSE;
}
else {
$definition = drupal_array_get_nested_value($config, $parents, $key_exists);
if ($key_exists && $definition) {
return $definition;
}
else {
return FALSE;
}
}
}
/**
* Helper function that maps "true" xnal field namespaces to those used by the
* Drupal Addressfield module (mostly maps underscores and things).
*
* @param string $field
* The name of the field as used by Drupal addressfield.
*
* @return string
* The name of the field as defined by the xNAL standard.
*/
function scale_addressfield_get_xnal_field_name($field) {
$map = array(
'locality_block' => 'locality',
'locality' => 'localityname',
'postal_code' => 'postalcode',
'administrative_area' => 'administrativearea',
);
return isset($map[$field]) ? $map[$field] : $field;
}
/**
* Helper function to remove errors from the global form state for a given form
* element.
*
* @param array $element
* The form element against which the error was originally set.
* @param string $message
* The error message (in English) that corresponds to the error.
* @param array $args
* (Optional) An array of arguments to be passed to the t() function for the
* given message string.
*/
function scale_addressfield_remove_element_form_error($element, $message, $args = array()) {
// Check that the error has even been lodged.
if ($error = form_get_error($element) AND $error == t($message, $args)) {
// Remove it from the global error state.
$key = implode('][', $element['#parents']);
$errors = &drupal_static('form_set_error');
unset($errors[$key]);
// There was also likely a message set. Remove it too.
scale_addressfield_remove_message('error', $message, $args);
}
}
/**
* Helper function to remove messages previously set elsewhere by Drupal.
*
* @param string $type
* The type of message to delete (error, status, etc).
* @param string $message
* The message (in English) that should not be displayed to the user.
* @param array $args
* Any arguments to pass to the translation function.
*/
function scale_addressfield_remove_message($type, $message, $args = array()) {
$message_search = t($message, $args);
// The array_search function expects an array.
if (isset($_SESSION['messages'][$type]) && is_array($_SESSION['messages'][$type])) {
$message_key = array_search($message_search, $_SESSION['messages'][$type]);
if ($message_key !== FALSE) {
// Remove the offending message.
unset($_SESSION['messages'][$type][$message_key]);
// If we deleted the only message, unset the message array.
if (count($_SESSION['messages'][$type]) == 0) {
unset($_SESSION['messages'][$type]);
// If we deleted the only message at all, unset the whole thing.
if (count($_SESSION['messages']) == 0) {
unset($_SESSION['messages']);
}
}
// Otherwise, reset the array keys. Drupal expects them neatly in order.
else {
$_SESSION['messages'][$type] = array_values($_SESSION['messages'][$type]);
}
}
}
}