Project

General

Profile

Download (102 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/**
3
 * @file
4
 * CDM Dataportal settings.
5
 */
6

    
7
// TODO Genus UUID.
8
define('DEFAULT_TAXONTREE_RANKLIMIT', '1b11c34c-48a8-4efa-98d5-84f7f66ef43a');
9
define('CDM_TAXONOMICTREE_UUID', 'cdm_taxonomictree_uuid');
10

    
11
define('CDM_DATAPORTAL_SEARCH_ITEMS_ON_PAGE', 25);
12
define('CDM_DATAPORTAL_NOMREF_IN_TITLE', 1);
13
define('CDM_DATAPORTAL_DISPLAY_IS_ACCEPTED_FOR', 0);
14
define('CDM_DATAPORTAL_ALL_FOOTNOTES', 0);
15
define('CDM_DATAPORTAL_ANNOTATIONS_FOOTNOTES', 0);
16
define('CDM_DATAPORTAL_LAST_VISITED_TAB_ARRAY_INDEX', 999);
17

    
18
/* annotationTypeKeys */
19
$annotationTypeKeys = array_keys(cdm_Vocabulary_as_option(UUID_ANNOTATION_TYPE));
20
if (in_array(UUID_ANNOTATION_TYPE_TECHNICAL, $annotationTypeKeys)) {
21
  $annotationTypeKeys = array_flip($annotationTypeKeys);
22

    
23
  // Technical annotation are off by default.
24
  unset($annotationTypeKeys[UUID_ANNOTATION_TYPE_TECHNICAL]);
25
  $annotationTypeKeys = array_flip($annotationTypeKeys);
26
  // Additional value for the NULL case.
27
  $annotationTypeKeys[] = 'NULL_VALUE';
28
}
29
define('ANNOTATIONS_TYPES_AS_FOOTNOTES_DEFAULT', serialize($annotationTypeKeys));
30

    
31
/* taxonRelationshipTypes */
32
define('CDM_TAXON_RELATIONSHIP_TYPES_DEFAULT', serialize(array(UUID_MISAPPLIED_NAME_FOR, UUID_INVALID_DESIGNATION_FOR)));
33

    
34

    
35

    
36
/* ---- MAP SETTING CONSTANTS ---- */
37
/**
38
 * @var array of URIs eg. http://edit.africamuseum.be"
39
 *   An options array
40
 */
41
define('EDIT_MAPSERVER_URI', serialize(
42
    array(
43
      'http://edit.africamuseum.be'=>'Primary (http://edit.africamuseum.be)',
44
      'http://edit.br.fgov.be'=>'Secondary (http://edit.br.fgov.be)',
45
    )
46
  )
47
);
48
define('EDIT_MAPSERVER_PATH', '/edit_wp5');
49
/**
50
 * @var array of versions eg. "v1.2"
51
 *   An options array
52
 */
53
define('EDIT_MAPSERVER_VERSION', serialize(
54
    array(
55
      'v1' => 'v1' ,
56
      'v1.1' => 'v1.1',
57
      'v1.2_dev' => 'v1.2_dev',
58
      'v1.2' => 'v1.2',
59
      'v1.3_dev' => 'v1.3_dev',
60
      'v1.4_dev' => 'v1.4_dev'
61
    )
62
  )
63
);
64
define('EDIT_MAPSERVER_URI_DEFAULT', 'http://edit.africamuseum.be');
65
define('EDIT_MAPSERVER_VERSION_DEFAULT', 'v1.2');
66

    
67
// --- Taxon profile settings --- /
68
define('LAYOUT_SETTING_PREFIX', 'layout_');
69
define('FEATURE_TREE_LAYOUT_DEFAULTS', serialize(
70
  array(
71
    'enabled' => FALSE,
72
    'enclosingTag' => 'ul',
73
    'entryEnclosingTag' => 'li',
74
    'glue' => ' ',
75
  )));
76

    
77
define('DISTRIBUTION_TEXTDATA_DISPLAY_ON_TOP', 'distribution_textdata_on_top');
78
define('CDM_TAXON_PROFILE_IMAGE', 'cdm_taxon_profile_image');
79
define('CDM_TAXON_PROFILE_IMAGE_DEFAULT', serialize(
80
    array(
81
        'show' => 0,
82
        'maxextend' => 184,
83
        'media_uri_query' => '',
84
        'custom_placeholder_image_on' => 0,
85
        'custom_placeholder_image_fid' => ''
86
    )
87
  )
88
);
89

    
90
/**
91
 * Returns the array of implemented taxon page tabs.
92
 * The array has fixed integer keys which must not be changed.
93
 */
94
function get_taxon_tabs_list() {
95
  return array(
96
    0 => 'General',
97
    1 => 'Synonymy',
98
    2 => 'Images',
99
    3 => 'Specimens',
100
    4 => 'Keys',
101
  );
102
}
103

    
104
define('CDM_TAXONPAGE_TAB_WEIGHT_DEFAULT', serialize(
105
  array('general' => '-3', 'synonymy' => '-2', 'images' => '0', 'specimens' => '1', 'keys' => '3')
106
));
107

    
108
$taxon_tab_options = get_taxon_tabs_list();
109
$taxon_tab_options[CDM_DATAPORTAL_LAST_VISITED_TAB_ARRAY_INDEX] = 'Last visited tab';
110

    
111
define('CDM_DATAPORTAL_DEFAULT_TAXON_TAB', serialize($taxon_tab_options));
112

    
113
/**
114
 * @todo document this function.
115
 */
116
function get_taxon_options_list() {
117
  $taxon_tab_options = array_flip(get_taxon_tabs_list());
118
  foreach ($taxon_tab_options as $key => $value) {
119
    $taxon_tab_options[$key] = t($key);
120
  }
121
  return $taxon_tab_options;
122

    
123
}
124

    
125
define('CDM_PART_DEFINITIONS', 'cdm-part-definitions');
126
define('CDM_PART_DEFINITIONS_DEFAULT', serialize(
127
  array(
128
      'ZoologicalName' => array(
129
        'namePart' => array('name' => TRUE),
130
        'nameAuthorPart' => array('name' => TRUE),
131
        'referencePart' => array('authors' => TRUE),
132
        'microreferencePart' => array('microreference' => TRUE),
133
        'statusPart' => array('status' => TRUE),
134
        'descriptionPart' => array('description' => TRUE),
135
      ),
136
      'BotanicalName'=> array(
137
        'namePart' => array('name' => TRUE),
138
        'nameAuthorPart' => array('name' => TRUE, 'authors' => TRUE),
139
        'referencePart' => array('reference' => TRUE, 'microreference' => TRUE),
140
        'statusPart' => array('status' => TRUE),
141
        'descriptionPart' => array('description' => TRUE),
142
      ),
143
     '#DEFAULT' => array(
144
        'namePart' => array(
145
            'name' => TRUE
146
        ),
147
        'nameAuthorPart' => array(
148
            'name' => TRUE,
149
            'authors' => TRUE
150
        ),
151
        'referencePart' => array(
152
            'reference' => TRUE
153
        ),
154
        'microreferencePart' => array(
155
            'microreference' => TRUE,
156
        ),
157
        'statusPart' => array(
158
            'status' => TRUE,
159
        ),
160
        'descriptionPart' => array(
161
            'description' => TRUE,
162
        ),
163
      )
164
    )
165
  )
166
);
167
define('CDM_NAME_RENDER_TEMPLATES', 'cdm-name-render-templates');
168
define('CDM_NAME_RENDER_TEMPLATES_DEFAULT', serialize(
169
   array (
170
     'taxon_page_title,polytomousKey'=> array(
171
          'namePart' => array('#uri' => TRUE),
172
        ),
173
      'taxon_page_synonymy,related_taxon'=> array(
174
          'nameAuthorPart' => array('#uri' => TRUE),
175
          'referencePart' => TRUE,
176
          'statusPart' => TRUE,
177
          'descriptionPart' => TRUE,
178
        ),
179
      'acceptedFor,typedesignations,list_of_taxa' => array(
180
          'nameAuthorPart' => array('#uri' => TRUE),
181
          'referencePart' => TRUE,
182
        ),
183
      '#DEFAULT' => array(
184
          'nameAuthorPart' => array('#uri' => TRUE),
185
          'referencePart' => TRUE,
186
       )
187
    )
188
));
189

    
190
define('CDM_SEARCH_TAXA_MODE','cdm_search_taxa_mode');
191
define('CDM_SEARCH_TAXA_MODE_DEFAULT', serialize(
192
    // to unset a default enntry set the value to 0
193
    array(
194
      'doTaxa'=>'doTaxa',
195
      'doSynonyms' => 'doSynonyms',
196
      'doTaxaByCommonNames' => 'doTaxaByCommonNames',
197
      'doMisappliedNames' => 'doMisappliedNames'
198
    )
199
  )
200
);
201

    
202
/* Gallery variables. */
203
$gallery_settings = array(
204
    "cdm_dataportal_show_taxon_thumbnails" => 1,
205
    "cdm_dataportal_show_synonym_thumbnails" => 0,
206
    "cdm_dataportal_show_thumbnail_captions" => 1,
207
    "cdm_dataportal_media_maxextend" => 120,
208
    "cdm_dataportal_media_cols" => 3,
209
    "cdm_dataportal_media_maxRows" => 1,
210
);
211

    
212
define('TAXONPAGE_VISIBILITY_OPTIONS_DEFAULT', serialize(get_taxon_options_list()));
213
define('CDM_DATAPORTAL_GALLERY_SETTINGS', serialize($gallery_settings));
214
define('CDM_DATAPORTAL_SPECIMEN_GALLERY_NAME', 'specimen_gallery');
215
define('CDM_DATAPORTAL_DESCRIPTION_GALLERY_NAME', "description_gallery");
216
define('CDM_DATAPORTAL_MEDIA_GALLERY_NAME', "media_gallery");
217
define('CDM_DATAPORTAL_TAXON_MEDIA_GALLERY_NAME_TAB', "taxon_tab_media_gallery");
218
define('CDM_DATAPORTAL_SEARCH_GALLERY_NAME', "search_gallery");
219
define('CDM_DATAPORTAL_DISPLAY_TAXON_RELATIONSHIPS', 'cdm_dataportal_display_taxon_relationships');
220
define('CDM_DATAPORTAL_DISPLAY_NAME_RELATIONSHIPS', 'cdm_dataportal_display_name_relations');
221
// define('CDM_DATAPORTAL_DISPLAY_NAME_RELATIONSHIPS_2', array("default" => t('Display all')));
222
define('CDM_DATAPORTAL_DISPLAY_TAXON_RELATIONSHIPS_DEFAULT', 1);
223
define('CDM_DATAPORTAL_DISPLAY_NAME_RELATIONSHIPS_DEFAULT', 1);
224
/**
225
 * The drupal variable key for the array containing the uuids of the taxon relationship types to display in
226
 * the snonymy.
227
 *
228
 * @var string
229
 */
230
define('CDM_TAXON_RELATIONSHIP_TYPES', 'cdm_taxon_relationship_types');
231
/**
232
 * The drupal variable for the configuration of the information aggregation along
233
 * the taxon relation ships. The mapped arrayis associative and holds two elements:
234
 *    - direct: the uuids of the taxon relationship types to take into account in invers
235
 *      direction.
236
 *    - invers: the uuids of the taxon relationship types to take into account in direct
237
 *      direction.
238
 *
239
 * @var String
240
 */
241
define('CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS', 'cdm_aggregate_by_taxon_relationships');
242
define('CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS_DEFAULT', serialize(
243
    array(
244
        'direct'=>array(),
245
        'invers'=>array()
246
     )
247
   ));
248
define('CDM_PROFILE_FEATURETREE_UUID', 'cdm_dataportal_featuretree_uuid');
249
define('CDM_OCCURRENCE_FEATURETREE_UUID', 'cdm_occurrence_featuretree_uuid');
250
define('CDM_DATAPORTAL_STRUCTURED_DESCRIPTION_FEATURETREE_UUID', 'cdm_dataportal_structdesc_featuretree_uuid');
251

    
252
define('CDM_TAXON_MEDIA_FILTER', 'cdm_taxon_media_filter');
253
define('CDM_TAXON_MEDIA_FILTER_DEFAULT', serialize(
254
    array(
255
        'includeTaxonDescriptions' => 'includeTaxonDescriptions',
256
        'includeOccurrences' => 0,
257
        'includeTaxonNameDescriptions' => 0
258
     )
259
  ));
260

    
261
define('CDM_MAP_DISTRIBUTION', 'cdm_map_distribution');
262
define('CDM_MAP_DISTRIBUTION_DEFAULT', serialize(array(
263
  // needs to be merged with user setting by drupal_array_merge_deep()
264
  'width' => 512, // optimum size for OSM layers is 512
265
  'height' => 512 / 2, // optimum size for OSM layers 256
266
  'bbox' => '', // empty to allow automatic zooming to extend
267
  'show_labels' => FALSE,
268
  'caption' => '',
269
  'distribution_opacity' => '0.5',
270
  'map_type' => 1, //  1 = 'openlayers', 0 = 'image'
271
  'image_map' => array(
272
    'base_layer' => '', // none, formerly this was cyprusdivs
273
    'bg_color' => '1874CD',
274
    'layer_style' => 'ffffff,606060,,',
275
  ),
276
  'openlayers' => array(
277
    'base_layers' =>  array(
278
      // A layer MUST NOT BE SET in the defaults,
279
      // otherwise it can not be overidden by the user settings:
280
      // 'osgeo_vmap0' => 'osgeo_vmap0',
281
      // it is sufficient to define the preferred layer,
282
      // since it will automatically be enabled:
283
      'PREFERRED' => 'osgeo_vmap0'),
284
     'custom_wms_base_layer' => array(
285
            'name' => NULL,
286
            'url' => NULL,
287
            'params' =>  NULL,
288
            'projection' => NULL,
289
            'proj4js_def' => NULL,
290
            'max_extent' => NULL,
291
            'units' => NULL
292
     ),
293
    'show_layer_switcher' => TRUE,
294
    'display_outside_max_extent' => FALSE
295
  ),
296
  'legend' => array(
297
    'show' => TRUE,
298
    'opacity' => '0.5',
299
    'font_size' => 10,
300
    'font_style' => FALSE,
301
    'icon_width' => 35,
302
    'icon_height' => 15
303
  )
304
)));
305

    
306
/**
307
 * Merges the named array variable with the array of defaults.
308
 *
309
 * IḾPORTANT: The array keys must be strings. When the keys are integers
310
 * the merging will not take place for these enties. Number keyed enties
311
 * are just appended to the result array.
312
 *
313
 * @param string $variable_name
314
 *     The variable name
315
 * @param string | array $default
316
 *     The array containing the default values either as array or serialized as string.
317
 *     Unserialization is cared for if nessecary
318
 * @return array
319
 *     The merged array as returnd by drupal_array_merge_deep()
320
 */
321
function get_array_variable_merged($variable_name, $default){
322

    
323
    // unserialize if nessecary
324
    if(!is_array($default)){
325
      $default = unserialize($default);
326
    }
327
    $variable = variable_get($variable_name, array());
328
    $result = drupal_array_merge_deep($default, $variable);
329
    return $result;
330
}
331

    
332
/**
333
 * @todo document this function.
334
 */
335
function getGallerySettings($gallery_config_form_name) {
336
  return get_array_variable_merged($gallery_config_form_name, CDM_DATAPORTAL_GALLERY_SETTINGS);
337
}
338

    
339
/**
340
 * Returns the string representation of the default tab.
341
 *
342
 * @param bool $returnTabIndex
343
 *   Defaults to FALSE, if set true this function will return the index number
344
 *   of the default tab. (used to supply default values to form elements).
345
 */
346
function get_default_taxon_tab($returnTabIndex = FALSE) {
347

    
348
  global $user;
349
  $values = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
350
  $user_tab_active = 'cdm_dataportal_' . $user->uid . '_default_tab_active';
351
  $user_tab = 'cdm_dataportal_' . $user->uid . '_default_tab';
352
  // Get the user value if the used has chosen to overwrite the system settings.
353
  $user_tab_on = variable_get($user_tab_active, FALSE);
354
  if ($user_tab_on) {
355
    $user_value = variable_get($user_tab, 0);
356
    $index_value = $user_value;
357
    // Get the system value.
358
  }
359
  else {
360
    $system_value = variable_get('cdm_dataportal_default_tab', 0);
361
    $index_value = $system_value;
362
  }
363

    
364
  // Return the index value or the string representation.
365
  if ($returnTabIndex) {
366
    return $index_value;
367
  }
368
  else {
369
    return ($values[$index_value]);
370
  }
371

    
372
}
373

    
374
/**
375
 * @todo Please document this function.
376
 * @see http://drupal.org/node/1354
377
 */
378
function cdm_dataportal_menu_admin(&$items) {
379
  // Display section on admin/config page.
380
  $items['admin/config/cdm_dataportal'] = array(
381
    'title' => 'CDM Dataportal',
382
    'description' => 'Settings for the CDM DataPortal.',
383
    'position' => 'right',
384
    'weight' => 10,
385
    'page callback' => 'system_admin_menu_block_page',
386
    'access arguments' => array('administer cdm_dataportal'),
387
    'file' => 'system.admin.inc',
388
    'file path' => drupal_get_path('module', 'system'),
389
  );
390
  $items['admin/config/cdm_dataportal/settings'] = array(
391
    'title' => 'Settings',
392
    'description' => 'Settings for the CDM DataPortal.',
393
    'weight' => 0,
394
    'page callback' => 'drupal_get_form',
395
    'page arguments' => array('cdm_settings_general'),
396
    'access arguments' => array('administer cdm_dataportal'),
397
    'type' => MENU_NORMAL_ITEM,
398
  );
399
  $items['admin/config/cdm_dataportal/settings/general'] = array(
400
    'title' => 'General',
401
    'description' => 'General',
402
    'weight' => 0,
403
    'page callback' => 'drupal_get_form',
404
    'page arguments' => array('cdm_settings_general'),
405
    'access arguments' => array('administer cdm_dataportal'),
406
    'type' => MENU_DEFAULT_LOCAL_TASK,
407
  );
408

    
409
  $items['admin/config/cdm_dataportal/settings/cachesite'] = array(
410
    'title' => 'Cache',
411
    'description' => 'Cache',
412
    'access arguments' => array('administer cdm_dataportal'),
413
    'page callback' => 'drupal_get_form',
414
    'page arguments' => array('cdm_settings_cache'),
415
    'weight' => 10,
416
    'type' => MENU_LOCAL_TASK,
417
  );
418

    
419
  $items['admin/config/cdm_dataportal/settings/geo'] = array(
420
    'title' => 'Geo & Map',
421
    'description' => 'Geo & Map',
422
    'access arguments' => array('administer cdm_dataportal'),
423
    'page callback' => 'drupal_get_form',
424
    'page arguments' => array('cdm_settings_geo'),
425
    'weight' => 1,
426
    'type' => MENU_LOCAL_TASK,
427
  );
428

    
429
  $items['admin/config/cdm_dataportal/settings/layout'] = array(
430
    'title' => 'Layout',
431
    'description' => 'Configure and adjust the layout of your DataPortal ',
432
    'access arguments' => array('administer cdm_dataportal'),
433
    'page callback' => 'drupal_get_form',
434
    'page arguments' => array('cdm_settings_layout'),
435
    'weight' => 2,
436
    'type' => MENU_LOCAL_TASK,
437
  );
438

    
439
  $items['admin/config/cdm_dataportal/settings/layout/taxon'] = array(
440
    'title' => 'Taxon',
441
    'description' => 'Configure and adjust the layout of your DataPortal ',
442
    'access arguments' => array('administer cdm_dataportal'),
443
    'page callback' => 'drupal_get_form',
444
    'page arguments' => array('cdm_settings_layout_taxon'),
445
    'weight' => 1,
446
    'type' => MENU_LOCAL_TASK,
447
  );
448
  /*
449
  $items[] = array(
450
  'path' => 'admin/config/cdm_dataportal/layout/synonymy',
451
  'title' => t('Synonymy'),
452
  'description' => t('Configure and adjust the layout of your DataPortal '),
453
  'access' => user_access('administer cdm_dataportal'),
454
  'callback' => 'drupal_get_form',
455
  'callback arguments' => array('cdm_settings_layout_synonymy'),
456
  'weight' => 1,
457
  'type' => MENU_LOCAL_TASK,
458
  );
459

    
460
  $items[] = array(
461
  'path' => 'admin/config/cdm_dataportal/layout/specimens',
462
  'title' => t('Specimens'),
463
  'description' => t('Configure and adjust the layout of your DataPortal '),
464
  'access' => user_access('administer cdm_dataportal'),
465
  'callback' => 'drupal_get_form',
466
  'callback arguments' => array('cdm_settings_layout_specimens'),
467
  'weight' => 1,
468
  'type' => MENU_LOCAL_TASK,
469
  );
470
  */
471
  $items['admin/config/cdm_dataportal/settings/layout/search'] = array(
472
    'title' => 'Search',
473
    'description' => 'Configure and adjust the layout of your DataPortal ',
474
    'access arguments' => array('administer cdm_dataportal'),
475
    'page callback' => 'drupal_get_form',
476
    'page arguments' => array('cdm_settings_layout_search'),
477
    'weight' => 2,
478
    'type' => MENU_LOCAL_TASK,
479
  );
480

    
481
  $items['admin/config/cdm_dataportal/settings/layout/media'] = array(
482
    'title' => 'Media',
483
    'description' => 'Configure and adjust the layout of your DataPortal ',
484
    'access arguments' => array('administer cdm_dataportal'),
485
    'page callback' => 'drupal_get_form',
486
    'page arguments' => array('cdm_settings_layout_media'),
487
    'weight' => 3,
488
    'type' => MENU_LOCAL_TASK,
489
  );
490

    
491
}
492

    
493
/**
494
 * @todo document this function.
495
 */
496
function cdm_help_general_cache() {
497
  $form = array();
498
  $form['cache_help'] = array(
499
    '#type' => 'fieldset',
500
    '#title' => t('Help'),
501
    '#collapsible' => TRUE,
502
    '#collapsed' => TRUE,
503
  );
504
  $form['cache_help']['test'] = array('#value' => t('probando'));
505
  return drupal_render($form);
506
  $res = array();
507
  $res['default'] = drupal_render($help);
508
  return $res;
509
}
510

    
511
/**
512
 * Configures the settings form for the CDM-API module.
513
 *
514
 * @return array
515
 *   Drupal settings form.
516
 */
517
function cdm_settings_general() {
518

    
519
  $form['cdm_webservice'] = array(
520
    '#type' => 'fieldset',
521
    '#title' => t('CDM Server'),
522
    '#collapsible' => FALSE,
523
    '#collapsed' => FALSE,
524
    '#description' => t('The <em>CDM Server</em> exposes data stored in a
525
        CDM data base to the web via RESTful web services and thus is the source of the data
526
        to be displayed by a CDM DataPotal.'),
527
  );
528

    
529
  $form['cdm_webservice']['cdm_webservice_url'] = array(
530
    '#type' => 'textfield',
531
    '#title' => t('CDM web service URL') . ':',
532
    '#description' => t('This is the URL to the CDM-Server exposing your data
533
      e.g. <em>"http://myserver.net/cdmserver/myproject"</em>'),
534
    '#default_value' => variable_get('cdm_webservice_url', NULL),
535
  );
536

    
537
  $form['cdm_webservice']['cdm_webservice_debug'] = array(
538
    '#type' => 'markup',
539
    '#markup' => '<b>Debug CDM Web Service:</b> The web service debug box has completely been replaced '
540
      . 'by  the ' . l('CDM web service debug block', 'admin/structure/block/manage/cdm_api/cdm_ws_debug/configure')
541
      . '. It is usually only visible for administrative roles like <i>administrator</i> and <i>CDM admin</i>'
542
  );
543

    
544
  $form['cdm_webservice']['freetext_index'] = array(
545
    '#type' => 'fieldset',
546
    '#title' => t('Freetext index'),
547
    '#collapsible' => FALSE,
548
    '#collapsed' => FALSE,
549
  );
550

    
551
  // Check the cdmserver port number and display a waring if it is not port 80
552
  preg_match("#http[s]?://[0-9\p{L}\.]*:([0-9]*)/.*#u", variable_get('cdm_webservice_url', ''), $portNumberMatch, PREG_OFFSET_CAPTURE);
553
  if (isset($portNumberMatch[1]) && $portNumberMatch[1] != '80') {
554
    $form['cdm_webservice']['freetext_index']['message'] = array(
555
      '#markup' => "<div class=\"description\">"
556
      . t("The CDM web service URL contains a portnumber other than standart HTTP port 80: '!port'."
557
      . " Due to this the reindex and purge fuctions may not be working if there is a firewall in between you and the CDM Server."
558
      . " You may want to contact the maintainer of the according CDM Server in order to solve this problem.", array('!port' => $portNumberMatch[1][0]))
559
      . "</div>",
560
    );
561
  };
562

    
563
  $frontentURL = urlencode(variable_get('cdm_webservice_url', ''));
564
  $trigger_link_options = array(
565
    'attributes' => array(
566
      'class' => 'index-trigger',
567
    ),
568
  );
569
  $form['cdm_webservice']['freetext_index']['operations'] = array(
570
    '#markup' => "<div>" . t('Operations: !url1 !url2', array(
571
        '!url1' => l(t("Purge"), cdm_compose_url(CDM_WS_MANAGE_PURGE, NULL, 'frontendBaseUrl=' . $frontentURL), $trigger_link_options),
572
        '!url2' => l(t("Reindex"), cdm_compose_url(CDM_WS_MANAGE_REINDEX, NULL, 'frontendBaseUrl=' . $frontentURL), $trigger_link_options),
573
      ))
574
    . '<div id="index-progress"></div></div>',
575
  );
576
  _add_js_cdm_ws_progressbar(".index-trigger", "#index-progress");
577

    
578
  $form['cdm_webservice']['proxy'] = array(
579
    '#type' => 'fieldset',
580
    '#title' => t('Proxy'),
581
    '#collapsible' => TRUE,
582
    '#collapsed' => TRUE,
583
  );
584

    
585
  $form['cdm_webservice']['proxy']['cdm_webservice_proxy_url'] = array(
586
    '#type' => 'textfield',
587
    '#title' => t('Proxy URL') . ':',
588
    '#description' => t('If this proxy url is set the cdm api tries
589
    to connect the web service over the given proxy server.
590
    Otherwise proxy usage is deactivated.'),
591
    '#default_value' => variable_get('cdm_webservice_proxy_url', FALSE),
592
  );
593

    
594
  $form['cdm_webservice']['proxy']['cdm_webservice_proxy_port'] = array(
595
    '#type' => 'textfield',
596
    '#title' => t('Proxy port') . ':',
597
    '#default_value' => variable_get('cdm_webservice_proxy_port', '80'),
598
  );
599

    
600
  $form['cdm_webservice']['proxy']['cdm_webservice_proxy_usr'] = array(
601
    '#type' => 'textfield',
602
    '#title' => t('Login') . ':',
603
    '#default_value' => variable_get('cdm_webservice_proxy_usr', FALSE),
604
  );
605

    
606
  $form['cdm_webservice']['proxy']['cdm_webservice_proxy_pwd'] = array(
607
    '#type' => 'textfield',
608
    '#title' => t('Password') . ':',
609
    '#default_value' => variable_get('cdm_webservice_proxy_pwd', FALSE),
610
  );
611

    
612
  // TODO: settings are still incomplete, compare with
613
  // trunk/dataportal/inc/config_default.php.inc.
614
  $form['taxon_tree'] = array(
615
    '#type' => 'fieldset',
616
    '#title' => t('Taxon Tree'),
617
    '#collapsible' => FALSE,
618
    '#collapsed' => TRUE,
619
    '#description' => t('<p>When you explore your collection, you can navigate
620
      it through a tree structure also called <em>Taxon Tree</em>.</p><p>To be
621
      able to navigate through your collection the
622
      <a href="http://drupal.org/handbook/blocks">drupal block</a>
623
      <em>CDM Taxon Tree</em> should be visible for users. Enable the block at
624
      <a href="./?q=admin/build/block">Administer&#45&#62Site building&#45&#62Blocks
625
      </a></p>'),
626
  );
627

    
628
  $form['taxon_tree'][CDM_TAXONOMICTREE_UUID] = array(
629
    '#type' => 'select',
630
    '#title' => t('Available classifications') . ':',
631
    '#default_value' => variable_get(CDM_TAXONOMICTREE_UUID, FALSE),
632
    '#options' => cdm_get_taxontrees_as_options(),
633
    '#description' => t('Select the default taxa classification for your
634
      <em>taxon tree</em>, the other classifications will be also available but
635
      with a manual user change.'),
636
  );
637

    
638
  $form['taxon_tree']['taxontree_ranklimit'] = array(
639
    '#type' => 'select',
640
    '#title' => t('Rank of highest displayed taxon') . ':',
641
     // Before DEFAULT_TAXONTREE_RANKLIMIT_UUID.
642
    '#default_value' => variable_get('taxontree_ranklimit', DEFAULT_TAXONTREE_RANKLIMIT),
643
    '#options' => cdm_rankVocabulary_as_option(),
644
    '#description' => t('This is the rank of the highest displayed taxon in the
645
      <em>taxon tree</em>. You can select here which rank should be at the top
646
      level of the tree structure.'),
647
  );
648

    
649
  $form['aggregation'] = array(
650
      '#type' => 'fieldset',
651
      '#title' => t('Aggregation of data'),
652
      '#collapsible' => FALSE,
653
      '#description' => t("This section covers the different aspects of aggregating information.
654
          <p>
655
          </p>"),
656

    
657
  );
658

    
659
  $form['aggregation'][CDM_TAXON_MEDIA_FILTER] = array(
660
      '#type' => 'checkboxes',
661
      '#title' => 'Taxon media filter',
662
      '#default_value' => variable_get(CDM_TAXON_MEDIA_FILTER, unserialize(CDM_TAXON_MEDIA_FILTER_DEFAULT)),
663
      '#options' => array(
664
          'includeTaxonDescriptions' => 'Media in taxon descriptions',
665
          'includeTaxonNameDescriptions' => 'Media in name descriptions',
666
          'includeOccurrences' => 'Media related to specimens and occurrences',
667
      ),
668
      '#description' => 'This filter configures which images should be taken into account.',
669
  );
670

    
671
  $form['aggregation']['notice'] = array(
672
      '#markup' => '<strong>NOTICE:</strong> The below aggregation settings can slow down the data portal, so you may want to sensibly apply these setting and you may also
673
          want to make use of the caching capabilities of the dataportal.',
674
  );
675

    
676
  $form['aggregation']['media_aggregation'] = array(
677
      '#type' => 'fieldset',
678
      '#title' => t('Media aggregation'),
679
      '#collapsible' => FALSE,
680
      '#collapsed' => TRUE,
681
      '#description' => t("The media aggregation is also affected by the settigs in \"<strong>Aggregation via taxon relationsships</strong>\" below."),
682

    
683
  );
684
  $form['aggregation']['media_aggregation']['cdm_images_include_children'] = array(
685
      '#type' => 'select',
686
      '#title' => t('Aggregation of taxon pictures') . ':',
687
      '#default_value' => variable_get('cdm_images_include_children', FALSE),
688
      '#options' => array(
689
          0 => "Show only pictures of the current taxon",
690
          1 => "Include pictures of taxonomic children",
691
      ),
692
      '#description' => t("Choose whether to include the images of the taxonomic children. This will affect the <em>Images</em> tab and image tumbnails like in the search results."),
693
  );
694

    
695
  $form['aggregation']['aggregate_by_taxon_relationships'][CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS] = array(
696
      '#type' => 'fieldset',
697
      '#attributes' => array('class'=>array('clearfix')),
698
      '#title' => t('Aggregation via taxon relationsships'),
699
      '#collapsible' => TRUE,
700
      '#collapsed' => TRUE,
701
      '#tree' => TRUE,
702
      '#description' => t('Information on taxa will be aggregated along the below chosen
703
          taxon relation ships. This will affect images and occurrences (specimens).
704
          Taxon relation ships are directed and point form one taxon to another. The taxon
705
          relationships to be taken into accunt can therefore configured for the direct direction
706
          and for the inverse.'),
707
  );
708

    
709
  $taxonRelationshipTypeOptions = cdm_Vocabulary_as_option(UUID_TAXON_RELATIONSHIP_TYPE, '_cdm_relationship_type_term_label_callback');
710
  $aggregate_by_taxon_relationships = variable_get(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS, unserialize(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS_DEFAULT));
711

    
712
  $form['aggregation']['aggregate_by_taxon_relationships'][CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS]['direct'] = array(
713
      '#type' => 'checkboxes',
714
      '#title' => t('Direct'),
715
      '#options' => $taxonRelationshipTypeOptions,
716
      '#default_value' => $aggregate_by_taxon_relationships['direct'],
717
  );
718
  $form['aggregation']['aggregate_by_taxon_relationships'][CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS]['invers'] = array(
719
      '#type' => 'checkboxes',
720
      '#title' => t('Invers'),
721
      '#options' => $taxonRelationshipTypeOptions,
722
      '#default_value' => $aggregate_by_taxon_relationships['invers'],
723
  );
724

    
725
  // ----------------------
726
  $form['cdm_js_devel_mode'] = array(
727
      '#type' => 'checkbox',
728
      '#title' => 'Java-script developer mode',
729
      '#default_value' => variable_get('cdm_js_devel_mode', FALSE),
730
      '#description' => 'In production envirionments the java script libraries
731
      the cdm_dataportal is making use of are compressed and optimized. This
732
      is good for performance but a caveat if you need to debug java-script. When the
733
      java-script developer mode is enabled the uncompressed and commented developer
734
      versions of java-script libraries will be used where possible.
735
      <br/><strong>Do not use this option in production!</strong>'
736
  );
737
  // ----------------------
738
  $form['cdm_debug_mode'] = array(
739
      '#type' => 'checkbox',
740
      '#title' => 'CDM page debug mode',
741
      '#default_value' => variable_get('cdm_debug_mode', FALSE),
742
      '#description' => 'When CDM page debug mode enabled the start and end of cdm entity page
743
      creation is logged as well as any http request send via the cdm_api. The log is written to a file in the temporary
744
      folder configured in the' . l('File system settings', 'admin/config/media/file-system') .
745
       '. For this site the file is <code> ' . file_directory_temp() . '/drupal_debug.txt</code>
746
      The log is written by the drupal devel module function <code>dd()</code>.
747
      <br/><strong>Note:</strong> The start and end of the page creation is currently only logged for taxon pages only.'
748
  );
749

    
750
  // Comment @WA: D7 form api does not support reset buttons,
751
  // so to mimic the D5 reset button we add one like this.
752
  $form['actions']['reset'] = array(
753
    '#markup' => '<input id="reset" type="reset" class="form-submit" value="' . t('Reset to defaults') . '" />',
754
    '#weight' => 1000,
755
  );
756

    
757
  return system_settings_form($form);
758
}
759

    
760

    
761
/**
762
 * LAYOUT settings
763
 * @return unknown_type
764
 *   todo
765
 */
766
function cdm_settings_layout() {
767

    
768
  $form = array();
769

    
770
  $form['about'] = array(
771
    '#markup' => '<h4>' . t('Portal Layout') . '</h4><p>' . t('This settings contains the general configurations
772
      layout. If you want to configure the specific sites layout visit the
773
      respective configuration site for taxon, search or media.') . '</p>',
774
  );
775

    
776
  // ---- footnotes --- //
777
  $form['footnotes'] = array(
778
    '#type' => 'fieldset',
779
    '#title' => t('Footnotes'),
780
    '#collapsible' => FALSE,
781
    '#collapsed' => FALSE,
782
    '#description' => t('Taxa data such authors, synonyms names, descriptions,
783
      media or distribution areas may have annotations or footnotes. When the
784
      footnotes are enabled they will be visible (if they exist).'),
785
  );
786

    
787
  $form['footnotes']['cdm_dataportal_all_footnotes'] = array(
788
    '#type' => 'checkbox',
789
    '#title' => t('Do not show footnotes'),
790
    '#default_value' => variable_get('cdm_dataportal_all_footnotes', CDM_DATAPORTAL_ALL_FOOTNOTES),
791
    '#description' => t('Check this if you do not want to show any footnotes'),
792
  );
793

    
794
  $form['footnotes']['cdm_dataportal_annotations_footnotes'] = array(
795
    '#type' => 'checkbox',
796
    '#title' => t('Do not show annotations footnotes'),
797
    '#default_value' => variable_get('cdm_dataportal_annotations_footnotes', CDM_DATAPORTAL_ANNOTATIONS_FOOTNOTES),
798
    '#description' => t('Check this if you do not want to show annotation footnotes'),
799
  );
800

    
801
  $annotationTypeOptions = cdm_Vocabulary_as_option(UUID_ANNOTATION_TYPE);
802
  // Additional option for the NULL case.
803
  $annotationTypeOptions['NULL_VALUE'] = t('untyped');
804
  $form['footnotes']['annotations_types_as_footnotes'] = array(
805
    '#type' => 'checkboxes',
806
    '#title' => t('Annotation types as footnotes'),
807
    '#description' => t("Only annotations of the selected type will be displayed
808
       as footnotes. You may want to turn 'technical annotations' off."),
809
    '#options' => $annotationTypeOptions,
810
  );
811
  $annotationsTypesAsFootnotes = variable_get('annotations_types_as_footnotes', unserialize(ANNOTATIONS_TYPES_AS_FOOTNOTES_DEFAULT));
812
  if (!empty($annotationsTypesAsFootnotes)) {
813
    $form['footnotes']['annotations_types_as_footnotes']['#default_value'] = $annotationsTypesAsFootnotes;
814
  }
815

    
816
  // --- Advanced Search --- //
817
  $form['asearch'] = array(
818
      '#type' => 'fieldset',
819
      '#title' => t('Advanced search'),
820
      '#collapsible' => FALSE,
821
      '#collapsed' => FALSE,
822
  );
823
  $form['asearch']['cdm_dataportal_show_advanced_search'] = array(
824
      '#type' => 'checkbox',
825
      '#title' => t('Show advanced search link'),
826
      '#default_value' => variable_get('cdm_dataportal_show_advanced_search', 1),
827
      '#description' => t('Check this box if the link to advanced search should be show below the search box.'),
828
  );
829

    
830
  // ---- Taxon Name Rendering --- //
831
  $form['taxon_name'] = array(
832
      '#type' => 'fieldset',
833
      '#title' => t('Taxon name display'),
834
      '#collapsible' => TRUE,
835
      '#collapsed' => TRUE,
836
      '#description' => t('The display of taxon names is configured by two parts.'
837
          . 'The <srong>name render templates</strong> define the parts of the name to be displayed in the different areas of the data portal pages.'
838
          . 'The name parts are defined in the <stong>part definitions</strong>'),
839
  );
840

    
841
  drupal_add_js(
842
      'jQuery(document).ready( function( ) {
843
         // pretty print json
844
         var json_text = jQuery(\'#edit-' . CDM_PART_DEFINITIONS . '\').val();
845
         var obj = JSON.parse(json_text);
846
         jQuery(\'#edit-' . CDM_PART_DEFINITIONS . '\').val(JSON.stringify(obj, undefined, 2));
847

    
848
         json_text = jQuery(\'#edit-' . CDM_NAME_RENDER_TEMPLATES . '\').val();
849
         obj = JSON.parse(json_text);
850
         jQuery(\'#edit-' . CDM_NAME_RENDER_TEMPLATES . '\').val(JSON.stringify(obj, undefined, 2));
851
       });'
852
      ,array(
853
          'type' => 'inline',
854
          'scope' => 'footer'
855
      )
856
  );
857

    
858
  $default_part_definitions = unserialize(CDM_PART_DEFINITIONS_DEFAULT);
859

    
860
  $form['taxon_name'][CDM_PART_DEFINITIONS] = array(
861
      '#type' => 'textarea',
862
      '#title' => t('Part definitions'),
863
      '#element_validate' => array('form_element_validate_json'),
864
      '#default_value' =>  json_encode(variable_get(CDM_PART_DEFINITIONS, $default_part_definitions)),
865
      '#description' => '
866
          <p>
867
          (Clearing the text area will reset it to the default)
868
          </p>
869
          <p>
870
           The part definitions define the specific parts of which a rendered taxon name plus additional information will consist.
871
          </p>
872
          <p>
873
           A full taxon name plus additional information can consist of the following elements:
874
          <ul>
875
             <li>name: the taxon name inclugin rank nbut without author</li>
876
             <li>authors:  The authors of a reference, also used in taxon names</li>
877
             <li>reference: the nomenclatural reference,</li>
878
             <li>microreference:  Volume, page number etc.</li>
879
             <li>status:  The nomenclatural status of a name</li>
880
             <li>description: name descriptions like protologues etc ...</li>
881
          </ul>
882
          </p>
883
          <p>
884
           These elements are combined in the part definitions array to from the specific parts to be rendered.
885
           (The taxon name "Lapsana communis L., Sp. Pl.: 811. 1753" shall be an example in the following)
886
           Usually the following parts are formed:
887
          <ul>
888
            <li>namePart: the name and rank (in example: "Lapsana communis")</li>
889
            <li>authorshipPart: the author (in example: "L.")</li>
890
            <li>nameAuthorPart: the combination of name and author part (in example: "Lapsana communis L.").</li>
891
               This is useful for zoological names where the authorshipPart belongs to the name and both should</li>
892
               be combined when a link to the taxon is rendered.</li>
893
            <li>referencePart: the nomencaltural reference (in example: "Sp. Pl. 1753")</li>
894
            <li>microreferencePart: usually the page number (in example ": 811.")</li>
895
            <li>statusPart: the nomenclatorical status</li>
896
            <li>descriptionPart: name descriptions like protologues etc ...</li>
897
          </ul>
898
          </p>
899
          <p>
900
           Each set of parts is dedicated to render a specific TaxonName type, the type names are used as keys for the
901
           specific parts part definitions:
902
          <ul>
903
            <li>BotanicalName</li>
904
            <li>ZoologicalName</li>
905
            <li>#DEFAULT: covers ViralNames and other NonViralNames
906
          </ul>
907
           An example:
908
          <pre>
909
           {
910
            "ZoologicalName": {
911
              "namePart": {
912
                "name": true
913
              },
914
              "referencePart": {
915
                "authors": true
916
              },
917
              "microreferencePart": {
918
                "microreference": true
919
              },
920
              "statusPart": {
921
                "status": true
922
              },
923
              "descriptionPart": {
924
                "description": true
925
              }
926
            },
927
            "BotanicalName": {
928
              "namePart": {
929
                "name": true,
930
                "authors": true
931
              },
932
              "referencePart": {
933
                "reference": true,
934
                "microreference": true
935
              },
936
              "statusPart": {
937
                "status": true
938
              },
939
              "descriptionPart": {
940
                "description": true
941
              }
942
            }
943
          }
944
           </pre>',
945
  );
946

    
947
  $default_render_templates = unserialize(CDM_NAME_RENDER_TEMPLATES_DEFAULT);
948

    
949
  $form['taxon_name'][CDM_NAME_RENDER_TEMPLATES] = array(
950
      '#type' => 'textarea',
951
      '#title' => t('Name render templates'),
952
      '#element_validate' => array('form_element_validate_json'),
953
      '#default_value' =>  json_encode(variable_get(CDM_NAME_RENDER_TEMPLATES, $default_render_templates)),
954
      '#description' => '
955
          <p>
956
          (Clearing the text area will reset it to the default)
957
          </p>
958
          <p>
959
          The render templates array contains one or more name render templates to be used within the page areas identified by the
960
          render path. The render path is used as key of the array sub subelements whereas the name render template array is set as value.
961
          The following render Path keys are curretly recognized:
962
          <ul>
963
            <li>list_of_taxa:</li>
964
            <li>acceptedFor:</li>
965
            <li>taxon_page_synonymy</li>
966
            <li>typedesignations</li>
967
            <li>taxon_page_title</li>
968
            <li>polytomousKey</li>
969
            <li>na: name + authorship</li>
970
            <li>nar:name + authorship + reference</li>
971
            <li>#DEFAULT</li>
972
          </ul>
973
          A single render template can be used for multiple render paths. In this case the according key of the render templates
974
          array element should be a comma separated list of render paths, without any whitespace!.
975
          </p>
976
          <p>
977
          A render template is an associative array. The keys of this array are referring to the keys as defined in the part
978
          definitions array. See <a href="#edit-cdm-part-definitions">Part definitions</a> above for more information.
979
          <p>
980
          The value of the render template element must be set to TRUE in order to let this part being rendered.
981
          The namePart, nameAuthorPart and referencePart can also hold an associative array with a single
982
          element: array(\'#uri\' => TRUE). The value of the #uri element will be replaced by the according
983
          links if the paramters $nameLink or $refenceLink are given to the name render function
984
          (this is hard coded and cannot be configured here).',
985
  );
986

    
987
  // @WA: D7 form api does not support reset buttons,
988
  // so to mimic the D5 reset button we add one like this.
989
  $form['actions']['reset'] = array(
990
    '#markup' => '<input id="reset" type="reset" class="form-submit" value="' . t('Reset to defaults') . '" />',
991
    '#weight' => 1000,
992
  );
993

    
994
  $form['#submit'] = array('submit_json_as_php_array');
995
  // #json_elements especially defined for submit_json_as_php_array()
996
  $form['#json_elements'] = array(CDM_NAME_RENDER_TEMPLATES, CDM_PART_DEFINITIONS);
997
  return system_settings_form($form);
998
}
999

    
1000

    
1001
/**
1002
 * @todo Please document this function.
1003
 * @see http://drupal.org/node/1354
1004
 */
1005
function cdm_dataportal_create_gallery_settings_form($form_name, $form_title, $collapsed, $form_description = '') {
1006
  $form[$form_name] = array(
1007
    '#type' => 'fieldset',
1008
    '#title' => t($form_title),
1009
    '#collapsible' => TRUE,
1010
    '#collapsed' => $collapsed,
1011
    '#tree' => TRUE,
1012
    '#description' => t($form_description),
1013
  );
1014

    
1015
  $default_values = unserialize(CDM_DATAPORTAL_GALLERY_SETTINGS);
1016
  $gallery_settings = variable_get($form_name, $default_values);
1017
  // $test = variable_get('cdm_dataportal_search_items_on_page', CDM_DATAPORTAL_SEARCH_ITEMS_ON_PAGE);
1018
  if ($form_name == CDM_DATAPORTAL_SEARCH_GALLERY_NAME) {
1019
    /*
1020
    TODO: why cdm_dataportal_search_items_on_page does not save the value on $test???
1021
    $form[$form_name]['cdm_dataportal_search_items_on_page'] = array(
1022
    '#type' => 'textfield',
1023
    '#title' => t('Search Page Size'),
1024
    '#default_value' => $test,
1025
    '#description' => t('Number of Names to display per page in search results.')
1026
    );
1027
    */
1028
    $form[$form_name]['cdm_dataportal_show_taxon_thumbnails'] = array(
1029
      '#type' => 'checkbox',
1030
      '#title' => t('Show media thumbnails for accepted taxa'),
1031
      '#default_value' => $gallery_settings['cdm_dataportal_show_taxon_thumbnails'],
1032
    );
1033

    
1034
    $form[$form_name]['cdm_dataportal_show_synonym_thumbnails'] = array(
1035
      '#type' => 'checkbox',
1036
      '#title' => t('Show media thumbnails for synonyms'),
1037
      '#default_value' => $gallery_settings['cdm_dataportal_show_synonym_thumbnails'],
1038
      '#description' => '',
1039
    );
1040
  }
1041

    
1042
  // $showCaption = variable_get('cdm_dataportal_findtaxa_show_thumbnail_captions', 0);
1043
  $form[$form_name]['cdm_dataportal_show_thumbnail_captions'] = array(
1044
    '#type' => 'checkbox',
1045
    '#title' => t('Show captions under thumbnails'),
1046
    '#default_value' => $gallery_settings['cdm_dataportal_show_thumbnail_captions'],
1047
    '#description' => '',
1048
  );
1049

    
1050
  $form[$form_name]['cdm_dataportal_media_maxextend'] = array(
1051
    '#type' => 'textfield',
1052
    '#title' => t('Thumbnail size') . ':',
1053
    '#default_value' => $gallery_settings['cdm_dataportal_media_maxextend'],
1054
    '#description' => t('Select the size of each individual thumbnail.'),
1055
  );
1056

    
1057
  if ($form_name != CDM_DATAPORTAL_MEDIA_GALLERY_NAME) {
1058
    $form[$form_name]['cdm_dataportal_media_cols'] = array(
1059
      '#type' => 'textfield',
1060
      '#title' => t('Number of columns') . ':',
1061
      '#default_value' => $gallery_settings['cdm_dataportal_media_cols'],
1062
      '#description' => t('Group the thumbnails in columns: select how many
1063
        columns the gallery should display.'),
1064
    );
1065
  }
1066

    
1067
  if ($form_name == CDM_DATAPORTAL_SEARCH_GALLERY_NAME) {
1068
    $form[$form_name]['cdm_dataportal_media_maxRows'] = array(
1069
      '#type' => 'textfield',
1070
      '#title' => t('Maximum number of rows') . ':',
1071
      '#default_value' => $gallery_settings['cdm_dataportal_media_maxRows'],
1072
      '#description' => t('You can group the thumbnails in rows, select in how
1073
        many rows should be the thumbnails grouped.<br/><strong>Note:</strong>
1074
        If you want an unlimited number of rows please set to 0.'),
1075
    );
1076
  }
1077

    
1078
  return $form;
1079
}
1080

    
1081
/**
1082
 * @todo document this function.
1083
 */
1084
function cdm_settings_layout_taxon() {
1085
  $collapsed = FALSE;
1086
  $form = array();
1087

    
1088
  $form['#submit'][] = 'cdm_settings_layout_taxon_submit';
1089

    
1090
  $form['cdm_dataportal_show_back_to_search_results'] = array(
1091
      '#type' => 'checkbox',
1092
      '#title' => t('Show <em>Back to search results</em> link at the taxon site.'),
1093
      '#default_value' => variable_get('cdm_dataportal_show_back_to_search_results', 1),
1094
      '#description' => t('<p>If checked the link to search results is rendered at
1095
       the top of the taxon site. Clicking on the link the last search performed
1096
       is rendered again.</p>'),
1097
  );
1098

    
1099
  // --------- TABBED TAXON ------- //
1100
  $form['taxon_tabs'] = array(
1101
    '#type' => 'fieldset',
1102
    '#title' => t('Taxon tabs'),
1103
    '#collapsible' => TRUE,
1104
    '#collapsed' => FALSE,
1105
    '#description' => t('If tabbed taxon page is enabled the taxon profile will
1106
      be splitted in four diferent tabs; General, Synonymy, Images and
1107
      Specimens. If the taxon has no information for any of the tabs/sections
1108
      such tab will be not displayed.'),
1109
  );
1110

    
1111
  $form['taxon_tabs']['cdm_dataportal_taxonpage_tabs'] = array(
1112
    '#type' => 'checkbox',
1113
    '#title' => t('Tabbed taxon page'),
1114
    '#default_value' => variable_get('cdm_dataportal_taxonpage_tabs', 1),
1115
    '#description' => t('<p>If selected split the taxon page into individual
1116
      tabs for description, images, synonymy and specimens. If not the taxon
1117
      data is rendered as a long single page without tabs.</p>'),
1118
  );
1119

    
1120
  $form['taxon_tabs']['cdm_taxonpage_tabs_visibility'] = array(
1121
    '#type' => 'checkboxes',
1122
    '#title' => t('Tabs visibility options') . ':',
1123
    '#default_value' => variable_get('cdm_taxonpage_tabs_visibility', get_taxon_options_list()),
1124
    '#options' => get_taxon_options_list(),
1125
    '#description' => t('Enable or disable Tabs in the Tabbed page display'),
1126
  );
1127

    
1128
  // WEIGHT
1129
  $taxontabs_weights = get_array_variable_merged('cdm_taxonpage_tabs_weight', CDM_TAXONPAGE_TAB_WEIGHT_DEFAULT);
1130
  $form['taxon_tabs']['cdm_taxonpage_tabs_weight'] = array(
1131
      '#tree' => true
1132
  );
1133
  // Weights range from -delta to +delta, so delta should be at least half
1134
  // of the amount of tabs present.
1135
  $tab_weight_delta = round(count(get_taxon_tabs_list()) / 2) + 1;
1136
  foreach (get_taxon_tabs_list() as $label) {
1137
    $key = strtolower($label); // turn in to string, since we need to use strings as keys
1138
    $form['taxon_tabs']['cdm_taxonpage_tabs_weight'][$key] = array(
1139
        '#title' => $label,
1140
        '#type'  => 'weight',
1141
        '#default_value' => $taxontabs_weights[$key],
1142
        '#delta' => $tab_weight_delta
1143
    );
1144
  }
1145

    
1146
  $form['taxon_tabs']['cdm_dataportal_default_tab'] = array(
1147
    '#type' => 'select',
1148
    '#title' => t('Default tab to display') . ':',
1149
    '#default_value' => variable_get('cdm_dataportal_default_tab', 0),
1150
    '#options' => unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB),
1151
    '#description' => t('<p>Select the default tab to display when visiting a
1152
      taxon page. Only available if Tabbed Taxon Page is enable.</p>
1153
      <strong>Note:</strong> After performing a search and clicking in any
1154
      synonym, the taxon tab to be rendered will be the synonymy of the accepted
1155
      taxon and not the above selected tab.'),
1156
  );
1157

    
1158
  /* ======  TAXON_PROFILE ====== */
1159
  $form['taxon_profile'] = array(
1160
    '#type' => 'fieldset',
1161
    '#title' => t('Taxon profile (tab)'),
1162
    '#description' => t('<p>This section covers the settings related to the taxon
1163
      profile tab, also known as the <strong>"General"</strong> tab.</p>'),
1164
    '#collapsible' => TRUE,
1165
    '#collapsed' => TRUE,
1166
  );
1167

    
1168
  // ---- PROFILE PICTURE ----//
1169

    
1170
  $form['taxon_profile'][CDM_TAXON_PROFILE_IMAGE] = array(
1171
    '#type' => 'fieldset',
1172
    '#tree' => TRUE,
1173
    '#title' => t('Taxon profile picture'),
1174
    '#collapsible' => TRUE,
1175
    '#collapsed' => FALSE,
1176
    '#description' => t('This sections allows configuring the display of the so called taxon profile image which is displayed in the taxon profile tab.'),
1177
  );
1178

    
1179
  //FIXME migrate variables:
1180
  //  cdm_dataportal_show_default_image ---> CDM_TAXON_PROFILE_IMAGE['show']
1181
  // FIXME
1182
  //  eanable file modul in profile and in update
1183

    
1184
  $taxon_profile_image_settings = variable_get(CDM_TAXON_PROFILE_IMAGE, unserialize(CDM_TAXON_PROFILE_IMAGE_DEFAULT));
1185
  /*
1186
   * 'show' => 1,
1187
   * 'maxextend' => 184,
1188
   * 'media_uri_query' => ''
1189
   * 'custom_placeholder_image_on' => 1,
1190
   * 'custom_placeholder_image_fid' => ''
1191
   */
1192
  $form['taxon_profile'][CDM_TAXON_PROFILE_IMAGE]['show'] = array(
1193
    '#type' => 'checkbox',
1194
    '#title' => t('Enable profil picture'),
1195
    '#description' => t('Show the profil picture.'),
1196
    '#default_value' => $taxon_profile_image_settings['show'],
1197
  );
1198

    
1199
  $form['taxon_profile'][CDM_TAXON_PROFILE_IMAGE]['maxextend'] = array(
1200
      '#type' => 'textfield',
1201
      '#tree' => TRUE,
1202
      '#title' => t('Profil picture maximum extend'),
1203
      '#default_value' =>  $taxon_profile_image_settings['maxextend'],
1204
      '#field_suffix' => 'px',
1205
      '#maxlength' => 4,
1206
      '#size' => 4,
1207
      '#description' => t('The maximum extend in either dimension, width or height, of the profil picture in pixels.')
1208
  );
1209

    
1210
  $form['taxon_profile'][CDM_TAXON_PROFILE_IMAGE]['media_uri_query'] = array(
1211
      '#type' => 'textfield',
1212
      '#tree' => TRUE,
1213
      '#title' => t('Additional URI query parameter'),
1214
      '#default_value' =>  $taxon_profile_image_settings['media_uri_query'],
1215
      '#maxlength' => 1024,
1216
      '#size' => 60,
1217
      '#description' => t('Additional query parameters to be used when requesting for the '
1218
          . 'profile image. E.g.: <code>width=400&height=300&quality=95&format=jpeg</code>.'
1219
          . 'The query parameters will be appendend to the uri of the media representation part'
1220
          . ' as stored in the cdm. The query parameter string must not start with a \'&\' or  \'?\'')
1221
  );
1222

    
1223
  $form['taxon_profile'][CDM_TAXON_PROFILE_IMAGE]['custom_placeholder_image_on'] = array(
1224
      '#type' => 'checkbox',
1225
      '#title' => t('Use a custom placeholder image'),
1226
      '#description' => t("This image is shown as replacement if no image of the taxon is available."),
1227
      '#default_value' => $taxon_profile_image_settings['custom_placeholder_image_on']
1228
  );
1229

    
1230
  if($taxon_profile_image_settings['custom_placeholder_image_on'] == 1){
1231
    $form['taxon_profile'][CDM_TAXON_PROFILE_IMAGE]['custom_placeholder_image_fid'] = array(
1232
        '#type' => 'managed_file',
1233
        '#title' => t('Custom placeholder image file'),
1234
        '#progress_indicator' => 'bar',
1235
        '#default_value' => $taxon_profile_image_settings['custom_placeholder_image_fid'],
1236
    //       '#name' => 'custom_placeholder_image',
1237
        '#upload_location' => 'public://' . CDM_TAXON_PROFILE_IMAGE .'/'
1238
    );
1239

    
1240
    if($taxon_profile_image_settings['custom_placeholder_image_fid']){
1241
      $profile_image_file = file_load($taxon_profile_image_settings['custom_placeholder_image_fid']);
1242
      $url = file_create_url($profile_image_file->uri);
1243
      $form['taxon_profile'][CDM_TAXON_PROFILE_IMAGE]['preview'] = array(
1244
                '#type' => 'item',
1245
                '#markup' => '<div class="image-preview"><img src="' . $url . '"/></div>',
1246
      );
1247
    }
1248
  } else {
1249
    $form['taxon_profile'][CDM_TAXON_PROFILE_IMAGE]['custom_placeholder_image_fid'] = array(
1250
        '#type' => 'hidden',
1251
        '#default_value' => $taxon_profile_image_settings['custom_placeholder_image_fid']
1252
    );
1253
  }
1254

    
1255

    
1256

    
1257
  $options = cdm_rankVocabulary_as_option();
1258
  array_unshift($options, '-- DISABLED --');
1259
  $form['taxon_profile']['picture']['image_hide_rank'] = array(
1260
    '#type' => 'select',
1261
    '#title' => t('Hide profile picture for higher ranks') . ':',
1262
    '#default_value' => variable_get('image_hide_rank', '0'),
1263
    '#options' => $options,
1264
    '#description' => t('The taxon profile picture will not be shown for taxa with rank higher that the selected.'),
1265
  );
1266

    
1267
  // -- MEDIA THUMBNAILS -- //
1268
  $form_name = CDM_DATAPORTAL_DESCRIPTION_GALLERY_NAME;
1269
  $form_title = 'Taxon Profile Images';
1270
  $form_description = '<p>The different section in the taxon  profile can have images associated with them. These images are displayed in a gallery of thumbnails wich can be configuered here:</p>';
1271
  $form['taxon_profile'][] = cdm_dataportal_create_gallery_settings_form($form_name, $form_title, $collapsed, $form_description);
1272

    
1273
  // ---- FEATURE TREE ---- //
1274
  $form['taxon_profile']['feature_trees'] = array(
1275
    '#type' => 'fieldset',
1276
    '#title' => t('Features'),
1277
    '#collapsible' => TRUE,
1278
    '#collapsed' => FALSE,
1279
    '#description' => t("This section covers settings related to the taxon's
1280
      <em>Feature Tree</em>. The <em>feature tree</em> are the taxon's
1281
      features such as description, distribution, common names, etc. that Drupal
1282
      will render at the taxon profile page."),
1283
  );
1284
  $featureTrees = cdm_get_featureTrees_as_options(TRUE);
1285
  $saved_uuid = variable_get(CDM_PROFILE_FEATURETREE_UUID, UUID_DEFAULT_FEATURETREE);
1286
  if(!isset($featureTrees['options'][$saved_uuid])) {
1287
    $saved_uuid = UUID_DEFAULT_FEATURETREE;
1288
  }
1289
  $form['taxon_profile']['feature_trees'][CDM_PROFILE_FEATURETREE_UUID] = array(
1290
    '#type' => 'radios',
1291
    '#title' => t('Taxon profile sections') . ':',
1292
    '#default_value' => $saved_uuid,
1293
    '#options' =>  $featureTrees['options'],
1294
    '#pre_render' => array('form_pre_render_conditional_form_element', 'radios_prepare_options_suffix'),
1295
    '#options_suffixes' => $featureTrees['treeRepresentations'],
1296
    '#description' => t('Select the Feature Tree to be displayed at the taxon
1297
      profile. Click "Show Details" to see the Feature Tree elements.'
1298
    ),
1299
  );
1300
  $featureTrees = cdm_get_featureTrees_as_options();
1301
  $saved_uuid = variable_get(CDM_DATAPORTAL_STRUCTURED_DESCRIPTION_FEATURETREE_UUID, UUID_DEFAULT_FEATURETREE);
1302
  if(!isset($featureTrees['options'][$saved_uuid])) {
1303
    $saved_uuid = NULL;
1304
  }
1305
  $form['taxon_profile']['feature_trees'][CDM_DATAPORTAL_STRUCTURED_DESCRIPTION_FEATURETREE_UUID] = array(
1306
    '#type' => 'radios',
1307
    '#title' => t('Natural language representation of structured descriptions') . ':',
1308
    '#default_value' => $saved_uuid,
1309
    '#options' => $featureTrees['options'],
1310
    '#pre_render' => array('form_pre_render_conditional_form_element', 'radios_prepare_options_suffix'),
1311
    '#options_suffixes' => $featureTrees['treeRepresentations'],
1312
    '#description' => t('Taxon descriptions can be stored in a highly structured
1313
      form. The feature tree selected here will be used to generate textual
1314
      representation in natural language.'
1315
    ),
1316
  );
1317

    
1318
  // ---- LAYOUT PER FEATURE ---- //
1319
  $feature_tree = get_profile_featureTree();
1320
  if (isset($feature_tree->root->childNodes)) {
1321

    
1322
    $form_feature_list_layout = array(
1323
      '#title' => t('Taxon profile layout'),
1324
      '#collapsible' => TRUE,
1325
      '#collapsed' => FALSE,
1326
      '#type' => 'fieldset',
1327
      '#description' => t('Will be available in a future release.'),
1328
    );
1329

    
1330
    $feature_list_layout_settings_disabled = TRUE;
1331
    foreach ($feature_tree->root->childNodes as $featureNode) {
1332

    
1333
      if (!$feature_list_layout_settings_disabled && isset($featureNode->feature)) {
1334
        // Must not exceed 45 characters !!!
1335
        $subform_id = LAYOUT_SETTING_PREFIX . $featureNode->feature->uuid;
1336

    
1337
        $settings = mixed_variable_get($subform_id, FEATURE_TREE_LAYOUT_DEFAULTS);
1338
        $systemDefaults = unserialize(FEATURE_TREE_LAYOUT_DEFAULTS);
1339

    
1340
        $form_feature_list_layout[$subform_id] = array(
1341
          '#tree' => TRUE,
1342
          '#title' => 'test' . $featureNode->feature->representation_L10n,
1343
          '#collapsible' => FALSE,
1344
          '#collapsed' => FALSE,
1345
          '#type' => 'fieldset',
1346
          '#description' => t(''),
1347
        );
1348

    
1349
        $form_feature_list_layout[$subform_id]['enabled'] = array(
1350
          '#type' => 'checkbox',
1351
          '#title' => t('Enable'),
1352
          '#default_value' => $settings['enabled'],
1353
          '#description' => t('Enable user defined layout for this feature'),
1354
        );
1355

    
1356
        $form_feature_list_layout[$subform_id]['enclosingTag'] = array(
1357
          '#type' => 'textfield',
1358
          '#title' => t('Enclosing tag'),
1359
          '#disabled' => !$settings['enabled'],
1360
          '#default_value' => $settings['enclosingTag'],
1361
          '#description' => t('Default is: ') . "'<code>" . $systemDefaults['enclosingTag'] . "</code>'",
1362
        );
1363

    
1364
        $form_feature_list_layout[$subform_id]['entryEnclosingTag'] = array(
1365
          '#type' => 'textfield',
1366
          '#title' => t('Entry enclosing tag'),
1367
          '#disabled' => !$settings['enabled'],
1368
          '#default_value' => $settings['entryEnclosingTag'],
1369
          '#description' => t('Default is: ') . "'<code>" . $systemDefaults['entryEnclosingTag'] . "</code>'",
1370
        );
1371

    
1372
        $form_feature_list_layout[$subform_id]['glue'] = array(
1373
          '#type' => 'textfield',
1374
          '#title' => t('Glue'),
1375
          '#disabled' => !$settings['enabled'],
1376
          '#default_value' => $settings['glue'],
1377
          '#description' => t('Default is: ') . "'<code>" . $systemDefaults['glue'] . "</code>'",
1378
        );
1379

    
1380
      }
1381

    
1382
      $form['taxon_profile']['feature_list_layout'] = $form_feature_list_layout;
1383
    }
1384
  }
1385

    
1386
  // ---- DISTRIBUTION LAYOUT ---- //
1387
  $form['taxon_profile']['distribution_layout'] = array(
1388
    '#title' => t('Distribution'),
1389
    '#collapsible' => TRUE,
1390
    '#collapsed' => FALSE,
1391
    '#type' => 'fieldset',
1392
    '#description' => t('Select if you want to sort or not the distribution text
1393
      located below the distribution map.'),
1394
  );
1395

    
1396
  $form['taxon_profile']['distribution_layout']['distribution_sort'] = array(
1397
    '#type' => 'radios',
1398
    '#title' => t('Sort') . ':',
1399
    '#default_value' => variable_get('distribution_sort', 'NO_SORT'),
1400
    '#options' => array(
1401
      'NO_SORT' => t('Standard (No sort)'),
1402
      'HIDE_TDWG2' => t('Sorted without TDWG Level 2'),
1403
    ),
1404
  );
1405

    
1406
  $form['taxon_profile']['distribution_layout'][DISTRIBUTION_TEXTDATA_DISPLAY_ON_TOP] = array(
1407
    '#type' => 'checkbox',
1408
    '#title' => t('Show TextData elements on top of the map'),
1409
    '#default_value' => variable_get(DISTRIBUTION_TEXTDATA_DISPLAY_ON_TOP, 0),
1410
    '#description' => t('Check this if you want to appear all <code>TextData</code>
1411
      elements on top of the map. Otherwise all <code>TextData</code>
1412
      distribution elements will be listed below the other area elements.
1413
      This option is useful if you need to have descriptive texts for each
1414
      distribution map.'),
1415
  );
1416

    
1417

    
1418
  /* ====== SYNONYMY ====== */
1419
  $form['taxon_synonymy'] = array(
1420
    '#type' => 'fieldset',
1421
    '#title' => t('Taxon synonymy (tab)'),
1422
    '#collapsible' => TRUE,
1423
    '#collapsed' => TRUE,
1424
    '#description' => t('This section covers the settings related to the taxon
1425
      <strong>synonymy</strong> tab.'),
1426
  );
1427

    
1428
  $form['taxon_synonymy']['cdm_dataportal_nomref_in_title'] = array(
1429
    '#type' => 'checkbox',
1430
    '#title' => t('Show accepted taxon on top of the synonymy'),
1431
    '#default_value' => variable_get('cdm_dataportal_nomref_in_title', CDM_DATAPORTAL_NOMREF_IN_TITLE),
1432
    '#description' => t('If checked, the first homotypic taxon is a repetition
1433
      of the accepted taxon most likely with the full nomenclatural reference
1434
      (depending on the currently chosen theme).'),
1435
  );
1436

    
1437
  $form['taxon_synonymy']['cdm_dataportal_display_is_accepted_for'] = array(
1438
    '#type' => 'checkbox',
1439
    '#title' => t('Display <em>is accepted for ...</em> on taxon pages when
1440
      coming from a synonym link.'),
1441
    '#default_value' => variable_get('cdm_dataportal_display_is_accepted_for', CDM_DATAPORTAL_DISPLAY_IS_ACCEPTED_FOR),
1442
    '#description' => t('Check this if after doing a search and clicking on a
1443
      synonym you want to see the "accept of" text for the accepted synonym.'),
1444
  );
1445

    
1446
  $nameRelationshipTypeOptions = cdm_Vocabulary_as_option(UUID_NAME_RELATIONSHIP_TYPE);
1447
  $form['taxon_synonymy']['name_relationships']['name_relationships_to_show'] = array(
1448
    '#type' => 'checkboxes',
1449
    '#title' => t('Display name relationships') . ':',
1450
    '#default_value' => variable_get('name_relationships_to_show', 0),
1451
    '#options' => $nameRelationshipTypeOptions,
1452
    '#description' => t('Select the name relationships you want to show for the
1453
      accepted taxa.'),
1454
  );
1455

    
1456
  $form['taxon_synonymy'][CDM_DATAPORTAL_DISPLAY_TAXON_RELATIONSHIPS] = array(
1457
    '#type' => 'checkbox',
1458
    '#title' => t('Show taxon relations ships of accepted taxon'),
1459
    '#default_value' => variable_get(CDM_DATAPORTAL_DISPLAY_TAXON_RELATIONSHIPS, CDM_DATAPORTAL_DISPLAY_TAXON_RELATIONSHIPS_DEFAULT),
1460
    '#description' => t('If this option is enabled the synonymy will show the
1461
      below selected taxon relationships of accepted taxa.'),
1462
  );
1463

    
1464
  $taxonRelationshipTypeOptions = cdm_Vocabulary_as_option(UUID_TAXON_RELATIONSHIP_TYPE, '_cdm_relationship_type_term_label_callback');
1465
  $form['taxon_synonymy'][CDM_TAXON_RELATIONSHIP_TYPES] = array(
1466
    '#type' => 'checkboxes',
1467
    '#title' => t('Taxon relationship types') . ':',
1468
    '#description' => t('Only taxon relationships of the selected type will be
1469
      displayed'),
1470
    '#options' => $taxonRelationshipTypeOptions,
1471
    '#default_value' => variable_get(CDM_TAXON_RELATIONSHIP_TYPES, unserialize(CDM_TAXON_RELATIONSHIP_TYPES_DEFAULT)),
1472
    '#disabled' => !variable_get(CDM_DATAPORTAL_DISPLAY_TAXON_RELATIONSHIPS, CDM_DATAPORTAL_DISPLAY_TAXON_RELATIONSHIPS_DEFAULT),
1473
  );
1474

    
1475
  // ====== SPECIMENS ====== //
1476
  $form['taxon_specimens'] = array(
1477
    '#type' => 'fieldset',
1478
    '#title' => t('Taxon specimens (tab)'),
1479
    '#collapsible' => TRUE,
1480
    '#collapsed' => TRUE,
1481
    '#description' => t('This section covers the settings related to the taxon
1482
      <strong>specimens</strong> tab.'),
1483
  );
1484

    
1485
  $featureTrees = cdm_get_featureTrees_as_options(TRUE);
1486
  $saved_uuid = variable_get(CDM_OCCURRENCE_FEATURETREE_UUID, UUID_DEFAULT_FEATURETREE);
1487
  if(!isset($featureTrees['options'][$saved_uuid])) {
1488
    $saved_uuid = UUID_DEFAULT_FEATURETREE;
1489
  }
1490
  $form['taxon_specimens']['feature_trees'][CDM_OCCURRENCE_FEATURETREE_UUID] = array(
1491
      '#type' => 'radios',
1492
      '#title' => t('Specimen description feature tree') . ':',
1493
      '#default_value' => $saved_uuid,
1494
      '#options' =>  $featureTrees['options'],
1495
      '#pre_render' => array('form_pre_render_conditional_form_element', 'radios_prepare_options_suffix'),
1496
      '#options_suffixes' => $featureTrees['treeRepresentations'],
1497
      '#description' => t('Select the feature tree to be used for displaying specimen descriptions. Click "Show Details" to see the Feature Tree elements.'
1498
      ),
1499
  );
1500

    
1501
  $form_name = CDM_DATAPORTAL_SPECIMEN_GALLERY_NAME;
1502
  $form_title = t('Specimen media');
1503
  $form_description = t('Specimens may have media which is displayed at the
1504
     Specimen tab/section as a gallery. It is possible to configure the
1505
     thumbnails gallery here, however for configuring how a single media should
1506
     be displayed please go to !url.</p>',
1507
     array(
1508
       '!url' => l(t('Layout -> Media'), 'admin/config/cdm_dataportal/settings/layout/media'),
1509
     ));
1510
  $form['taxon_specimens'][] = cdm_dataportal_create_gallery_settings_form($form_name, $form_title, FALSE, $form_description);
1511

    
1512
  // --- MEDIA GALLERY ---- //
1513
  $form_name = CDM_DATAPORTAL_TAXON_MEDIA_GALLERY_NAME_TAB;
1514
  $form_title = 'Media gallery (tab)';
1515
  $form_description = '<p>This section covers the settings related to the taxon <strong>media</strong> tab.
1516
   Taxa may have media (usually images) and they are as thumbnails displayed. It is possible to configure
1517
   the thumbnails gallery here, however for configuring how a single media should be displayed please go to
1518
   <a href="./?q=admin/settings/cdm_dataportal/layout/media">Layout -&gt; Media</a></p>
1519
   <p><strong>Note:</strong> These settings are only taken into account when the standard
1520
   gallery viewer is selected at <a href="./?q=admin/settings/cdm_dataportal/layout/media">Layout -&gt; Media</a>.</p>';
1521
  $form['taxon_media'][] = cdm_dataportal_create_gallery_settings_form($form_name, $form_title, TRUE, $form_description);
1522

    
1523
  // Comment @WA: D7 form api does not support reset buttons,
1524
  // so to mimic the D5 reset button we add one like this.
1525
  $form['actions']['reset'] = array(
1526
    '#markup' => '<input id="reset" type="reset" class="form-submit" value="' . t('Reset to defaults') . '" />',
1527
    '#weight' => 1000,
1528
  );
1529
  return system_settings_form($form);
1530
}
1531

    
1532
/**
1533
 * @todo document this function.
1534
 */
1535
function cdm_settings_layout_search() {
1536

    
1537
  $form = array();
1538

    
1539
  $form['#submit'][] = 'cdm_settings_layout_search_submit';
1540

    
1541
  $form['search_settings'] = array(
1542
    '#type' => 'fieldset',
1543
    '#title' => t('Taxa Search'),
1544
    '#collapsible' => FALSE,
1545
    '#collapsed' => FALSE,
1546
    '#description' => t('<p>The data portal allows the users to perform searchs.</p><p>To perform searchs
1547
         the block <em>CDM Taxon Search</em> should be enabled and visible for users
1548
         where they can write the text to be searched. You can find Drupal block configuration
1549
         site at <a href="./?q=admin/build/block">Administer&#45&#62Site building&#45&#62Blocks</a></p> '),
1550
  );
1551

    
1552
  $form['search_settings']['simple_search_ignore_classification'] = array(
1553
      '#type' => 'checkbox',
1554
      '#title' => t('Ignore the chosen classification in simple search'),
1555
      '#default_value' => variable_get('simple_search_ignore_classification', TRUE),
1556
      '#description' => t('The simple search, which can be executed via the search block,
1557
          will by default search on all classifications. Remove the tick if you want your
1558
          portal to search on the classification selected in the classification browser
1559
          selector.'),
1560
  );
1561

    
1562
  $form['search_settings']['cdm_dataportal_search_items_on_page'] = array(
1563
    '#type' => 'textfield',
1564
    '#title' => t('Results per page') . ':',
1565
    '#default_value' => variable_get('cdm_dataportal_search_items_on_page', CDM_DATAPORTAL_SEARCH_ITEMS_ON_PAGE),
1566
    '#description' => t('Number of results to display per page.'),
1567
  );
1568

    
1569
  $search_mode_default = get_array_variable_merged(CDM_SEARCH_TAXA_MODE, CDM_SEARCH_TAXA_MODE_DEFAULT);
1570
  $form['search_settings']['cdm_search_taxa_mode'] = array(
1571
      '#type' => 'checkboxes',
1572
      '#title' => 'Search mode',
1573
      '#description' => 'The taxon search can operate in different modes in order to find only taxa, synonyms,
1574
          taxa by its common name and even taxa which have been used as misappied names. The settings made here will affect the default
1575
          for the advance search form and the behaviour of the simple search form which always will behave according to the
1576
          defaults set here.',
1577
      '#options' => drupal_map_assoc(array_keys(unserialize(CDM_SEARCH_TAXA_MODE_DEFAULT))),
1578
      '#default_value' => $search_mode_default
1579
      );
1580

    
1581
  // --- SEARCH TAXA GALLERY ---- //
1582
  $items = variable_get('cdm_dataportal_search_items_on_page', CDM_DATAPORTAL_SEARCH_ITEMS_ON_PAGE);
1583
  $collapsed = FALSE;
1584
  $form_name = CDM_DATAPORTAL_SEARCH_GALLERY_NAME;
1585
  $form_title = 'Taxa Search thumbnails';
1586
  $form_description = 'Search results may show thumbnails. ';
1587
  $form[] = cdm_dataportal_create_gallery_settings_form($form_name, $form_title, $collapsed, $form_description);
1588

    
1589
  // Comment @WA: D7 form api does not support reset buttons,
1590
  // so to mimic the D5 reset button we add one like this.
1591
  $form['actions']['reset'] = array(
1592
    '#markup' => '<input id="reset" type="reset" class="form-submit" value="' . t('Reset to defaults') . '" />',
1593
    '#weight' => 1000,
1594
  );
1595
  return system_settings_form($form);
1596
}
1597

    
1598
/**
1599
 * @todo document this function.
1600
 */
1601
function cdm_settings_layout_media() {
1602

    
1603
  $form = array();
1604

    
1605
  $form['media_settings'] = array(
1606
    '#type' => 'fieldset',
1607
    '#title' => t('Media settings'),
1608
    '#collapsible' => FALSE,
1609
    '#collapsed' => FALSE,
1610
    '#description' => 'This section covers layout settings for media pages.'
1611
      . 'Further media related settings may be found under the taxon layout settings and on the general settings.',
1612
  );
1613

    
1614
  $form['media_settings']['image_gallery_viewer'] = array(
1615
    '#type' => 'select',
1616
    '#title' => t('Image viewer') . ':',
1617
    '#default_value' => variable_get('image_gallery_viewer', 'default'),
1618
    '#options' => array(
1619
      'default' => t('Standard image viewer'),
1620
      'fsi' => t('FSI viewer (requires FSI server!)'),
1621
    ),
1622
  );
1623

    
1624
  // --- MEDIA GALLERY ---- //
1625
  $form_name = CDM_DATAPORTAL_MEDIA_GALLERY_NAME;
1626
  $form_title = 'Standard viewer';
1627
  $form_description = '<p>Configure the standard image viewer.</p><p><strong>Note:</strong> the image viewer should selected otherwise settings are not taking into account.</p>';
1628
  // $form[] = cdm_dataportal_create_gallery_settings_form($form_name, $form_title, $collapsed);
1629
  $form['media_settings'][] = cdm_dataportal_create_gallery_settings_form($form_name, $form_title, FALSE, $form_description);
1630

    
1631
  // @WA: D7 form api does not support reset buttons,
1632
  // so to mimic the D5 reset button we add one like this.
1633
  $form['actions']['reset'] = array(
1634
    '#markup' => '<input id="reset" type="reset" class="form-submit" value="' . t('Reset to defaults') . '" />',
1635
    '#weight' => 1000,
1636
  );
1637
  return system_settings_form($form);
1638
}
1639

    
1640
/**
1641
 * GEOSERVICE and Map settings.
1642
 */
1643
function cdm_settings_geo($form, &$form_state) {
1644

    
1645
  $current_geoserver_settings = get_edit_map_service_settings();
1646
  $map_distribution = get_array_variable_merged(CDM_MAP_DISTRIBUTION, CDM_MAP_DISTRIBUTION_DEFAULT);
1647
  // The default layer must always be enabled
1648
  $preferred_layer = $map_distribution['openlayers']['base_layers']['PREFERRED'];
1649
  $map_distribution['openlayers']['base_layers'][$preferred_layer] = $preferred_layer;
1650

    
1651
  $form = array();
1652

    
1653
  $dummy_distribution_query = NULL;
1654
  if($map_distribution['map_type'] != 1){
1655
    // we need to apply a dummy query since the map serice requires for image maps
1656
    // at least as and ad to be defined
1657
    $dummy_distribution_query = "as=a:339966&ad=tdwg1:a:1,2,3,4,5,6,7,8,9";
1658
  }
1659
  $form['map_preview'] = array(
1660
      '#type' => 'fieldset',
1661
      '#tree' => FALSE,
1662
      '#title' => t('Map preview'),
1663
      '#collapsible' => FALSE,
1664
      '#description' => 'The preview of the map'
1665
       . ($dummy_distribution_query != null ?
1666
           ' may not be accurate in case if image maps, please check the map display in the taxon pages.':
1667
           '.<br/>Hold down Strg and drag with your mouse to select a bbox to zoom to. <br/>The bbox of the visible area of the map is always displayed below the map.')
1668
  );
1669
  $form['map_preview']['map'] = compose_map(NULL, $dummy_distribution_query, NULL,
1670
      array(
1671
          'move' => "this.cdmOpenlayersMap.printInfo",
1672
          '#execute' => "this.cdmOpenlayersMap.printInfo"
1673
      )
1674
  );
1675

    
1676

    
1677
  /*
1678
   * GEO SERVER
1679
   */
1680
  $form['edit_map_server'] = array(
1681
    '#type' => 'fieldset',
1682
    '#tree' => true,
1683
    '#title' => t('EDIT map service'),
1684
    '#collapsible' => TRUE,
1685
    '#collapsed' => TRUE,
1686
    '#description' => t('Configuration and selection of your geo server.
1687
      The Geo Server is responsible for generating the maps.'),
1688
  );
1689

    
1690
  $form['edit_map_server']['base_uri'] = array(
1691
    '#type' => 'select',
1692
    '#title' => t('EDIT map service') . ':',
1693
    '#default_value' => $current_geoserver_settings['base_uri'],
1694
    '#options' => unserialize(EDIT_MAPSERVER_URI),
1695
    '#description' => t('Select the EDIT map server you want to use within your data portal.'),
1696
  );
1697
  $form['edit_map_server']['version'] = array(
1698
      '#type' => 'select',
1699
      '#title' => t('Version') . ':',
1700
      '#default_value' => $current_geoserver_settings['version'],
1701
      '#options' => unserialize(EDIT_MAPSERVER_VERSION),
1702
      '#description' => t('The version of the EDIT map services'),
1703
  );
1704

    
1705
  $localhostkey = 'ABQIAAAAFho6eHAcUOTHLmH9IYHAeBRi_j0U6kJrkFvY4-OX2XYmEAa76BTsyMmEq-tn6nFNtD2UdEGvfhvoCQ';
1706
  $gmap_api_key = variable_get('gmap_api_key', 'ABQIAAAAFho6eHAcUOTHLmH9IYHAeBRi_j0U6kJrkFvY4-OX2XYmEAa76BTsyMmEq-tn6nFNtD2UdEGvfhvoCQ');
1707
  $form['gmap_api_key'] = array(
1708
      '#type' => 'textfield',
1709
      '#title' => t('Google maps API key') . ':',
1710
      '#default_value' => variable_get('gmap_api_key', $gmap_api_key),
1711
      '#description' => t('If you want to use the Google Maps Layer, a key is
1712
      needed. If you need a key, visit
1713
      <a href="http://code.google.com/intl/en/apis/maps/signup.html">google maps api key</a>.
1714
      <br/><strong>Note:</strong> The following key: <code>!localhostkey</code>
1715
      is the default key for the localhost (127.0.0.1).',
1716
      array('!localhostkey' => $localhostkey)),
1717
  );
1718

    
1719

    
1720
  /*
1721
   * MAP SETTINGS
1722
   */
1723

    
1724
  $form[CDM_MAP_DISTRIBUTION] = array(
1725
    '#type' => 'fieldset',
1726
    '#tree' => TRUE,
1727
    '#title' => t('Maps settings'),
1728
    '#collapsible' => TRUE,
1729
    '#collapsed' => TRUE,
1730
    '#description' => t('General configuration for all map types.'),
1731
  );
1732

    
1733
  /*
1734
   * settings for the distribution map are used also for specimens map!!!!
1735
   */
1736

    
1737
  $form[CDM_MAP_DISTRIBUTION]['width'] = array(
1738
    '#type' => 'textfield',
1739
    '#title' => 'Width',
1740
    '#default_value' => $map_distribution['width'],
1741
    '#maxlength' => 4,
1742
    '#size' => 4,
1743
    '#description' => 'Width of the map. To allow OSM baselayers to zoom out to the full extend of the world the map width must be
1744
      a multiple of 256px since the osm tiles from tile.openstreetmap.org have a size of 256px x 256px and frational zoom
1745
      levels are not possible in this case.',
1746
  );
1747
  $form[CDM_MAP_DISTRIBUTION]['height'] = array(
1748
      '#type' => 'textfield',
1749
      '#title' => 'Height',
1750
      '#default_value' => $map_distribution['height'],
1751
      '#maxlength' => 4,
1752
      '#size' => 4,
1753
      '#description' => 'Height of the map. Depending on the chosen base layer you may want to choose the height equal
1754
      to the width or half of the width. Any other aspect ratio is also possible if desired.',
1755
  );
1756

    
1757
  $form[CDM_MAP_DISTRIBUTION]['bbox'] = array(
1758
    '#type' => 'textfield',
1759
    '#title' => 'Bounding box',
1760
    '#default_value' => $map_distribution['bbox'],
1761
    '#description' => t('The bounding box (left, bottom, right, top) defines the area to be initially displayed in maps.
1762
      Use "-180,-90,180,90" for the whole world. Leave <strong>empty</strong>
1763
      to let the map <strong>automatically zoom</strong> to the bounds enclosing the shown data.</p>
1764
      <strong>TIP: </strong>You can use the map preview above to choose a bbox from the map. Maybe you need to change the map type to OpeLayers.
1765
      Hold down Strg and drag with your mouse to select a bbox to zoom to. The bbox of the visible area of the map is always displayed
1766
      below the map from where you can copy the bbox string.</p>'),
1767
  );
1768

    
1769
  $form[CDM_MAP_DISTRIBUTION]['show_labels'] = array(
1770
    '#type' => 'checkbox',
1771
    '#title' => 'Display area labels',
1772
    '#default_value' => $map_distribution['show_labels'],
1773
    '#description' => t('The map will show name labels of the areas'),
1774
  );
1775

    
1776
  $form[CDM_MAP_DISTRIBUTION]['caption'] = array(
1777
    '#type' => 'textfield',
1778
    '#title' => 'Map caption',
1779
    '#default_value' => $map_distribution['caption'],
1780
    '#description' => t('The caption will be shown below the map.'),
1781
  );
1782

    
1783
  $form[CDM_MAP_DISTRIBUTION]['distribution_opacity'] = array(
1784
    '#type' => 'textfield',
1785
    '#title' => 'Distribution layer opacity',
1786
    '#default_value' => $map_distribution['distribution_opacity'],
1787
    '#description' => t('Valid values range from 0.0 to 1.0. Value 1.0 means the distributions (the countries or regions) will
1788
                           fully visible, while a value near to 0.0 will be not much visible.'),
1789
  );
1790

    
1791
  $form[CDM_MAP_DISTRIBUTION]['map_type'] = array(
1792
    '#type' => 'radios',
1793
    '#title' => 'Map types',
1794
    '#options' => array(
1795
      1 => "OpenLayers dynamic map viewer",
1796
      0 => "Plain image",
1797
    ),
1798
    '#default_value' => $map_distribution['map_type'],
1799
    '#description' => 'Two different map types are available :
1800
      <ul><li><em>OpenLayers</em>: Display the maps in an interactive viewer
1801
      which allows zooming and panning. If enabled you can configure the default layer
1802
      (background of your maps) below.</li>
1803
      <li><em>Plain image</em>: The map will be static non interactive
1804
      image.</li></ul>',
1805
  );
1806
  $open_layers_is_enabled = $map_distribution['map_type'] == 1;
1807

    
1808

    
1809
  // --- Plain Image Settings --- //
1810
  $form[CDM_MAP_DISTRIBUTION]['image_map'] = array(
1811
    '#type' => 'fieldset',
1812
    '#title' => 'Plain image map settings',
1813
    '#tree' => TRUE,
1814
    '#collapsible' => TRUE,
1815
    '#collapsed' => $open_layers_is_enabled,
1816
    '#description' => 'The settings in this section are still expertimental
1817
      and can only be used with the EDIT map service version 1.1 or above.',
1818
  );
1819
  $edit_mapserver_version = get_edit_map_service_version_number();
1820
  if ($edit_mapserver_version < 1.1) {
1821
    $form[CDM_MAP_DISTRIBUTION]['image_map']['#description'] = '<div class="messages warning">' . t("The chosen EDIT map service version ($edit_mapserver_version) is too low, it must be at least 1.1") . '</div>'
1822
      . $form[CDM_MAP_DISTRIBUTION]['image_map']['#description'];
1823
  }
1824

    
1825
  $form[CDM_MAP_DISTRIBUTION]['image_map']['base_layer'] = array(
1826
    '#type' => 'textfield',
1827
    '#title' => 'Background layer',
1828
    '#default_value' => $map_distribution['image_map']['base_layer'],
1829
    '#description' => t('Background layer. For available layers inspect !url1 or !url2.', array(
1830
      '!url1' => l('deegree-csw', 'http://edit.africamuseum.be:8080/deegree-csw/md_search.jsp'),
1831
      '!url2' => l('geoserver layers', 'http://edit.africamuseum.be/geoserver/web/'),
1832
    )),
1833
  );
1834

    
1835
  $form[CDM_MAP_DISTRIBUTION]['image_map']['bg_color'] = array(
1836
    '#type' => 'textfield',
1837
    '#title' => 'Background color',
1838
    '#default_value' => $map_distribution['image_map']['bg_color'],
1839
  );
1840

    
1841
  $form[CDM_MAP_DISTRIBUTION]['image_map']['layer_style'] = array(
1842
    '#type' => 'textfield',
1843
    '#title' => 'Background layer style',
1844
     // Only line color by now.
1845
    '#default_value' => $map_distribution['image_map']['layer_style'],
1846
    '#description' => 'Syntax: {Area fill color},{Area stroke color},{Area stroke width},{Area stroke dash style}',
1847
  );
1848

    
1849
  $form[CDM_MAP_DISTRIBUTION]['image_map']['projection'] = array(
1850
      '#type' => 'textfield',
1851
      '#title' => 'Projection',
1852
      '#default_value' => drupal_array_get_nested_value($map_distribution, array('image_map', 'projection')),
1853
      '#description' => 'Spatial Reference System (SRS) identifier ) optional ( Defines projections in WMS GetMap request.
1854
        Using EPSG:4326 (WGS84 lat/long) is the default but can be changed
1855
        on-the-fly to different UTM and much more zone specific. Examples: EPSG:4326, EPSG:900913, EPSG:3857, EPSG:7777777',
1856
  );
1857

    
1858

    
1859
  // --- OpenLayers Settings --- //
1860
  $form[CDM_MAP_DISTRIBUTION]['openlayers'] = array(
1861
    '#type' => 'fieldset',
1862
    '#title' => 'OpenLayers settings',
1863
    '#tree' => TRUE,
1864
    '#collapsible' => TRUE,
1865
    '#collapsed' => !$open_layers_is_enabled,
1866
    '#description' => '',
1867
  );
1868

    
1869

    
1870
  $form[CDM_MAP_DISTRIBUTION]['openlayers']['display_outside_max_extent'] = array(
1871
      '#type' => 'checkbox',
1872
      '#title' => 'Display outside max extent',
1873
      '#default_value' => $map_distribution['openlayers']['display_outside_max_extent'],
1874
      '#description' => t('Allows the map to display parts of the layers which are outside
1875
         the max extent if the aspect ratio of the map and of the baselayer
1876
         are not equal.'),
1877
  );
1878

    
1879

    
1880
  $form[CDM_MAP_DISTRIBUTION]['openlayers']['show_layer_switcher'] = array(
1881
      '#type' => 'checkbox',
1882
      '#title' => 'Show Layer Switcher',
1883
      '#default_value' => $map_distribution['openlayers']['show_layer_switcher'],
1884
      '#description' => 'The Layer Switcher control displays a table of contents
1885
      for the map.  This allows the user interface to switch between
1886
      base layers and to show or hide overlays.  By default the switcher is
1887
      shown minimized on the right edge of the map, the user may expand it
1888
      by clicking on the handle.',
1889
  );
1890

    
1891
  if (!$open_layers_is_enabled) {
1892
    $form[CDM_MAP_DISTRIBUTION]['openlayers']['#description'] = '<div class="messages warning">'
1893
        . 'The Openlayers viewer is currently not enabled! (see section Maps settings above )</div>'
1894
        . $form[CDM_MAP_DISTRIBUTION]['openlayers']['#description'];
1895
  }
1896

    
1897
  $baselayer_options = array(
1898
    /*
1899
   NOTICE: must correspond to the layers defined in
1900
   js/openlayers_,ap.js#getLayersByName()
1901
   */
1902
    'osgeo_vmap0' => "Metacarta Vmap0 (OSGeo server)", // EPSG:4326: EPSG:900913
1903
    'metacarta_vmap0' => "Metacarta Vmap0 (MetaCarta Labs server)", // EPSG:4326, EPSG:900913
1904
    // all others EPSG:900913
1905
    // 'edit-vmap0_world_basic' => 'EDIT Vmap0',
1906
    'edit-etopo1' => "ETOPO1 Global Relief Model",
1907
    'mapnik' => 'OpenStreetMap',
1908
    'mapquest_open' => "MapQuest",
1909
    'mapquest_sat' => "MapQuest Sattelite",
1910
//     'osmarender' => 'OpenStreetMap (Tiles@home)',
1911
    'gmap' => 'Google Streets',
1912
    'gsat' => 'Google Satellite',
1913
    'ghyb' => 'Google Hybrid',
1914
//     'veroad' => 'Virtual Earth Roads',
1915
//     'veaer' => 'Virtual Earth Aerial',
1916
//     'vehyb' => 'Virtual Earth Hybrid',
1917
    // 'yahoo' => 'Yahoo Street',
1918
    // 'yahoosat' => 'Yahoo Satellite',
1919
    // 'yahoohyb' => 'Yahoo Hybrid',
1920
     'custom_wms_base_layer_1' => 'Custom WMS base layer (needs to be manually configured below!)',
1921
  );
1922

    
1923
  $form[CDM_MAP_DISTRIBUTION]['openlayers']['base_layers'] = array(
1924
    '#type' => 'checkboxes_preferred',
1925
    '#title' => 'Base Layers',
1926
    '#options' => $baselayer_options,
1927
    '#default_value' =>  $map_distribution['openlayers']['base_layers'],
1928
    '#description' => 'Choose the baselayer layer you prefer to use as map background in the OpenLayers dynamic mapviewer.',
1929
  );
1930

    
1931
  $form[CDM_MAP_DISTRIBUTION]['openlayers']['custom_wms_base_layer'] = array(
1932
      '#type' => 'fieldset',
1933
      '#title' => 'Custom WMS base layer',
1934
      '#tree' => TRUE,
1935
      '#collapsible' => FALSE,
1936
      '#collapsed' => FALSE,
1937
      '#description' => 'Here you an define a custom wms layer as additional base layer.',
1938
  );
1939

    
1940
  $form[CDM_MAP_DISTRIBUTION]['openlayers']['custom_wms_base_layer']['name'] = array(
1941
      '#type' => 'textfield',
1942
      '#title' => 'Layer name',
1943
      // Only line color by now.
1944
      '#default_value' => $map_distribution['openlayers']['custom_wms_base_layer']['name'],
1945
      '#description' => 'A arbitrary name for the layer.',
1946
  );
1947
  $form[CDM_MAP_DISTRIBUTION]['openlayers']['custom_wms_base_layer']['url'] = array(
1948
      '#type' => 'textfield',
1949
      '#title' => 'WMS url',
1950
      // Only line color by now.
1951
      '#default_value' => $map_distribution['openlayers']['custom_wms_base_layer']['url'],
1952
      '#description' => 'Base url for the WMS (e.g.  http://wms.jpl.nasa.gov/wms.cgi)'
1953
  );
1954
  $form[CDM_MAP_DISTRIBUTION]['openlayers']['custom_wms_base_layer']['params'] = array(
1955
      '#type' => 'textarea',
1956
      '#title' => 'WMS parameters',
1957
      '#element_validate' => array('form_element_validate_json'),
1958
      // Only line color by now.
1959
      '#default_value' => $map_distribution['openlayers']['custom_wms_base_layer']['params'],
1960
      '#description' => 'An javasript object with key/value pairs representing the GetMap query string parameters and parameter values, entered in valid JSON. For example:
1961
<pre> {
1962
  "Layers": "topp:em_tiny_jan2003",
1963
  "Format": "image/png",
1964
  "BGCOLOR": "0xe0faff"
1965
}
1966
</pre>'
1967
  );
1968
  $form[CDM_MAP_DISTRIBUTION]['openlayers']['custom_wms_base_layer']['projection'] = array(
1969
      '#type' => 'textfield',
1970
      '#title' => 'Projection',
1971
      // Only line color by now.
1972
      '#default_value' => $map_distribution['openlayers']['custom_wms_base_layer']['projection'],
1973
      '#description' => 'The desired projection for the layer (e.g. EPSG:4326, EPSG:900913, EPSG:3857)'
1974
  );
1975
  $form[CDM_MAP_DISTRIBUTION]['openlayers']['custom_wms_base_layer']['proj4js_def'] = array(
1976
      '#type' => 'textfield',
1977
      '#maxlength' => 256,
1978
      '#title' => 'proj4js definition',
1979
      // Only line color by now.
1980
      '#default_value' => $map_distribution['openlayers']['custom_wms_base_layer']['proj4js_def'],
1981
      '#description' => 'The <a href="http://trac.osgeo.org/openlayers/wiki/Documentation/Dev/proj4js">proj4js definition</a> for the projection named above.
1982
            The definitions for
1983
            EPSG:102067, EPSG:102757, EPSG:102758, EPSG:21781, EPSG:26591, EPSG:26912, EPSG:27200, EPSG:27563, EPSG:3857,
1984
            EPSG:41001, EPSG:4139, EPSG:4181, EPSG:42304, EPSG:4272, EPSG:4302, EPSG:900913
1985
            are already predefined and must be added here again.  If your dont know the defintion of your desired projection,
1986
            go to  <a href="http://spatialreference.org/">http://spatialreference.org/</a>, search for your projection and
1987
            choose to display the proj4js definition string.
1988
            <h5>Quick Reference on the commion proj4js definition parameters:</h5>
1989
            <pre>
1990
+a         Semimajor radius of the ellipsoid axis
1991
+alpha     ? Used with Oblique Mercator and possibly a few others
1992
+axis      Axis orientation (new in 4.8.0)
1993
+b         Semiminor radius of the ellipsoid axis
1994
+datum     Datum name (see `proj -ld`)
1995
+ellps     Ellipsoid name (see `proj -le`)
1996
+k         Scaling factor (old name)
1997
+k_0       Scaling factor (new name)
1998
+lat_0     Latitude of origin
1999
+lat_1     Latitude of first standard parallel
2000
+lat_2     Latitude of second standard parallel
2001
+lat_ts    Latitude of true scale
2002
+lon_0     Central meridian
2003
+lonc      ? Longitude used with Oblique Mercator and possibly a few others
2004
+lon_wrap  Center longitude to use for wrapping (see below)
2005
+nadgrids  Filename of NTv2 grid file to use for datum transforms (see below)
2006
+no_defs   Don\'t use the /usr/share/proj/proj_def.dat defaults file
2007
+over      Allow longitude output outside -180 to 180 range, disables wrapping (see below)
2008
+pm        Alternate prime meridian (typically a city name, see below)
2009
+proj      Projection name (see `proj -l`)
2010
+south     Denotes southern hemisphere UTM zone
2011
+to_meter  Multiplier to convert map units to 1.0m
2012
+towgs84   3 or 7 term datum transform parameters (see below)
2013
+units     meters, US survey feet, etc.
2014
+vto_meter vertical conversion to meters.
2015
+vunits    vertical units.
2016
+x_0       False easting
2017
+y_0       False northing
2018
+zone      UTM zone
2019
            </pre>
2020
          For the full reference please refer to <a href="http://trac.osgeo.org/proj/wiki/GenParms">http://trac.osgeo.org/proj/wiki/GenParms</a>.'
2021
  );
2022
  $form[CDM_MAP_DISTRIBUTION]['openlayers']['custom_wms_base_layer']['max_extent'] = array(
2023
      '#type' => 'textfield',
2024
      '#title' => 'Maximum extent',
2025
      // Only line color by now.
2026
      '#default_value' => $map_distribution['openlayers']['custom_wms_base_layer']['max_extent'],
2027
      '#description' => 'The maximum extent of the map as bounding box (left, bottom, right, top) in the units of the map.'
2028
  );
2029
  $form[CDM_MAP_DISTRIBUTION]['openlayers']['custom_wms_base_layer']['units'] = array(
2030
      '#type' => 'textfield',
2031
      '#title' => 'Units',
2032
      '#default_value' => $map_distribution['openlayers']['custom_wms_base_layer']['units'],
2033
      '#description' => 'The layer map units.  Defaults to null.  Possible values are ‘degrees’ (or ‘dd’), ‘m’, ‘ft’, ‘km’, ‘mi’, ‘inches’.  Normally taken from the projection.  Only required if both map and layers do not define a projection, or if they define a projection which does not define units.'
2034
  );
2035

    
2036
  /*
2037
   * Map Legend
2038
   */
2039
  $form[CDM_MAP_DISTRIBUTION]['legend'] = array(
2040
    '#type' => 'fieldset',
2041
    '#title' => 'Map legend',
2042
    '#tree' => TRUE,
2043
    '#collapsible' => TRUE,
2044
    '#collapsed' => TRUE,
2045
    '#description' => 'Configure the maps legend.',
2046
  );
2047

    
2048
  $form[CDM_MAP_DISTRIBUTION]['legend']['show'] = array(
2049
    '#type' => 'checkbox',
2050
    '#title' => 'Display a map legend',
2051
    '#default_value' => $map_distribution['legend']['show'],
2052
    '#description' => 'Check this if you like a legend to be displayed with the maps.',
2053
  );
2054

    
2055
  $form[CDM_MAP_DISTRIBUTION]['legend']['opacity'] = array(
2056
    '#type' => 'textfield',
2057
    '#title' => 'Legend opacity',
2058
    '#default_value' => $map_distribution['legend']['opacity'],
2059
    '#description' => 'Valid values range from 0.0 to 1.0. Value 1.0 means the legend will be fully visible, while a value near
2060
                         to 0.0 will be not much visible.',
2061
  );
2062

    
2063
  $form[CDM_MAP_DISTRIBUTION]['legend']['font_size'] = array(
2064
    '#type' => 'textfield',
2065
    '#title' => 'Font size',
2066
    '#default_value' => $map_distribution['legend']['font_size'],
2067
    '#description' => 'Font size in pixels.',
2068
  );
2069

    
2070
  $fontStyles = array(
2071
    0 => "plane",
2072
    1 => "italic",
2073
  );
2074
  $form[CDM_MAP_DISTRIBUTION]['legend']['font_style'] = array(
2075
    '#type' => 'select',
2076
    '#title' => 'Available font styles',
2077
    '#default_value' => $map_distribution['legend']['font_style'],
2078
    '#options' => $fontStyles,
2079
    '#description' => 'Select a font style for the map legend.',
2080
  );
2081

    
2082
  $form[CDM_MAP_DISTRIBUTION]['legend']['icon_width'] = array(
2083
    '#type' => 'textfield',
2084
    '#title' => 'Icon width',
2085
    '#default_value' => $map_distribution['legend']['icon_width'],
2086
    '#description' => 'Legend icon width in pixels.',
2087
  );
2088
  $form[CDM_MAP_DISTRIBUTION]['legend']['icon_height'] = array(
2089
    '#type' => 'textfield',
2090
    '#title' => 'Icon height',
2091
    '#default_value' => $map_distribution['legend']['icon_height'],
2092
    '#description' => 'Legend icon height in pixels.',
2093
  );
2094

    
2095
  // @WA: D7 form api does not support reset buttons,
2096
  // so to mimic the D5 reset button we add one like this.
2097
  $form['actions']['reset'] = array(
2098
    '#markup' => '<input id="reset" type="reset" class="form-submit" value="' . t('Reset to defaults') . '" />',
2099
    '#weight' => 1000,
2100
  );
2101

    
2102
  return system_settings_form($form);
2103
}
2104

    
2105
/**
2106
 * @todo document this function.
2107
 */
2108
function cdm_settings_cache() {
2109

    
2110
  $form = array();
2111

    
2112
  $form['cache_settings'] = array(
2113
    '#type' => 'fieldset',
2114
    '#title' => t('Cache Settings'),
2115
    '#collapsible' => FALSE,
2116
    '#collapsed' => FALSE,
2117
    '#description' => t('<p>When caching is enabled all single taxon sites are
2118
      stored in an internal drupal cache doing the portal response of taxa pages
2119
      faster. This is possible because the sites are loaded from the cache and
2120
      are not created from scratch.</p>'),
2121
  );
2122

    
2123
  $form['cache_settings']['cdm_webservice_cache'] = array(
2124
    '#type' => 'checkbox',
2125
    '#title' => t('<strong>Enable caching</strong>'),
2126
    '#options' => cdm_help_general_cache(),
2127
    '#default_value' => variable_get('cdm_webservice_cache', 1),
2128
    '#description' => t('<p>Enable drupal to load taxa pages from the cache.</p>
2129
       <p><strong>Note:</strong> If taxa are modified by the editor or any other
2130
       application the changes will be not visible till the cache is erased.
2131
       Therefore developers should deactived this feature when they are working
2132
       on the CDM Dataportal Module.</p>'),
2133
  );
2134

    
2135
  $form['cache_settings']['cdm_run_cache'] = array(
2136
    '#markup' => cdm_view_cache_site(),
2137
  );
2138

    
2139
  // @WA: D7 form api does not support reset buttons,
2140
  // so to mimic the D5 reset button we add one like this.
2141
  $form['actions']['reset'] = array(
2142
    '#markup' => '<input id="reset" type="reset" class="form-submit" value="' . t('Reset to defaults') . '" />',
2143
    '#weight' => 1000,
2144
  );
2145
  return system_settings_form($form);
2146
}
2147

    
2148
/**
2149
 * Walk and cache all taxon pages.
2150
 */
2151
function cdm_view_cache_site() {
2152

    
2153
  $out = '';
2154

    
2155
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/cache_all_taxa.js');
2156

    
2157
  $request_params = array();
2158
  $request_params['class'] = "Taxon";
2159

    
2160
  $cdm_ws_page_taxa_url = cdm_compose_url(CDM_WS_TAXON . ".json", NULL, queryString($request_params));
2161
  $cdm_ws_page_taxa_url = uri_uriByProxy($cdm_ws_page_taxa_url);
2162
  $cdm_ws_page_taxa_url = rtrim($cdm_ws_page_taxa_url, '/');
2163

    
2164
  $out .= t('<p><strong>Cache all taxon pages</strong></p>');
2165
  $out .= '<p>When you launch the cache process the cache is filled and ready to be enabled.<br/>
2166
  Remember that when you load the taxa from the cache last changes on taxa will be not visible till you erase
2167
  the cache and fill it again.</p>';
2168
  $out .= '<p>Before  running the cache bot you have to empty the cache manually.</p>';
2169

    
2170
  $out .= '<div>' . t('This caching process may take long time and could cause heavy load on your server') . '</div>';
2171
  $out .= '<div id="progress"></div>';
2172

    
2173
  // Comment @WA: A form within a form is not valid html and not needed here.
2174
  // Also, it would be recommended just to include this part of the form in the
2175
  // rest of the form array in cdm_settings_cache().
2176
  // $out .= '<form id="cache_site">';
2177
  $out .= '<input type="hidden" name="pageTaxaUrl" value="' . $cdm_ws_page_taxa_url . '"/>';
2178
  $out .= '<input type="hidden" name="taxonPageUrl" value="' . url('cdm_dataportal/taxon/') . '"/>';
2179
  $out .= '<input type="button" name="start" value="' . t('Start') . '"/>';
2180
  $out .= '<input type="button" name="stop" value="' . t('Stop') . '"/>';
2181
  // $out .= '</form>';
2182
  $out .= '</div>';
2183
  /*
2184
  foreach($taxonPager->records as $taxon){
2185
    cdm_dataportal_taxon_view($uuid);
2186
  }
2187
  */
2188
  return $out;
2189
}
2190

    
2191

    
2192
function cdm_settings_layout_taxon_submit($form, &$form_state){
2193
  if (isset($form_state['values'][CDM_TAXON_PROFILE_IMAGE]['custom_placeholder_image_fid'])) {
2194
    $file = file_load($form_state['values'][CDM_TAXON_PROFILE_IMAGE]['custom_placeholder_image_fid']);
2195
    if(is_object($file)){
2196
      $file->status = FILE_STATUS_PERMANENT;
2197
      file_save($file);
2198
      file_usage_add($file, 'cdm_dataportal', CDM_TAXON_PROFILE_IMAGE, 0);
2199
    }
2200
  }
2201
  // rebuild the menu if the show tabs setting has changed, otherwise the change will not have a consistent effect
2202
  if(variable_get('cdm_dataportal_taxonpage_tabs', 1) != $form_state['values']['cdm_dataportal_taxonpage_tabs']){
2203
    // we first need to set the variable to persist the changes setting
2204
    variable_set('cdm_dataportal_taxonpage_tabs', $form_state['values']['cdm_dataportal_taxonpage_tabs']);
2205
    menu_rebuild();
2206
  }
2207
}
2208

    
2209
function cdm_settings_layout_search_submit($form, &$form_state){
2210
  // the visibility of media thumbnails also affects the ui of the search results
2211
  // so reset the according session variable
2212
  //    1. in order to give the user immediate
2213
  //       feedback on potential setting changes
2214
  //    2. let refresh the default if it has changed
2215
  if (isset($_SESSION['pageoption']['searchtaxa']['showThumbnails'])) {
2216
    unset($_SESSION['pageoption']['searchtaxa']['showThumbnails']);
2217
  }
2218
}
2219

    
2220
/**
2221
 * Form validation handler for cdm_settings_general
2222
 *
2223
 * Comment @WA: currently this handler is not used.
2224
 * It seems partly for cdm_settings_general en partly for cdm_settings_cache?
2225
 * Then you can change the name into cdm_settings_general_validate() or
2226
 * cdm_settings_cache_validate().
2227
 * But cdm_api_secref_cache_clear is not doing anything (yet)?
2228
 */
2229
function cdm_settings_general_validate($form, &$form_state) {
2230

    
2231
  if (!str_endsWith($form_state['values']['cdm_webservice_url'], '/')) {
2232
    $form_state['values']['cdm_webservice_url'] .= '/';
2233
  }
2234

    
2235
}
2236

    
2237
/**
2238
 * Form validation handler for cdm_settings_cache
2239
 */
2240
function cdm_settings_cache_validate($form, &$form_state) {
2241
  if ($form_state['values']['cdm_webservice_cache'] != variable_get('cdm_webservice_cache', 1)) {
2242
    cache_clear_all(NULL, 'cache_cdm_ws');
2243
    // Better clear secref_cache since I can not be sure if the cache has not
2244
    // be used during this response.
2245
    cdm_api_secref_cache_clear();
2246
  }
2247

    
2248
}
2249

    
2250
/**
2251
 * Returns an associative array of the currently chosen settings for the EDIT map service or the defaults as
2252
 * specified in EDIT_MAPSERVER_URI_DEFAULT and EDIT_MAPSERVER_VERSION_DEFAULT:
2253
 *  - base_uri: the protocol and host part , e.g.: http://edit.africamuseum.be
2254
 *  - version: the version, e.g.: v1.1
2255
 *
2256
 * @return array
2257
 *    An associative array of the currently chosen settings for the EDIT map service or the defaults.
2258
 */
2259
function get_edit_map_service_settings() {
2260

    
2261
  $settings = variable_get('edit_map_server', array(
2262
      'base_uri' => EDIT_MAPSERVER_URI_DEFAULT,
2263
      'version' => EDIT_MAPSERVER_VERSION_DEFAULT
2264
      )
2265
  );
2266
  // replace old non tree like settings by default
2267
  // TODO to be removed after release 3.1.5
2268
  if(!is_array($settings)){
2269
    variable_del('edit_map_server');
2270
    return get_edit_map_service_settings();
2271
  }
2272

    
2273
  return $settings;
2274
}
2275

    
2276
/**
2277
 * Returns the full edit map service URI e.g.: http://edit.africamuseum.be/edit_wp5/v1.1
2278
 *
2279
 * @return string
2280
 *   The full edit map service URI e.g.: http://edit.africamuseum.be/edit_wp5/v1.1
2281
 */
2282
function get_edit_map_service_full_uri() {
2283
  $settings = get_edit_map_service_settings();
2284
  return $settings['base_uri'] . EDIT_MAPSERVER_PATH .  '/' . $settings['version'];
2285
}
2286

    
2287

    
2288
/**
2289
 * Returns the version number of the currently selected edit mapserver as a float
2290
 *
2291
 * @return float
2292
 *   The version number of the currently selected edit mapserver as a float.
2293
 *   Returns 0 on error.
2294
 */
2295
function get_edit_map_service_version_number() {
2296

    
2297
  $pattern = '/v([\d\.]+).*$/';
2298

    
2299
  $settings = get_edit_map_service_settings();
2300
  preg_match($pattern, $settings['version'], $matches, PREG_OFFSET_CAPTURE);
2301
  if (isset($matches[1])) {
2302
    // Convert string to float.
2303
    $version = 1 + $matches[1][0] - 1;
2304
    return $version;
2305
  }
2306
  else {
2307
    // Report error.
2308
    drupal_set_message(t(" Invalid EDIT map service version number: '!version'",
2309
        array(
2310
          '!version' => $settings['version'],
2311
          'warning')
2312
        )
2313
      );
2314
    return 0;
2315
  }
2316
}
2317

    
2318
/**
2319
 * Returns the array of selected items in a options array
2320
 *
2321
 * @param array $options
2322
 *   An options array as generated by a form element like checkoxes, select ...,
2323
 */
2324
function get_selection($options) {
2325
  $selection = array();
2326
  foreach ($options as $key=>$val) {
2327
    if (!empty($val)) {
2328
      $selection[] = $val;
2329
    }
2330
  }
2331
  return $selection;
2332
}
2333

    
2334

    
2335
/**
2336
 * Implements hook_element_info().
2337
 *
2338
 * Allows modules to declare their own Form API element types and specify their default values.
2339
 *
2340
 * @see http://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_element_info/7
2341
 */
2342
function cdm_dataportal_element_info() {
2343
  $type['checkboxes_preferred'] = array(
2344
    '#input' => TRUE,
2345
    '#process' => array('checkboxes_preferred_expand'),
2346
    '#after_build' => array('checkboxes_preferred_after_build'),
2347
    '#theme' => array('checkboxes_preferred'),
2348
    // '#theme_wrapper' => array('form_element'),
2349
  );
2350
  return $type;
2351
}
2352

    
2353
/**
2354
 * #process callback function for the custom form element type 'checkbox_preferred'
2355
 *
2356
 *
2357
 */
2358
function checkboxes_preferred_expand($element, &$form_state, $form) {
2359

    
2360
  // First of all create checkboxes for each of the elements
2361
  $element = form_process_checkboxes($element);
2362

    
2363
  // compose the element name
2364
  $parents = array();
2365
  array_deep_copy($element['#parents'], $parents);
2366
  $parents[count($parents) -1 ] .= '_preferred';
2367
  $element_name = $parents[0];
2368
  for ($i=1; $i < count($parents); $i++){
2369
    $element_name .= '[' . $parents[$i] . ']';
2370
  }
2371

    
2372
  $children = element_children($element);
2373

    
2374
  $element['table_start'] = array(
2375
    '#markup' => '<table class="checkboxes_preferred"><tr><th></th><th>' . t('Enabled') . '</th><th>' . t('Default') . '</th></tr>',
2376
    '#weight' => -1,
2377
  );
2378

    
2379
  // prepare first part each of the table rows which contains the row label
2380
  $weight = 0;
2381
  foreach ($children as $key) {
2382
    $odd_even = $weight % 4 == 0 ? 'odd' : 'even';
2383
    $element[$key]['#weight'] = $weight;
2384
    $element[$key]['#prefix'] = '<tr class="' . $odd_even . '"><td>' . t($element['#options'][$key]) . '</td><td>';
2385
    $element[$key]['#suffix'] = '</td>';
2386
    unset($element[$key]['#title']);
2387
    $weight += 2;
2388
  }
2389
  $weight = 0;
2390

    
2391
  // add a radio button to each of the checkboxes, the
2392
  // check boxes have already been created at the beginning
2393
  // of this function
2394
  if (count($element['#options']) > 0) {
2395
    foreach ($element['#options'] as $key => $choice) {
2396
      if (!isset($element[$key . '_preferred'])) {
2397
        $element[$key . '_preferred'] = array(
2398
          '#type' => 'radio',
2399
          '#name' => $element_name,
2400
          '#return_value' => check_plain($key),
2401
          '#default_value' => empty($element['#default_value_2']) ? NULL : $element['#default_value_2'],
2402
          '#attributes' => $element['#attributes'],
2403
          '#parents' => $element['#parents'],
2404
          // '#spawned' => TRUE,
2405
          '#weight' => $weight + 1,
2406
          '#prefix' => '<td>',        // add a prefix to start a new table cell
2407
          '#suffix' => '</td></tr>',  // add a prefix to close the tabel row
2408
        );
2409
      }
2410
      $weight += 2;
2411
    }
2412
  }
2413

    
2414
  // end the table
2415
  $element['table_end'] = array(
2416
    '#markup' => '</table>',
2417
    '#weight' => $weight++,
2418
  );
2419

    
2420
  return $element;
2421
}
2422

    
2423
/**
2424
 * Theme function for the custom form field 'checkboxes_preferred'.
2425
 */
2426
function theme_checkboxes_preferred($variables) {
2427
  $element = $variables['element'];
2428
  $out = '<div id="edit-baselayers-wrapper" class="form-item">';
2429
  $out .= '<label for="edit-baselayers">' . $element['#title'] . '</label>';
2430
  $out .= drupal_render_children($element);
2431
  $out .= '<div class="description">' . $element['#description'] . '</div>';
2432
  $out .= '</div>';
2433
  return $out;
2434
}
2435

    
2436
/**
2437
 * Callback for checkboxes preferred for widget which will
2438
 * be called after the form or element is built. The call
2439
 * back is configured in the form element by setting it as
2440
 * #after_build parameter.
2441
 *
2442
 * @see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#after_build
2443
 *
2444
 * @param $element
2445
 *   Nested array of form elements that comprise the form.
2446
 * @param $form_state
2447
 *   A keyed array containing the current state of the form.
2448
 *   This includes the current persistent storage data for the form.
2449
 *   Additional information, like the sanitized $_POST data,
2450
 *   is also accumulated here in $form_state['input']
2451
 *
2452
 * @return the modified form array
2453
 */
2454
function checkboxes_preferred_after_build($element, &$form_state) {
2455

    
2456
  $parent_id = $element['#parents'][count($element['#parents']) - 1];
2457

    
2458
  if ($_POST && count($_POST) > 0) {
2459
    // TODO use  $form_state['input'] instead of POST !!!
2460
    // First pass of form processing.
2461
    $parents = array();
2462
    array_deep_copy($element['#parents'], $parents);
2463
    $parents[count($parents) - 1] .= '_preferred';
2464
    $preferred_layer = drupal_array_get_nested_value($_POST, $parents);
2465
    $element['#value']['PREFERRED'] = $preferred_layer;
2466
//     $form_state[$parent_id] = $element['#value'];
2467
//     $form_state['values']['baselayers'] = $element['#value'];
2468
    $form_state_element_values = &drupal_array_get_nested_value($form_state['values'], $element['#parents']);
2469
    $form_state_element_values = $element['#value'];
2470
  }
2471
  else {
2472
    // Second pass of form processing.
2473
    $preferred_layer = $element['#value']['PREFERRED'];
2474
  }
2475

    
2476
  // Also set the chosen value (not sure if this is good Drupal style ....).
2477
  foreach ($children = element_children($element) as $key) {
2478
    if (!empty($element[$key]['#type']) && $element[$key]['#type'] == 'radio') {
2479
      $element[$key]['#value'] = $preferred_layer;
2480
    }
2481
  }
2482
  // The default layer must always be enabled.
2483
  $element[$preferred_layer]['#value'] = $preferred_layer;
2484

    
2485
  return $element;
2486
}
2487

    
2488
function radios_prepare_options_suffix(&$elements){
2489

    
2490
  $childrenKeys = element_children($elements);
2491
  foreach($childrenKeys as $key){
2492
    if(!is_array($elements[$key]['#theme_wrappers'])){
2493
      $elements[$key]['#theme_wrappers'] = array();
2494
    }
2495
    if(isset($elements['#options_suffixes'][$key])){
2496
      $elements[$key]['#theme_wrappers'][] = 'radio_options_suffix';
2497
      $elements[$key]['#options_suffix'] = $elements['#options_suffixes'][$key];
2498
    }
2499
  }
2500
  return $elements;
2501

    
2502
}
2503

    
2504
/**
2505
 * TODO
2506
 * @param unknown $variables
2507
 */
2508
function theme_radio_options_suffix($variables) {
2509
  $element = $variables['element'];
2510
  if(isset($element['#options_suffix'])) {
2511
    $element['#children'] .= $element['#options_suffix'];
2512
  }
2513
  return $element['#children'];
2514
}
2515

    
2516

    
2517
/**
2518
 * Element validate callback for text field and arrays containing json.
2519
 *
2520
 * @param $element
2521
 *   The form element to validate
2522
 * @param $form_state
2523
 *   A keyed array containing the current state of the form.
2524
 * @param $form
2525
 *   Nested array of form elements that comprise the form.
2526
 */
2527
function form_element_validate_json($element, &$form_state, $form) {
2528
   if (!empty($element['#value'])) {
2529
     json_decode($element['#value']);
2530
     if(json_last_error() != JSON_ERROR_NONE){
2531
       form_error($element, t('The form element %title contains invalid JSON. You can check the syntax with ', array('%title' => $element['#title'])) . l('JSONLint', 'http://jsonlint.com/'));
2532
     }
2533
   }
2534
}
2535

    
2536
/**
2537
 * Form submission handler for textareas and textfields containing JSON.
2538
 *
2539
 * The contained JSON will be converted into an php array
2540
 * or object and will be stored in the variables as such.
2541
 *
2542
 * @see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#submit
2543
 *
2544
 * @param $form
2545
 *   Nested array of form elements that comprise the form.
2546
 * @param $form_state
2547
 *   A keyed array containing the current state of the form.
2548
 *
2549
 */
2550
function submit_json_as_php_array($form, &$form_state) {
2551
  if (is_array($form['#json_elements'])) {
2552
    foreach ($form['#json_elements'] as $element){
2553
      if (trim($form_state['values'][$element])) {
2554
        $form_state['values'][$element] = (array) json_decode($form_state['values'][$element]);
2555
      } else {
2556
        $form_state['values'][$element] = NULL;
2557
      }
2558
    }
2559
  }
2560
}
(14-14/14)