Project

General

Profile

Download (105 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
define ('CDM_TAXONTREE_INCLUDES', 'taxontree_includes');
11

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

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

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

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

    
35

    
36

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

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

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

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

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

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

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

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

    
124
}
125

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

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

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

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

    
253
define('CDM_DISTRIBUTION_FILTER', 'cdm_distribution_filter');
254
define('CDM_DISTRIBUTION_FILTER_DEFAULT', serialize(
255
      array(
256
      'filter_rules' => array(
257
        'statusOrderPreference' => 0,
258
        'subAreaPreference' => 0,
259
      ),
260
      'hideMarkedAreas' => array()
261
     )
262
));
263

    
264

    
265
define('CDM_TAXON_MEDIA_FILTER', 'cdm_taxon_media_filter');
266
define('CDM_TAXON_MEDIA_FILTER_DEFAULT', serialize(
267
    array(
268
        'includeTaxonDescriptions' => 'includeTaxonDescriptions',
269
        'includeOccurrences' => 0,
270
        'includeTaxonNameDescriptions' => 0
271
     )
272
  ));
273

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

    
319
/**
320
 * Merges the named array variable with the array of defaults.
321
 *
322
 * IḾPORTANT: The array keys must be strings. When the keys are integers
323
 * the merging will not take place for these enties. Number keyed enties
324
 * are just appended to the result array.
325
 *
326
 * @param string $variable_name
327
 *     The variable name
328
 * @param string | array $default
329
 *     The array containing the default values either as array or serialized as string.
330
 *     Unserialization is cared for if nessecary
331
 * @return array
332
 *     The merged array as returnd by drupal_array_merge_deep()
333
 */
334
function get_array_variable_merged($variable_name, $default){
335

    
336
    // unserialize if nessecary
337
    if(!is_array($default)){
338
      $default = unserialize($default);
339
    }
340
    $variable = variable_get($variable_name, array());
341
    $result = drupal_array_merge_deep($default, $variable);
342
    return $result;
343
}
344

    
345
/**
346
 * @todo document this function.
347
 */
348
function getGallerySettings($gallery_config_form_name) {
349
  return get_array_variable_merged($gallery_config_form_name, CDM_DATAPORTAL_GALLERY_SETTINGS);
350
}
351

    
352
/**
353
 * Returns the string representation of the default tab.
354
 *
355
 * @param bool $returnTabIndex
356
 *   Defaults to FALSE, if set true this function will return the index number
357
 *   of the default tab. (used to supply default values to form elements).
358
 */
359
function get_default_taxon_tab($returnTabIndex = FALSE) {
360

    
361
  global $user;
362
  $values = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
363
  $user_tab_active = 'cdm_dataportal_' . $user->uid . '_default_tab_active';
364
  $user_tab = 'cdm_dataportal_' . $user->uid . '_default_tab';
365
  // Get the user value if the used has chosen to overwrite the system settings.
366
  $user_tab_on = variable_get($user_tab_active, FALSE);
367
  if ($user_tab_on) {
368
    $user_value = variable_get($user_tab, 0);
369
    $index_value = $user_value;
370
    // Get the system value.
371
  }
372
  else {
373
    $system_value = variable_get('cdm_dataportal_default_tab', 0);
374
    $index_value = $system_value;
375
  }
376

    
377
  // Return the index value or the string representation.
378
  if ($returnTabIndex) {
379
    return $index_value;
380
  }
381
  else {
382
    return ($values[$index_value]);
383
  }
384

    
385
}
386

    
387
/**
388
 * @todo Please document this function.
389
 * @see http://drupal.org/node/1354
390
 */
391
function cdm_dataportal_menu_admin(&$items) {
392
  // Display section on admin/config page.
393
  $items['admin/config/cdm_dataportal'] = array(
394
    'title' => 'CDM Dataportal',
395
    'description' => 'Settings for the CDM DataPortal.',
396
    'position' => 'right',
397
    'weight' => 10,
398
    'page callback' => 'system_admin_menu_block_page',
399
    'access arguments' => array('administer cdm_dataportal'),
400
    'file' => 'system.admin.inc',
401
    'file path' => drupal_get_path('module', 'system'),
402
  );
403
  $items['admin/config/cdm_dataportal/settings'] = array(
404
    'title' => 'Settings',
405
    'description' => 'Settings for the CDM DataPortal.',
406
    'weight' => 0,
407
    'page callback' => 'drupal_get_form',
408
    'page arguments' => array('cdm_settings_general'),
409
    'access arguments' => array('administer cdm_dataportal'),
410
    'type' => MENU_NORMAL_ITEM,
411
  );
412
  $items['admin/config/cdm_dataportal/settings/general'] = array(
413
    'title' => 'General',
414
    'description' => 'General',
415
    'weight' => 0,
416
    'page callback' => 'drupal_get_form',
417
    'page arguments' => array('cdm_settings_general'),
418
    'access arguments' => array('administer cdm_dataportal'),
419
    'type' => MENU_DEFAULT_LOCAL_TASK,
420
  );
421

    
422
  $items['admin/config/cdm_dataportal/settings/cachesite'] = array(
423
    'title' => 'Cache',
424
    'description' => 'Cache',
425
    'access arguments' => array('administer cdm_dataportal'),
426
    'page callback' => 'drupal_get_form',
427
    'page arguments' => array('cdm_settings_cache'),
428
    'weight' => 10,
429
    'type' => MENU_LOCAL_TASK,
430
  );
431

    
432
  $items['admin/config/cdm_dataportal/settings/geo'] = array(
433
    'title' => 'Geo & Map',
434
    'description' => 'Geo & Map',
435
    'access arguments' => array('administer cdm_dataportal'),
436
    'page callback' => 'drupal_get_form',
437
    'page arguments' => array('cdm_settings_geo'),
438
    'weight' => 1,
439
    'type' => MENU_LOCAL_TASK,
440
  );
441

    
442
  $items['admin/config/cdm_dataportal/settings/layout'] = array(
443
    'title' => 'Layout',
444
    'description' => 'Configure and adjust the layout of your DataPortal ',
445
    'access arguments' => array('administer cdm_dataportal'),
446
    'page callback' => 'drupal_get_form',
447
    'page arguments' => array('cdm_settings_layout'),
448
    'weight' => 2,
449
    'type' => MENU_LOCAL_TASK,
450
  );
451

    
452
  $items['admin/config/cdm_dataportal/settings/layout/taxon'] = array(
453
    'title' => 'Taxon',
454
    'description' => 'Configure and adjust the layout of your DataPortal ',
455
    'access arguments' => array('administer cdm_dataportal'),
456
    'page callback' => 'drupal_get_form',
457
    'page arguments' => array('cdm_settings_layout_taxon'),
458
    'weight' => 1,
459
    'type' => MENU_LOCAL_TASK,
460
  );
461
  /*
462
  $items[] = array(
463
  'path' => 'admin/config/cdm_dataportal/layout/synonymy',
464
  'title' => t('Synonymy'),
465
  'description' => t('Configure and adjust the layout of your DataPortal '),
466
  'access' => user_access('administer cdm_dataportal'),
467
  'callback' => 'drupal_get_form',
468
  'callback arguments' => array('cdm_settings_layout_synonymy'),
469
  'weight' => 1,
470
  'type' => MENU_LOCAL_TASK,
471
  );
472

    
473
  $items[] = array(
474
  'path' => 'admin/config/cdm_dataportal/layout/specimens',
475
  'title' => t('Specimens'),
476
  'description' => t('Configure and adjust the layout of your DataPortal '),
477
  'access' => user_access('administer cdm_dataportal'),
478
  'callback' => 'drupal_get_form',
479
  'callback arguments' => array('cdm_settings_layout_specimens'),
480
  'weight' => 1,
481
  'type' => MENU_LOCAL_TASK,
482
  );
483
  */
484
  $items['admin/config/cdm_dataportal/settings/layout/search'] = array(
485
    'title' => 'Search',
486
    'description' => 'Configure and adjust the layout of your DataPortal ',
487
    'access arguments' => array('administer cdm_dataportal'),
488
    'page callback' => 'drupal_get_form',
489
    'page arguments' => array('cdm_settings_layout_search'),
490
    'weight' => 2,
491
    'type' => MENU_LOCAL_TASK,
492
  );
493

    
494
  $items['admin/config/cdm_dataportal/settings/layout/media'] = array(
495
    'title' => 'Media',
496
    'description' => 'Configure and adjust the layout of your DataPortal ',
497
    'access arguments' => array('administer cdm_dataportal'),
498
    'page callback' => 'drupal_get_form',
499
    'page arguments' => array('cdm_settings_layout_media'),
500
    'weight' => 3,
501
    'type' => MENU_LOCAL_TASK,
502
  );
503

    
504
}
505

    
506
/**
507
 * @todo document this function.
508
 */
509
function cdm_help_general_cache() {
510
  $form = array();
511
  $form['cache_help'] = array(
512
    '#type' => 'fieldset',
513
    '#title' => t('Help'),
514
    '#collapsible' => TRUE,
515
    '#collapsed' => TRUE,
516
  );
517
  $form['cache_help']['test'] = array('#value' => t('probando'));
518
  return drupal_render($form);
519
  $res = array();
520
  $res['default'] = drupal_render($help);
521
  return $res;
522
}
523

    
524
/**
525
 * Configures the settings form for the CDM-API module.
526
 *
527
 * @return array
528
 *   Drupal settings form.
529
 */
530
function cdm_settings_general() {
531

    
532
  $form['cdm_webservice'] = array(
533
    '#type' => 'fieldset',
534
    '#title' => t('CDM Server'),
535
    '#collapsible' => FALSE,
536
    '#collapsed' => FALSE,
537
    '#description' => t('The <em>CDM Server</em> exposes data stored in a
538
        CDM data base to the web via RESTful web services and thus is the source of the data
539
        to be displayed by a CDM DataPotal.'),
540
  );
541

    
542
  $form['cdm_webservice']['cdm_webservice_url'] = array(
543
    '#type' => 'textfield',
544
    '#title' => t('CDM web service URL') . ':',
545
    '#description' => t('This is the URL to the CDM-Server exposing your data
546
      e.g. <em>"http://myserver.net/cdmserver/myproject"</em>'),
547
    '#default_value' => variable_get('cdm_webservice_url', NULL),
548
  );
549

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

    
557
  $form['cdm_webservice']['freetext_index'] = array(
558
    '#type' => 'fieldset',
559
    '#title' => t('Freetext index'),
560
    '#collapsible' => FALSE,
561
    '#collapsed' => FALSE,
562
  );
563

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

    
576
  $frontentURL = urlencode(variable_get('cdm_webservice_url', ''));
577
  $trigger_link_options = array(
578
    'attributes' => array(
579
      'class' => 'index-trigger',
580
    ),
581
  );
582
  $form['cdm_webservice']['freetext_index']['operations'] = array(
583
    '#markup' => "<div>" . t('Operations: !url1 !url2', array(
584
        '!url1' => l(t("Purge"), cdm_compose_url(CDM_WS_MANAGE_PURGE, NULL, 'frontendBaseUrl=' . $frontentURL), $trigger_link_options),
585
        '!url2' => l(t("Reindex"), cdm_compose_url(CDM_WS_MANAGE_REINDEX, NULL, 'frontendBaseUrl=' . $frontentURL), $trigger_link_options),
586
      ))
587
    . '<div id="index-progress"></div></div>',
588
  );
589
  _add_js_cdm_ws_progressbar(".index-trigger", "#index-progress");
590

    
591
  $form['cdm_webservice']['proxy'] = array(
592
    '#type' => 'fieldset',
593
    '#title' => t('Proxy'),
594
    '#collapsible' => TRUE,
595
    '#collapsed' => TRUE,
596
  );
597

    
598
  $form['cdm_webservice']['proxy']['cdm_webservice_proxy_url'] = array(
599
    '#type' => 'textfield',
600
    '#title' => t('Proxy URL') . ':',
601
    '#description' => t('If this proxy url is set the cdm api tries
602
    to connect the web service over the given proxy server.
603
    Otherwise proxy usage is deactivated.'),
604
    '#default_value' => variable_get('cdm_webservice_proxy_url', FALSE),
605
  );
606

    
607
  $form['cdm_webservice']['proxy']['cdm_webservice_proxy_port'] = array(
608
    '#type' => 'textfield',
609
    '#title' => t('Proxy port') . ':',
610
    '#default_value' => variable_get('cdm_webservice_proxy_port', '80'),
611
  );
612

    
613
  $form['cdm_webservice']['proxy']['cdm_webservice_proxy_usr'] = array(
614
    '#type' => 'textfield',
615
    '#title' => t('Login') . ':',
616
    '#default_value' => variable_get('cdm_webservice_proxy_usr', FALSE),
617
  );
618

    
619
  $form['cdm_webservice']['proxy']['cdm_webservice_proxy_pwd'] = array(
620
    '#type' => 'textfield',
621
    '#title' => t('Password') . ':',
622
    '#default_value' => variable_get('cdm_webservice_proxy_pwd', FALSE),
623
  );
624

    
625
  // TODO: settings are still incomplete, compare with
626
  // trunk/dataportal/inc/config_default.php.inc.
627
  $form['taxon_tree'] = array(
628
    '#type' => 'fieldset',
629
    '#title' => t('Taxon Tree'),
630
    '#collapsible' => FALSE,
631
    '#collapsed' => TRUE,
632
    '#description' => t('<p>When you explore your collection, you can navigate
633
      it through a tree structure also called <em>Taxon Tree</em>.</p><p>To be
634
      able to navigate through your collection the
635
      <a href="http://drupal.org/handbook/blocks">drupal block</a>
636
      <em>CDM Taxon Tree</em> should be visible for users. Enable the block at
637
      <a href="./?q=admin/build/block">Administer&#45&#62Site building&#45&#62Blocks
638
      </a></p>'),
639
  );
640

    
641
  $form['taxon_tree'][CDM_TAXONOMICTREE_UUID] = array(
642
    '#type' => 'select',
643
    '#title' => t('Available classifications') . ':',
644
    '#default_value' => variable_get(CDM_TAXONOMICTREE_UUID, FALSE),
645
    '#options' => cdm_get_taxontrees_as_options(),
646
    '#description' => t('Select the default taxa classification for your
647
      <em>taxon tree</em>, the other classifications will be also available but
648
      with a manual user change.'),
649
  );
650

    
651
  $form['taxon_tree']['taxontree_ranklimit'] = array(
652
    '#type' => 'select',
653
    '#title' => t('Rank of highest displayed taxon') . ':',
654
     // Before DEFAULT_TAXONTREE_RANKLIMIT_UUID.
655
    '#default_value' => variable_get('taxontree_ranklimit', DEFAULT_TAXONTREE_RANKLIMIT),
656
    '#options' => cdm_rankVocabulary_as_option(),
657
    '#description' => t('This is the rank of the highest displayed taxon in the
658
      <em>taxon tree</em>. You can select here which rank should be at the top
659
      level of the tree structure.'),
660
  );
661

    
662
  $classification_uuids = array_keys(cdm_get_taxontrees_as_options());
663
  $taxontree_includes_default = array_combine($classification_uuids, $classification_uuids);
664
  $form['taxon_tree'][CDM_TAXONTREE_INCLUDES] = array(
665
      '#type' => 'checkboxes',
666
      '#title' => t('Included Classifications') . ':',
667
      '#default_value' => variable_get(CDM_TAXONTREE_INCLUDES, $taxontree_includes_default),
668
      '#options' => cdm_get_taxontrees_as_options(),
669
      '#description' => t('Only the checked classifications will be avaliable in the classification chooser.'),
670
  );
671

    
672
  $form['distribution'] = array(
673
      '#type' => 'fieldset',
674
      '#title' => t('Distributions'),
675
      '#collapsible' => FALSE,
676
      '#description' => 'This section covers general settings regarding distributions, map related settings are found in the '
677
          . l('geo & map tab', 'admin/config/cdm_dataportal/settings/geo') .
678
          '<p>
679
          </p>',
680
  );
681

    
682
  $form['distribution'][CDM_DISTRIBUTION_FILTER] = array(
683
      '#type' => 'fieldset',
684
      '#title' => 'Distribution filter',
685
      '#collapsible' => FALSE,
686
      '#collapsed' => FALSE,
687
      '#tree' => TRUE,
688
      '#description' => 'The Distribution filter offers the following options
689
      <ul>
690
      <li><strong>Status order preference rule:</strong> In case of multiple distribution status (PresenceAbsenceTermBase) for the same area the status with the highest order is preferred, see OrderedTermBase.compareTo(OrderedTermBase).</li>
691
      <li><strong>Sub area preference rule:</strong>If there is an area with a direct sub area and both areas have the same computed status only the information on the sub area should be reported, whereas the super area should be ignored.</li>
692
      <li><strong>Marked area filter:</strong>Skip distributions where the area has a Marker with one of the specified MarkerTypes</li>
693
      </ul>'
694
  );
695

    
696
  $cdm_distribution_filter = get_array_variable_merged(CDM_DISTRIBUTION_FILTER, CDM_DISTRIBUTION_FILTER_DEFAULT);
697
  $form['distribution'][CDM_DISTRIBUTION_FILTER]['filter_rules'] = array(
698
      '#type' => 'checkboxes',
699
      '#title' => 'Filter rules',
700
      '#default_value' => $cdm_distribution_filter['filter_rules'],
701
      '#options' => array(
702
          'statusOrderPreference' => 'Status order preference rule',
703
          'subAreaPreference' => 'Sub area preference rule'
704
      ),
705
  );
706

    
707
  $marker_type_options = cdm_terms_as_options( cdm_ws_fetch_all('term', array('class' => 'MarkerType' )) );
708
  $form['distribution'][CDM_DISTRIBUTION_FILTER]['hideMarkedAreas'] = array(
709
      '#type' => 'checkboxes',
710
      '#title' => 'Hide marked area filter',
711
      '#default_value' => $cdm_distribution_filter['hideMarkedAreas'],
712
      '#options' => $marker_type_options,
713
      '#description' => 'Check one or more MarkerTypes to define the "hide marked area" filter .',
714
  );
715

    
716
  $form['aggregation'] = array(
717
      '#type' => 'fieldset',
718
      '#title' => t('Aggregation of data'),
719
      '#collapsible' => FALSE,
720
      '#description' => 'This section covers the different aspects of aggregating information.
721
          <p>
722
          </p>',
723
  );
724

    
725
  $form['aggregation'][CDM_TAXON_MEDIA_FILTER] = array(
726
      '#type' => 'checkboxes',
727
      '#title' => 'Taxon media filter',
728
      '#default_value' => variable_get(CDM_TAXON_MEDIA_FILTER, unserialize(CDM_TAXON_MEDIA_FILTER_DEFAULT)),
729
      '#options' => array(
730
          'includeTaxonDescriptions' => 'Media in taxon descriptions',
731
          'includeTaxonNameDescriptions' => 'Media in name descriptions',
732
          'includeOccurrences' => 'Media related to specimens and occurrences',
733
      ),
734
      '#description' => 'This filter configures which images should be taken into account.',
735
  );
736

    
737
  $form['aggregation']['notice'] = array(
738
      '#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
739
          want to make use of the caching capabilities of the dataportal.',
740
  );
741

    
742
  $form['aggregation']['media_aggregation'] = array(
743
      '#type' => 'fieldset',
744
      '#title' => t('Media aggregation'),
745
      '#collapsible' => FALSE,
746
      '#collapsed' => TRUE,
747
      '#description' => t("The media aggregation is also affected by the settigs in \"<strong>Aggregation via taxon relationsships</strong>\" below."),
748

    
749
  );
750
  $form['aggregation']['media_aggregation']['cdm_images_include_children'] = array(
751
      '#type' => 'select',
752
      '#title' => t('Aggregation of taxon pictures') . ':',
753
      '#default_value' => variable_get('cdm_images_include_children', FALSE),
754
      '#options' => array(
755
          0 => "Show only pictures of the current taxon",
756
          1 => "Include pictures of taxonomic children",
757
      ),
758
      '#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."),
759
  );
760

    
761
  $form['aggregation']['aggregate_by_taxon_relationships'][CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS] = array(
762
      '#type' => 'fieldset',
763
      '#attributes' => array('class'=>array('clearfix')),
764
      '#title' => t('Aggregation via taxon relationsships'),
765
      '#collapsible' => TRUE,
766
      '#collapsed' => TRUE,
767
      '#tree' => TRUE,
768
      '#description' => t('Information on taxa will be aggregated along the below chosen
769
          taxon relation ships. This will affect images and occurrences (specimens).
770
          Taxon relation ships are directed and point form one taxon to another. The taxon
771
          relationships to be taken into accunt can therefore configured for the direct direction
772
          and for the inverse.'),
773
  );
774

    
775
  $taxonRelationshipTypeOptions = cdm_Vocabulary_as_option(UUID_TAXON_RELATIONSHIP_TYPE, '_cdm_relationship_type_term_label_callback');
776
  $aggregate_by_taxon_relationships = variable_get(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS, unserialize(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS_DEFAULT));
777

    
778
  $form['aggregation']['aggregate_by_taxon_relationships'][CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS]['direct'] = array(
779
      '#type' => 'checkboxes',
780
      '#title' => t('Direct'),
781
      '#options' => $taxonRelationshipTypeOptions,
782
      '#default_value' => $aggregate_by_taxon_relationships['direct'],
783
  );
784
  $form['aggregation']['aggregate_by_taxon_relationships'][CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS]['invers'] = array(
785
      '#type' => 'checkboxes',
786
      '#title' => t('Invers'),
787
      '#options' => $taxonRelationshipTypeOptions,
788
      '#default_value' => $aggregate_by_taxon_relationships['invers'],
789
  );
790

    
791
  // ----------------------
792
  $form['cdm_js_devel_mode'] = array(
793
      '#type' => 'checkbox',
794
      '#title' => 'Java-script developer mode',
795
      '#default_value' => variable_get('cdm_js_devel_mode', FALSE),
796
      '#description' => 'In production envirionments the java script libraries
797
      the cdm_dataportal is making use of are compressed and optimized. This
798
      is good for performance but a caveat if you need to debug java-script. When the
799
      java-script developer mode is enabled the uncompressed and commented developer
800
      versions of java-script libraries will be used where possible.
801
      <br/><strong>Do not use this option in production!</strong>'
802
  );
803
  // ----------------------
804
  $form['cdm_debug_mode'] = array(
805
      '#type' => 'checkbox',
806
      '#title' => 'CDM page debug mode',
807
      '#default_value' => variable_get('cdm_debug_mode', FALSE),
808
      '#description' => 'When CDM page debug mode enabled the start and end of cdm entity page
809
      creation is logged as well as any http request send via the cdm_api. The log is written to a file in the temporary
810
      folder configured in the' . l('File system settings', 'admin/config/media/file-system') .
811
       '. For this site the file is <code> ' . file_directory_temp() . '/drupal_debug.txt</code>
812
      The log is written by the drupal devel module function <code>dd()</code>.
813
      <br/><strong>Note:</strong> The start and end of the page creation is currently only logged for taxon pages only.'
814
  );
815

    
816
  // Comment @WA: D7 form api does not support reset buttons,
817
  // so to mimic the D5 reset button we add one like this.
818
  $form['actions']['reset'] = array(
819
    '#markup' => '<input id="reset" type="reset" class="form-submit" value="' . t('Reset to defaults') . '" />',
820
    '#weight' => 1000,
821
  );
822

    
823
  $form['#submit'][] = 'cdm_settings_general_submit';
824

    
825
  return system_settings_form($form);
826
}
827

    
828

    
829
/**
830
 * LAYOUT settings
831
 * @return unknown_type
832
 *   todo
833
 */
834
function cdm_settings_layout() {
835

    
836
  $form = array();
837

    
838
  $form['about'] = array(
839
    '#markup' => '<h4>' . t('Portal Layout') . '</h4><p>' . t('This settings contains the general configurations
840
      layout. If you want to configure the specific sites layout visit the
841
      respective configuration site for taxon, search or media.') . '</p>',
842
  );
843

    
844
  // ---- footnotes --- //
845
  $form['footnotes'] = array(
846
    '#type' => 'fieldset',
847
    '#title' => t('Footnotes'),
848
    '#collapsible' => FALSE,
849
    '#collapsed' => FALSE,
850
    '#description' => t('Taxa data such authors, synonyms names, descriptions,
851
      media or distribution areas may have annotations or footnotes. When the
852
      footnotes are enabled they will be visible (if they exist).'),
853
  );
854

    
855
  $form['footnotes']['cdm_dataportal_all_footnotes'] = array(
856
    '#type' => 'checkbox',
857
    '#title' => t('Do not show footnotes'),
858
    '#default_value' => variable_get('cdm_dataportal_all_footnotes', CDM_DATAPORTAL_ALL_FOOTNOTES),
859
    '#description' => t('Check this if you do not want to show any footnotes'),
860
  );
861

    
862
  $form['footnotes']['cdm_dataportal_annotations_footnotes'] = array(
863
    '#type' => 'checkbox',
864
    '#title' => t('Do not show annotations footnotes'),
865
    '#default_value' => variable_get('cdm_dataportal_annotations_footnotes', CDM_DATAPORTAL_ANNOTATIONS_FOOTNOTES),
866
    '#description' => t('Check this if you do not want to show annotation footnotes'),
867
  );
868

    
869
  $annotationTypeOptions = cdm_Vocabulary_as_option(UUID_ANNOTATION_TYPE);
870
  // Additional option for the NULL case.
871
  $annotationTypeOptions['NULL_VALUE'] = t('untyped');
872
  $form['footnotes']['annotations_types_as_footnotes'] = array(
873
    '#type' => 'checkboxes',
874
    '#title' => t('Annotation types as footnotes'),
875
    '#description' => t("Only annotations of the selected type will be displayed
876
       as footnotes. You may want to turn 'technical annotations' off."),
877
    '#options' => $annotationTypeOptions,
878
  );
879
  $annotationsTypesAsFootnotes = variable_get('annotations_types_as_footnotes', unserialize(ANNOTATIONS_TYPES_AS_FOOTNOTES_DEFAULT));
880
  if (!empty($annotationsTypesAsFootnotes)) {
881
    $form['footnotes']['annotations_types_as_footnotes']['#default_value'] = $annotationsTypesAsFootnotes;
882
  }
883

    
884
  // --- Advanced Search --- //
885
  $form['asearch'] = array(
886
      '#type' => 'fieldset',
887
      '#title' => t('Advanced search'),
888
      '#collapsible' => FALSE,
889
      '#collapsed' => FALSE,
890
  );
891
  $form['asearch']['cdm_dataportal_show_advanced_search'] = array(
892
      '#type' => 'checkbox',
893
      '#title' => t('Show advanced search link'),
894
      '#default_value' => variable_get('cdm_dataportal_show_advanced_search', 1),
895
      '#description' => t('Check this box if the link to advanced search should be show below the search box.'),
896
  );
897

    
898
  // ---- Taxon Name Rendering --- //
899
  $form['taxon_name'] = array(
900
      '#type' => 'fieldset',
901
      '#title' => t('Taxon name display'),
902
      '#collapsible' => TRUE,
903
      '#collapsed' => TRUE,
904
      '#description' => t('The display of taxon names is configured by two parts.'
905
          . 'The <srong>name render templates</strong> define the parts of the name to be displayed in the different areas of the data portal pages.'
906
          . 'The name parts are defined in the <stong>part definitions</strong>'),
907
  );
908

    
909
  drupal_add_js(
910
      'jQuery(document).ready( function( ) {
911
         // pretty print json
912
         var json_text = jQuery(\'#edit-' . CDM_PART_DEFINITIONS . '\').val();
913
         var obj = JSON.parse(json_text);
914
         jQuery(\'#edit-' . CDM_PART_DEFINITIONS . '\').val(JSON.stringify(obj, undefined, 2));
915

    
916
         json_text = jQuery(\'#edit-' . CDM_NAME_RENDER_TEMPLATES . '\').val();
917
         obj = JSON.parse(json_text);
918
         jQuery(\'#edit-' . CDM_NAME_RENDER_TEMPLATES . '\').val(JSON.stringify(obj, undefined, 2));
919
       });'
920
      ,array(
921
          'type' => 'inline',
922
          'scope' => 'footer'
923
      )
924
  );
925

    
926
  $default_part_definitions = unserialize(CDM_PART_DEFINITIONS_DEFAULT);
927

    
928
  $form['taxon_name'][CDM_PART_DEFINITIONS] = array(
929
      '#type' => 'textarea',
930
      '#title' => t('Part definitions'),
931
      '#element_validate' => array('form_element_validate_json'),
932
      '#default_value' =>  json_encode(variable_get(CDM_PART_DEFINITIONS, $default_part_definitions)),
933
      '#description' => '
934
          <p>
935
          (Clearing the text area will reset it to the default)
936
          </p>
937
          <p>
938
           The part definitions define the specific parts of which a rendered taxon name plus additional information will consist.
939
          </p>
940
          <p>
941
           A full taxon name plus additional information can consist of the following elements:
942
          <ul>
943
             <li>name: the taxon name inclugin rank nbut without author</li>
944
             <li>authors:  The authors of a reference, also used in taxon names</li>
945
             <li>reference: the nomenclatural reference,</li>
946
             <li>microreference:  Volume, page number etc.</li>
947
             <li>status:  The nomenclatural status of a name</li>
948
             <li>description: name descriptions like protologues etc ...</li>
949
          </ul>
950
          </p>
951
          <p>
952
           These elements are combined in the part definitions array to from the specific parts to be rendered.
953
           (The taxon name "Lapsana communis L., Sp. Pl.: 811. 1753" shall be an example in the following)
954
           Usually the following parts are formed:
955
          <ul>
956
            <li>namePart: the name and rank (in example: "Lapsana communis")</li>
957
            <li>authorshipPart: the author (in example: "L.")</li>
958
            <li>nameAuthorPart: the combination of name and author part (in example: "Lapsana communis L.").</li>
959
               This is useful for zoological names where the authorshipPart belongs to the name and both should</li>
960
               be combined when a link to the taxon is rendered.</li>
961
            <li>referencePart: the nomencaltural reference (in example: "Sp. Pl. 1753")</li>
962
            <li>microreferencePart: usually the page number (in example ": 811.")</li>
963
            <li>statusPart: the nomenclatorical status</li>
964
            <li>descriptionPart: name descriptions like protologues etc ...</li>
965
          </ul>
966
          </p>
967
          <p>
968
           Each set of parts is dedicated to render a specific TaxonName type, the type names are used as keys for the
969
           specific parts part definitions:
970
          <ul>
971
            <li>BotanicalName</li>
972
            <li>ZoologicalName</li>
973
            <li>#DEFAULT: covers ViralNames and other NonViralNames
974
          </ul>
975
           An example:
976
          <pre>
977
           {
978
            "ZoologicalName": {
979
              "namePart": {
980
                "name": true
981
              },
982
              "referencePart": {
983
                "authors": true
984
              },
985
              "microreferencePart": {
986
                "microreference": true
987
              },
988
              "statusPart": {
989
                "status": true
990
              },
991
              "descriptionPart": {
992
                "description": true
993
              }
994
            },
995
            "BotanicalName": {
996
              "namePart": {
997
                "name": true,
998
                "authors": true
999
              },
1000
              "referencePart": {
1001
                "reference": true,
1002
                "microreference": true
1003
              },
1004
              "statusPart": {
1005
                "status": true
1006
              },
1007
              "descriptionPart": {
1008
                "description": true
1009
              }
1010
            }
1011
          }
1012
           </pre>',
1013
  );
1014

    
1015
  $default_render_templates = unserialize(CDM_NAME_RENDER_TEMPLATES_DEFAULT);
1016

    
1017
  $form['taxon_name'][CDM_NAME_RENDER_TEMPLATES] = array(
1018
      '#type' => 'textarea',
1019
      '#title' => t('Name render templates'),
1020
      '#element_validate' => array('form_element_validate_json'),
1021
      '#default_value' =>  json_encode(variable_get(CDM_NAME_RENDER_TEMPLATES, $default_render_templates)),
1022
      '#description' => '
1023
          <p>
1024
          (Clearing the text area will reset it to the default)
1025
          </p>
1026
          <p>
1027
          The render templates array contains one or more name render templates to be used within the page areas identified by the
1028
          render path. The render path is used as key of the array sub subelements whereas the name render template array is set as value.
1029
          The following render Path keys are curretly recognized:
1030
          <ul>
1031
            <li>list_of_taxa:</li>
1032
            <li>acceptedFor:</li>
1033
            <li>taxon_page_synonymy</li>
1034
            <li>typedesignations</li>
1035
            <li>taxon_page_title</li>
1036
            <li>polytomousKey</li>
1037
            <li>na: name + authorship</li>
1038
            <li>nar:name + authorship + reference</li>
1039
            <li>#DEFAULT</li>
1040
          </ul>
1041
          A single render template can be used for multiple render paths. In this case the according key of the render templates
1042
          array element should be a comma separated list of render paths, without any whitespace!.
1043
          </p>
1044
          <p>
1045
          A render template is an associative array. The keys of this array are referring to the keys as defined in the part
1046
          definitions array. See <a href="#edit-cdm-part-definitions">Part definitions</a> above for more information.
1047
          <p>
1048
          The value of the render template element must be set to TRUE in order to let this part being rendered.
1049
          The namePart, nameAuthorPart and referencePart can also hold an associative array with a single
1050
          element: array(\'#uri\' => TRUE). The value of the #uri element will be replaced by the according
1051
          links if the paramters $nameLink or $refenceLink are given to the name render function
1052
          (this is hard coded and cannot be configured here).',
1053
  );
1054

    
1055
  // @WA: D7 form api does not support reset buttons,
1056
  // so to mimic the D5 reset button we add one like this.
1057
  $form['actions']['reset'] = array(
1058
    '#markup' => '<input id="reset" type="reset" class="form-submit" value="' . t('Reset to defaults') . '" />',
1059
    '#weight' => 1000,
1060
  );
1061

    
1062
  $form['#submit'] = array('submit_json_as_php_array');
1063
  // #json_elements especially defined for submit_json_as_php_array()
1064
  $form['#json_elements'] = array(CDM_NAME_RENDER_TEMPLATES, CDM_PART_DEFINITIONS);
1065
  return system_settings_form($form);
1066
}
1067

    
1068

    
1069
/**
1070
 * @todo Please document this function.
1071
 * @see http://drupal.org/node/1354
1072
 */
1073
function cdm_dataportal_create_gallery_settings_form($form_name, $form_title, $collapsed, $form_description = '') {
1074
  $form[$form_name] = array(
1075
    '#type' => 'fieldset',
1076
    '#title' => t($form_title),
1077
    '#collapsible' => TRUE,
1078
    '#collapsed' => $collapsed,
1079
    '#tree' => TRUE,
1080
    '#description' => t($form_description),
1081
  );
1082

    
1083
  $default_values = unserialize(CDM_DATAPORTAL_GALLERY_SETTINGS);
1084
  $gallery_settings = variable_get($form_name, $default_values);
1085
  // $test = variable_get('cdm_dataportal_search_items_on_page', CDM_DATAPORTAL_SEARCH_ITEMS_ON_PAGE);
1086
  if ($form_name == CDM_DATAPORTAL_SEARCH_GALLERY_NAME) {
1087
    /*
1088
    TODO: why cdm_dataportal_search_items_on_page does not save the value on $test???
1089
    $form[$form_name]['cdm_dataportal_search_items_on_page'] = array(
1090
    '#type' => 'textfield',
1091
    '#title' => t('Search Page Size'),
1092
    '#default_value' => $test,
1093
    '#description' => t('Number of Names to display per page in search results.')
1094
    );
1095
    */
1096
    $form[$form_name]['cdm_dataportal_show_taxon_thumbnails'] = array(
1097
      '#type' => 'checkbox',
1098
      '#title' => t('Show media thumbnails for accepted taxa'),
1099
      '#default_value' => $gallery_settings['cdm_dataportal_show_taxon_thumbnails'],
1100
    );
1101

    
1102
    $form[$form_name]['cdm_dataportal_show_synonym_thumbnails'] = array(
1103
      '#type' => 'checkbox',
1104
      '#title' => t('Show media thumbnails for synonyms'),
1105
      '#default_value' => $gallery_settings['cdm_dataportal_show_synonym_thumbnails'],
1106
      '#description' => '',
1107
    );
1108
  }
1109

    
1110
  // $showCaption = variable_get('cdm_dataportal_findtaxa_show_thumbnail_captions', 0);
1111
  $form[$form_name]['cdm_dataportal_show_thumbnail_captions'] = array(
1112
    '#type' => 'checkbox',
1113
    '#title' => t('Show captions under thumbnails'),
1114
    '#default_value' => $gallery_settings['cdm_dataportal_show_thumbnail_captions'],
1115
    '#description' => '',
1116
  );
1117

    
1118
  $form[$form_name]['cdm_dataportal_media_maxextend'] = array(
1119
    '#type' => 'textfield',
1120
    '#title' => t('Thumbnail size') . ':',
1121
    '#default_value' => $gallery_settings['cdm_dataportal_media_maxextend'],
1122
    '#description' => t('Select the size of each individual thumbnail.'),
1123
  );
1124

    
1125
  if ($form_name != CDM_DATAPORTAL_MEDIA_GALLERY_NAME) {
1126
    $form[$form_name]['cdm_dataportal_media_cols'] = array(
1127
      '#type' => 'textfield',
1128
      '#title' => t('Number of columns') . ':',
1129
      '#default_value' => $gallery_settings['cdm_dataportal_media_cols'],
1130
      '#description' => t('Group the thumbnails in columns: select how many
1131
        columns the gallery should display.'),
1132
    );
1133
  }
1134

    
1135
  if ($form_name == CDM_DATAPORTAL_SEARCH_GALLERY_NAME) {
1136
    $form[$form_name]['cdm_dataportal_media_maxRows'] = array(
1137
      '#type' => 'textfield',
1138
      '#title' => t('Maximum number of rows') . ':',
1139
      '#default_value' => $gallery_settings['cdm_dataportal_media_maxRows'],
1140
      '#description' => t('You can group the thumbnails in rows, select in how
1141
        many rows should be the thumbnails grouped.<br/><strong>Note:</strong>
1142
        If you want an unlimited number of rows please set to 0.'),
1143
    );
1144
  }
1145

    
1146
  return $form;
1147
}
1148

    
1149
/**
1150
 * @todo document this function.
1151
 */
1152
function cdm_settings_layout_taxon() {
1153
  $collapsed = FALSE;
1154
  $form = array();
1155

    
1156
  $form['#submit'][] = 'cdm_settings_layout_taxon_submit';
1157

    
1158
  $form['cdm_dataportal_show_back_to_search_results'] = array(
1159
      '#type' => 'checkbox',
1160
      '#title' => t('Show <em>Back to search results</em> link at the taxon site.'),
1161
      '#default_value' => variable_get('cdm_dataportal_show_back_to_search_results', 1),
1162
      '#description' => t('<p>If checked the link to search results is rendered at
1163
       the top of the taxon site. Clicking on the link the last search performed
1164
       is rendered again.</p>'),
1165
  );
1166

    
1167
  // --------- TABBED TAXON ------- //
1168
  $form['taxon_tabs'] = array(
1169
    '#type' => 'fieldset',
1170
    '#title' => t('Taxon tabs'),
1171
    '#collapsible' => TRUE,
1172
    '#collapsed' => FALSE,
1173
    '#description' => t('If tabbed taxon page is enabled the taxon profile will
1174
      be splitted in four diferent tabs; General, Synonymy, Images and
1175
      Specimens. If the taxon has no information for any of the tabs/sections
1176
      such tab will be not displayed.'),
1177
  );
1178

    
1179
  $form['taxon_tabs']['cdm_dataportal_taxonpage_tabs'] = array(
1180
    '#type' => 'checkbox',
1181
    '#title' => t('Tabbed taxon page'),
1182
    '#default_value' => variable_get('cdm_dataportal_taxonpage_tabs', 1),
1183
    '#description' => t('<p>If selected split the taxon page into individual
1184
      tabs for description, images, synonymy and specimens. If not the taxon
1185
      data is rendered as a long single page without tabs.</p>'),
1186
  );
1187

    
1188
  $form['taxon_tabs']['cdm_taxonpage_tabs_visibility'] = array(
1189
    '#type' => 'checkboxes',
1190
    '#title' => t('Tabs visibility options') . ':',
1191
    '#default_value' => variable_get('cdm_taxonpage_tabs_visibility', get_taxon_options_list()),
1192
    '#options' => get_taxon_options_list(),
1193
    '#description' => t('Enable or disable Tabs in the Tabbed page display'),
1194
  );
1195

    
1196
  // WEIGHT
1197
  $taxontabs_weights = get_array_variable_merged('cdm_taxonpage_tabs_weight', CDM_TAXONPAGE_TAB_WEIGHT_DEFAULT);
1198
  $form['taxon_tabs']['cdm_taxonpage_tabs_weight'] = array(
1199
      '#tree' => true
1200
  );
1201
  // Weights range from -delta to +delta, so delta should be at least half
1202
  // of the amount of tabs present.
1203
  $tab_weight_delta = round(count(get_taxon_tabs_list()) / 2) + 1;
1204
  foreach (get_taxon_tabs_list() as $label) {
1205
    $key = strtolower($label); // turn in to string, since we need to use strings as keys
1206
    $form['taxon_tabs']['cdm_taxonpage_tabs_weight'][$key] = array(
1207
        '#title' => $label,
1208
        '#type'  => 'weight',
1209
        '#default_value' => $taxontabs_weights[$key],
1210
        '#delta' => $tab_weight_delta
1211
    );
1212
  }
1213

    
1214
  $form['taxon_tabs']['cdm_dataportal_default_tab'] = array(
1215
    '#type' => 'select',
1216
    '#title' => t('Default tab to display') . ':',
1217
    '#default_value' => variable_get('cdm_dataportal_default_tab', 0),
1218
    '#options' => unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB),
1219
    '#description' => t('<p>Select the default tab to display when visiting a
1220
      taxon page. Only available if Tabbed Taxon Page is enable.</p>
1221
      <strong>Note:</strong> After performing a search and clicking in any
1222
      synonym, the taxon tab to be rendered will be the synonymy of the accepted
1223
      taxon and not the above selected tab.'),
1224
  );
1225

    
1226
  /* ======  TAXON_PROFILE ====== */
1227
  $form['taxon_profile'] = array(
1228
    '#type' => 'fieldset',
1229
    '#title' => t('Taxon profile (tab)'),
1230
    '#description' => t('<p>This section covers the settings related to the taxon
1231
      profile tab, also known as the <strong>"General"</strong> tab.</p>'),
1232
    '#collapsible' => TRUE,
1233
    '#collapsed' => TRUE,
1234
  );
1235

    
1236
  // ---- PROFILE PICTURE ----//
1237

    
1238
  $form['taxon_profile'][CDM_TAXON_PROFILE_IMAGE] = array(
1239
    '#type' => 'fieldset',
1240
    '#tree' => TRUE,
1241
    '#title' => t('Taxon profile picture'),
1242
    '#collapsible' => TRUE,
1243
    '#collapsed' => FALSE,
1244
    '#description' => t('This sections allows configuring the display of the so called taxon profile image which is displayed in the taxon profile tab.'),
1245
  );
1246

    
1247
  //FIXME migrate variables:
1248
  //  cdm_dataportal_show_default_image ---> CDM_TAXON_PROFILE_IMAGE['show']
1249
  // FIXME
1250
  //  eanable file modul in profile and in update
1251

    
1252
  $taxon_profile_image_settings = variable_get(CDM_TAXON_PROFILE_IMAGE, unserialize(CDM_TAXON_PROFILE_IMAGE_DEFAULT));
1253
  /*
1254
   * 'show' => 1,
1255
   * 'maxextend' => 184,
1256
   * 'media_uri_query' => ''
1257
   * 'custom_placeholder_image_on' => 1,
1258
   * 'custom_placeholder_image_fid' => ''
1259
   */
1260
  $form['taxon_profile'][CDM_TAXON_PROFILE_IMAGE]['show'] = array(
1261
    '#type' => 'checkbox',
1262
    '#title' => t('Enable profil picture'),
1263
    '#description' => t('Show the profil picture.'),
1264
    '#default_value' => $taxon_profile_image_settings['show'],
1265
  );
1266

    
1267
  $form['taxon_profile'][CDM_TAXON_PROFILE_IMAGE]['maxextend'] = array(
1268
      '#type' => 'textfield',
1269
      '#tree' => TRUE,
1270
      '#title' => t('Profil picture maximum extend'),
1271
      '#default_value' =>  $taxon_profile_image_settings['maxextend'],
1272
      '#field_suffix' => 'px',
1273
      '#maxlength' => 4,
1274
      '#size' => 4,
1275
      '#description' => t('The maximum extend in either dimension, width or height, of the profil picture in pixels.')
1276
  );
1277

    
1278
  $form['taxon_profile'][CDM_TAXON_PROFILE_IMAGE]['media_uri_query'] = array(
1279
      '#type' => 'textfield',
1280
      '#tree' => TRUE,
1281
      '#title' => t('Additional URI query parameter'),
1282
      '#default_value' =>  $taxon_profile_image_settings['media_uri_query'],
1283
      '#maxlength' => 1024,
1284
      '#size' => 60,
1285
      '#description' => t('Additional query parameters to be used when requesting for the '
1286
          . 'profile image. E.g.: <code>width=400&height=300&quality=95&format=jpeg</code>.'
1287
          . 'The query parameters will be appendend to the uri of the media representation part'
1288
          . ' as stored in the cdm. The query parameter string must not start with a \'&\' or  \'?\'')
1289
  );
1290

    
1291
  $form['taxon_profile'][CDM_TAXON_PROFILE_IMAGE]['custom_placeholder_image_on'] = array(
1292
      '#type' => 'checkbox',
1293
      '#title' => t('Use a custom placeholder image'),
1294
      '#description' => t("This image is shown as replacement if no image of the taxon is available."),
1295
      '#default_value' => $taxon_profile_image_settings['custom_placeholder_image_on']
1296
  );
1297

    
1298
  if($taxon_profile_image_settings['custom_placeholder_image_on'] == 1){
1299
    $form['taxon_profile'][CDM_TAXON_PROFILE_IMAGE]['custom_placeholder_image_fid'] = array(
1300
        '#type' => 'managed_file',
1301
        '#title' => t('Custom placeholder image file'),
1302
        '#progress_indicator' => 'bar',
1303
        '#default_value' => $taxon_profile_image_settings['custom_placeholder_image_fid'],
1304
    //       '#name' => 'custom_placeholder_image',
1305
        '#upload_location' => 'public://' . CDM_TAXON_PROFILE_IMAGE .'/'
1306
    );
1307

    
1308
    if($taxon_profile_image_settings['custom_placeholder_image_fid']){
1309
      $profile_image_file = file_load($taxon_profile_image_settings['custom_placeholder_image_fid']);
1310
      $url = file_create_url($profile_image_file->uri);
1311
      $form['taxon_profile'][CDM_TAXON_PROFILE_IMAGE]['preview'] = array(
1312
                '#type' => 'item',
1313
                '#markup' => '<div class="image-preview"><img src="' . $url . '"/></div>',
1314
      );
1315
    }
1316
  } else {
1317
    $form['taxon_profile'][CDM_TAXON_PROFILE_IMAGE]['custom_placeholder_image_fid'] = array(
1318
        '#type' => 'hidden',
1319
        '#default_value' => $taxon_profile_image_settings['custom_placeholder_image_fid']
1320
    );
1321
  }
1322

    
1323

    
1324

    
1325
  $options = cdm_rankVocabulary_as_option();
1326
  array_unshift($options, '-- DISABLED --');
1327
  $form['taxon_profile']['picture']['image_hide_rank'] = array(
1328
    '#type' => 'select',
1329
    '#title' => t('Hide profile picture for higher ranks') . ':',
1330
    '#default_value' => variable_get('image_hide_rank', '0'),
1331
    '#options' => $options,
1332
    '#description' => t('The taxon profile picture will not be shown for taxa with rank higher that the selected.'),
1333
  );
1334

    
1335
  // -- MEDIA THUMBNAILS -- //
1336
  $form_name = CDM_DATAPORTAL_DESCRIPTION_GALLERY_NAME;
1337
  $form_title = 'Taxon Profile Images';
1338
  $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>';
1339
  $form['taxon_profile'][] = cdm_dataportal_create_gallery_settings_form($form_name, $form_title, $collapsed, $form_description);
1340

    
1341
  // ---- FEATURE TREE ---- //
1342
  $form['taxon_profile']['feature_trees'] = array(
1343
    '#type' => 'fieldset',
1344
    '#title' => t('Features'),
1345
    '#collapsible' => TRUE,
1346
    '#collapsed' => FALSE,
1347
    '#description' => t("This section covers settings related to the taxon's
1348
      <em>Feature Tree</em>. The <em>feature tree</em> are the taxon's
1349
      features such as description, distribution, common names, etc. that Drupal
1350
      will render at the taxon profile page."),
1351
  );
1352
  $featureTrees = cdm_get_featureTrees_as_options(TRUE);
1353
  $saved_uuid = variable_get(CDM_PROFILE_FEATURETREE_UUID, UUID_DEFAULT_FEATURETREE);
1354
  if(!isset($featureTrees['options'][$saved_uuid])) {
1355
    $saved_uuid = UUID_DEFAULT_FEATURETREE;
1356
  }
1357
  $form['taxon_profile']['feature_trees'][CDM_PROFILE_FEATURETREE_UUID] = array(
1358
    '#type' => 'radios',
1359
    '#title' => t('Taxon profile sections') . ':',
1360
    '#default_value' => $saved_uuid,
1361
    '#options' =>  $featureTrees['options'],
1362
    '#pre_render' => array('form_pre_render_conditional_form_element', 'radios_prepare_options_suffix'),
1363
    '#options_suffixes' => $featureTrees['treeRepresentations'],
1364
    '#description' => t('Select the Feature Tree to be displayed at the taxon
1365
      profile. Click "Show Details" to see the Feature Tree elements.'
1366
    ),
1367
  );
1368
  $featureTrees = cdm_get_featureTrees_as_options();
1369
  $saved_uuid = variable_get(CDM_DATAPORTAL_STRUCTURED_DESCRIPTION_FEATURETREE_UUID, UUID_DEFAULT_FEATURETREE);
1370
  if(!isset($featureTrees['options'][$saved_uuid])) {
1371
    $saved_uuid = NULL;
1372
  }
1373
  $form['taxon_profile']['feature_trees'][CDM_DATAPORTAL_STRUCTURED_DESCRIPTION_FEATURETREE_UUID] = array(
1374
    '#type' => 'radios',
1375
    '#title' => t('Natural language representation of structured descriptions') . ':',
1376
    '#default_value' => $saved_uuid,
1377
    '#options' => $featureTrees['options'],
1378
    '#pre_render' => array('form_pre_render_conditional_form_element', 'radios_prepare_options_suffix'),
1379
    '#options_suffixes' => $featureTrees['treeRepresentations'],
1380
    '#description' => t('Taxon descriptions can be stored in a highly structured
1381
      form. The feature tree selected here will be used to generate textual
1382
      representation in natural language.'
1383
    ),
1384
  );
1385

    
1386
  // ---- LAYOUT PER FEATURE ---- //
1387
  $feature_tree = get_profile_featureTree();
1388
  if (isset($feature_tree->root->childNodes)) {
1389

    
1390
    $form_feature_list_layout = array(
1391
      '#title' => t('Taxon profile layout'),
1392
      '#collapsible' => TRUE,
1393
      '#collapsed' => FALSE,
1394
      '#type' => 'fieldset',
1395
      '#description' => t('Will be available in a future release.'),
1396
    );
1397

    
1398
    $feature_list_layout_settings_disabled = TRUE;
1399
    foreach ($feature_tree->root->childNodes as $featureNode) {
1400

    
1401
      if (!$feature_list_layout_settings_disabled && isset($featureNode->feature)) {
1402
        // Must not exceed 45 characters !!!
1403
        $subform_id = LAYOUT_SETTING_PREFIX . $featureNode->feature->uuid;
1404

    
1405
        $settings = mixed_variable_get($subform_id, FEATURE_TREE_LAYOUT_DEFAULTS);
1406
        $systemDefaults = unserialize(FEATURE_TREE_LAYOUT_DEFAULTS);
1407

    
1408
        $form_feature_list_layout[$subform_id] = array(
1409
          '#tree' => TRUE,
1410
          '#title' => 'test' . $featureNode->feature->representation_L10n,
1411
          '#collapsible' => FALSE,
1412
          '#collapsed' => FALSE,
1413
          '#type' => 'fieldset',
1414
          '#description' => t(''),
1415
        );
1416

    
1417
        $form_feature_list_layout[$subform_id]['enabled'] = array(
1418
          '#type' => 'checkbox',
1419
          '#title' => t('Enable'),
1420
          '#default_value' => $settings['enabled'],
1421
          '#description' => t('Enable user defined layout for this feature'),
1422
        );
1423

    
1424
        $form_feature_list_layout[$subform_id]['enclosingTag'] = array(
1425
          '#type' => 'textfield',
1426
          '#title' => t('Enclosing tag'),
1427
          '#disabled' => !$settings['enabled'],
1428
          '#default_value' => $settings['enclosingTag'],
1429
          '#description' => t('Default is: ') . "'<code>" . $systemDefaults['enclosingTag'] . "</code>'",
1430
        );
1431

    
1432
        $form_feature_list_layout[$subform_id]['entryEnclosingTag'] = array(
1433
          '#type' => 'textfield',
1434
          '#title' => t('Entry enclosing tag'),
1435
          '#disabled' => !$settings['enabled'],
1436
          '#default_value' => $settings['entryEnclosingTag'],
1437
          '#description' => t('Default is: ') . "'<code>" . $systemDefaults['entryEnclosingTag'] . "</code>'",
1438
        );
1439

    
1440
        $form_feature_list_layout[$subform_id]['glue'] = array(
1441
          '#type' => 'textfield',
1442
          '#title' => t('Glue'),
1443
          '#disabled' => !$settings['enabled'],
1444
          '#default_value' => $settings['glue'],
1445
          '#description' => t('Default is: ') . "'<code>" . $systemDefaults['glue'] . "</code>'",
1446
        );
1447

    
1448
      }
1449

    
1450
      $form['taxon_profile']['feature_list_layout'] = $form_feature_list_layout;
1451
    }
1452
  }
1453

    
1454
  // ---- DISTRIBUTION LAYOUT ---- //
1455
  $form['taxon_profile']['distribution_layout'] = array(
1456
    '#title' => t('Distribution'),
1457
    '#collapsible' => TRUE,
1458
    '#collapsed' => FALSE,
1459
    '#type' => 'fieldset',
1460
    '#description' => t('Select if you want to sort or not the distribution text
1461
      located below the distribution map.'),
1462
  );
1463

    
1464
  $form['taxon_profile']['distribution_layout']['distribution_sort'] = array(
1465
    '#type' => 'radios',
1466
    '#title' => t('Sort') . ':',
1467
    '#default_value' => variable_get('distribution_sort', 'NO_SORT'),
1468
    '#options' => array(
1469
      'NO_SORT' => t('Standard (No sort)'),
1470
      'HIDE_TDWG2' => t('Sorted without TDWG Level 2'),
1471
    ),
1472
  );
1473

    
1474
  $form['taxon_profile']['distribution_layout'][DISTRIBUTION_TEXTDATA_DISPLAY_ON_TOP] = array(
1475
    '#type' => 'checkbox',
1476
    '#title' => t('Show TextData elements on top of the map'),
1477
    '#default_value' => variable_get(DISTRIBUTION_TEXTDATA_DISPLAY_ON_TOP, 0),
1478
    '#description' => t('Check this if you want to appear all <code>TextData</code>
1479
      elements on top of the map. Otherwise all <code>TextData</code>
1480
      distribution elements will be listed below the other area elements.
1481
      This option is useful if you need to have descriptive texts for each
1482
      distribution map.'),
1483
  );
1484

    
1485

    
1486
  /* ====== SYNONYMY ====== */
1487
  $form['taxon_synonymy'] = array(
1488
    '#type' => 'fieldset',
1489
    '#title' => t('Taxon synonymy (tab)'),
1490
    '#collapsible' => TRUE,
1491
    '#collapsed' => TRUE,
1492
    '#description' => t('This section covers the settings related to the taxon
1493
      <strong>synonymy</strong> tab.'),
1494
  );
1495

    
1496
  $form['taxon_synonymy']['cdm_dataportal_nomref_in_title'] = array(
1497
    '#type' => 'checkbox',
1498
    '#title' => t('Show accepted taxon on top of the synonymy'),
1499
    '#default_value' => variable_get('cdm_dataportal_nomref_in_title', CDM_DATAPORTAL_NOMREF_IN_TITLE),
1500
    '#description' => t('If checked, the first homotypic taxon is a repetition
1501
      of the accepted taxon most likely with the full nomenclatural reference
1502
      (depending on the currently chosen theme).'),
1503
  );
1504

    
1505
  $form['taxon_synonymy']['cdm_dataportal_display_is_accepted_for'] = array(
1506
    '#type' => 'checkbox',
1507
    '#title' => t('Display <em>is accepted for ...</em> on taxon pages when
1508
      coming from a synonym link.'),
1509
    '#default_value' => variable_get('cdm_dataportal_display_is_accepted_for', CDM_DATAPORTAL_DISPLAY_IS_ACCEPTED_FOR),
1510
    '#description' => t('Check this if after doing a search and clicking on a
1511
      synonym you want to see the "accept of" text for the accepted synonym.'),
1512
  );
1513

    
1514
  $nameRelationshipTypeOptions = cdm_Vocabulary_as_option(UUID_NAME_RELATIONSHIP_TYPE);
1515
  $form['taxon_synonymy']['name_relationships']['name_relationships_to_show'] = array(
1516
    '#type' => 'checkboxes',
1517
    '#title' => t('Display name relationships') . ':',
1518
    '#default_value' => variable_get('name_relationships_to_show', 0),
1519
    '#options' => $nameRelationshipTypeOptions,
1520
    '#description' => t('Select the name relationships you want to show for the
1521
      accepted taxa.'),
1522
  );
1523

    
1524
  $form['taxon_synonymy'][CDM_DATAPORTAL_DISPLAY_TAXON_RELATIONSHIPS] = array(
1525
    '#type' => 'checkbox',
1526
    '#title' => t('Show taxon relations ships of accepted taxon'),
1527
    '#default_value' => variable_get(CDM_DATAPORTAL_DISPLAY_TAXON_RELATIONSHIPS, CDM_DATAPORTAL_DISPLAY_TAXON_RELATIONSHIPS_DEFAULT),
1528
    '#description' => t('If this option is enabled the synonymy will show the
1529
      below selected taxon relationships of accepted taxa.'),
1530
  );
1531

    
1532
  $taxonRelationshipTypeOptions = cdm_Vocabulary_as_option(UUID_TAXON_RELATIONSHIP_TYPE, '_cdm_relationship_type_term_label_callback');
1533
  $form['taxon_synonymy'][CDM_TAXON_RELATIONSHIP_TYPES] = array(
1534
    '#type' => 'checkboxes',
1535
    '#title' => t('Taxon relationship types') . ':',
1536
    '#description' => t('Only taxon relationships of the selected type will be
1537
      displayed'),
1538
    '#options' => $taxonRelationshipTypeOptions,
1539
    '#default_value' => variable_get(CDM_TAXON_RELATIONSHIP_TYPES, unserialize(CDM_TAXON_RELATIONSHIP_TYPES_DEFAULT)),
1540
    '#disabled' => !variable_get(CDM_DATAPORTAL_DISPLAY_TAXON_RELATIONSHIPS, CDM_DATAPORTAL_DISPLAY_TAXON_RELATIONSHIPS_DEFAULT),
1541
  );
1542

    
1543
  // ====== SPECIMENS ====== //
1544
  $form['taxon_specimens'] = array(
1545
    '#type' => 'fieldset',
1546
    '#title' => t('Taxon specimens (tab)'),
1547
    '#collapsible' => TRUE,
1548
    '#collapsed' => TRUE,
1549
    '#description' => t('This section covers the settings related to the taxon
1550
      <strong>specimens</strong> tab.'),
1551
  );
1552

    
1553
  $featureTrees = cdm_get_featureTrees_as_options(TRUE);
1554
  $saved_uuid = variable_get(CDM_OCCURRENCE_FEATURETREE_UUID, UUID_DEFAULT_FEATURETREE);
1555
  if(!isset($featureTrees['options'][$saved_uuid])) {
1556
    $saved_uuid = UUID_DEFAULT_FEATURETREE;
1557
  }
1558
  $form['taxon_specimens']['feature_trees'][CDM_OCCURRENCE_FEATURETREE_UUID] = array(
1559
      '#type' => 'radios',
1560
      '#title' => t('Specimen description feature tree') . ':',
1561
      '#default_value' => $saved_uuid,
1562
      '#options' =>  $featureTrees['options'],
1563
      '#pre_render' => array('form_pre_render_conditional_form_element', 'radios_prepare_options_suffix'),
1564
      '#options_suffixes' => $featureTrees['treeRepresentations'],
1565
      '#description' => t('Select the feature tree to be used for displaying specimen descriptions. Click "Show Details" to see the Feature Tree elements.'
1566
      ),
1567
  );
1568

    
1569
  $form_name = CDM_DATAPORTAL_SPECIMEN_GALLERY_NAME;
1570
  $form_title = t('Specimen media');
1571
  $form_description = t('Specimens may have media which is displayed at the
1572
     Specimen tab/section as a gallery. It is possible to configure the
1573
     thumbnails gallery here, however for configuring how a single media should
1574
     be displayed please go to !url.</p>',
1575
     array(
1576
       '!url' => l(t('Layout -> Media'), 'admin/config/cdm_dataportal/settings/layout/media'),
1577
     ));
1578
  $form['taxon_specimens'][] = cdm_dataportal_create_gallery_settings_form($form_name, $form_title, FALSE, $form_description);
1579

    
1580
  // --- MEDIA GALLERY ---- //
1581
  $form_name = CDM_DATAPORTAL_TAXON_MEDIA_GALLERY_NAME_TAB;
1582
  $form_title = 'Media gallery (tab)';
1583
  $form_description = '<p>This section covers the settings related to the taxon <strong>media</strong> tab.
1584
   Taxa may have media (usually images) and they are as thumbnails displayed. It is possible to configure
1585
   the thumbnails gallery here, however for configuring how a single media should be displayed please go to
1586
   <a href="./?q=admin/settings/cdm_dataportal/layout/media">Layout -&gt; Media</a></p>
1587
   <p><strong>Note:</strong> These settings are only taken into account when the standard
1588
   gallery viewer is selected at <a href="./?q=admin/settings/cdm_dataportal/layout/media">Layout -&gt; Media</a>.</p>';
1589
  $form['taxon_media'][] = cdm_dataportal_create_gallery_settings_form($form_name, $form_title, TRUE, $form_description);
1590

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

    
1600
/**
1601
 * @todo document this function.
1602
 */
1603
function cdm_settings_layout_search() {
1604

    
1605
  $form = array();
1606

    
1607
  $form['#submit'][] = 'cdm_settings_layout_search_submit';
1608

    
1609
  $form['search_settings'] = array(
1610
    '#type' => 'fieldset',
1611
    '#title' => t('Taxa Search'),
1612
    '#collapsible' => FALSE,
1613
    '#collapsed' => FALSE,
1614
    '#description' => t('<p>The data portal allows the users to perform searchs.</p><p>To perform searchs
1615
         the block <em>CDM Taxon Search</em> should be enabled and visible for users
1616
         where they can write the text to be searched. You can find Drupal block configuration
1617
         site at <a href="./?q=admin/build/block">Administer&#45&#62Site building&#45&#62Blocks</a></p> '),
1618
  );
1619

    
1620
  $form['search_settings']['simple_search_ignore_classification'] = array(
1621
      '#type' => 'checkbox',
1622
      '#title' => t('Ignore the chosen classification in simple search'),
1623
      '#default_value' => variable_get('simple_search_ignore_classification', TRUE),
1624
      '#description' => t('The simple search, which can be executed via the search block,
1625
          will by default search on all classifications. Remove the tick if you want your
1626
          portal to search on the classification selected in the classification browser
1627
          selector.'),
1628
  );
1629

    
1630
  $form['search_settings']['cdm_dataportal_search_items_on_page'] = array(
1631
    '#type' => 'textfield',
1632
    '#title' => t('Results per page') . ':',
1633
    '#default_value' => variable_get('cdm_dataportal_search_items_on_page', CDM_DATAPORTAL_SEARCH_ITEMS_ON_PAGE),
1634
    '#description' => t('Number of results to display per page.'),
1635
  );
1636

    
1637
  $search_mode_default = get_array_variable_merged(CDM_SEARCH_TAXA_MODE, CDM_SEARCH_TAXA_MODE_DEFAULT);
1638
  $form['search_settings']['cdm_search_taxa_mode'] = array(
1639
      '#type' => 'checkboxes',
1640
      '#title' => 'Search mode',
1641
      '#description' => 'The taxon search can operate in different modes in order to find only taxa, synonyms,
1642
          taxa by its common name and even taxa which have been used as misappied names. The settings made here will affect the default
1643
          for the advance search form and the behaviour of the simple search form which always will behave according to the
1644
          defaults set here.',
1645
      '#options' => drupal_map_assoc(array_keys(unserialize(CDM_SEARCH_TAXA_MODE_DEFAULT))),
1646
      '#default_value' => $search_mode_default
1647
      );
1648

    
1649
  // --- SEARCH TAXA GALLERY ---- //
1650
  $items = variable_get('cdm_dataportal_search_items_on_page', CDM_DATAPORTAL_SEARCH_ITEMS_ON_PAGE);
1651
  $collapsed = FALSE;
1652
  $form_name = CDM_DATAPORTAL_SEARCH_GALLERY_NAME;
1653
  $form_title = 'Taxa Search thumbnails';
1654
  $form_description = 'Search results may show thumbnails. ';
1655
  $form[] = cdm_dataportal_create_gallery_settings_form($form_name, $form_title, $collapsed, $form_description);
1656

    
1657
  // Comment @WA: D7 form api does not support reset buttons,
1658
  // so to mimic the D5 reset button we add one like this.
1659
  $form['actions']['reset'] = array(
1660
    '#markup' => '<input id="reset" type="reset" class="form-submit" value="' . t('Reset to defaults') . '" />',
1661
    '#weight' => 1000,
1662
  );
1663
  return system_settings_form($form);
1664
}
1665

    
1666
/**
1667
 * @todo document this function.
1668
 */
1669
function cdm_settings_layout_media() {
1670

    
1671
  $form = array();
1672

    
1673
  $form['media_settings'] = array(
1674
    '#type' => 'fieldset',
1675
    '#title' => t('Media settings'),
1676
    '#collapsible' => FALSE,
1677
    '#collapsed' => FALSE,
1678
    '#description' => 'This section covers layout settings for media pages.'
1679
      . 'Further media related settings may be found under the taxon layout settings and on the general settings.',
1680
  );
1681

    
1682
  $form['media_settings']['image_gallery_viewer'] = array(
1683
    '#type' => 'select',
1684
    '#title' => t('Image viewer') . ':',
1685
    '#default_value' => variable_get('image_gallery_viewer', 'default'),
1686
    '#options' => array(
1687
      'default' => t('Standard image viewer'),
1688
      'fsi' => t('FSI viewer (requires FSI server!)'),
1689
    ),
1690
  );
1691

    
1692
  // --- MEDIA GALLERY ---- //
1693
  $form_name = CDM_DATAPORTAL_MEDIA_GALLERY_NAME;
1694
  $form_title = 'Standard viewer';
1695
  $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>';
1696
  // $form[] = cdm_dataportal_create_gallery_settings_form($form_name, $form_title, $collapsed);
1697
  $form['media_settings'][] = cdm_dataportal_create_gallery_settings_form($form_name, $form_title, FALSE, $form_description);
1698

    
1699
  // @WA: D7 form api does not support reset buttons,
1700
  // so to mimic the D5 reset button we add one like this.
1701
  $form['actions']['reset'] = array(
1702
    '#markup' => '<input id="reset" type="reset" class="form-submit" value="' . t('Reset to defaults') . '" />',
1703
    '#weight' => 1000,
1704
  );
1705
  return system_settings_form($form);
1706
}
1707

    
1708
/**
1709
 * GEOSERVICE and Map settings.
1710
 */
1711
function cdm_settings_geo($form, &$form_state) {
1712

    
1713
  $current_geoserver_settings = get_edit_map_service_settings();
1714
  $map_distribution = get_array_variable_merged(CDM_MAP_DISTRIBUTION, CDM_MAP_DISTRIBUTION_DEFAULT);
1715
  // The default layer must always be enabled
1716
  $preferred_layer = $map_distribution['openlayers']['base_layers']['PREFERRED'];
1717
  $map_distribution['openlayers']['base_layers'][$preferred_layer] = $preferred_layer;
1718

    
1719
  $form = array();
1720

    
1721
  $dummy_distribution_query = NULL;
1722
  if($map_distribution['map_type'] != 1){
1723
    // we need to apply a dummy query since the map serice requires for image maps
1724
    // at least as and ad to be defined
1725
    $dummy_distribution_query = "as=a:339966&ad=tdwg1:a:1,2,3,4,5,6,7,8,9";
1726
  }
1727
  $form['map_preview'] = array(
1728
      '#type' => 'fieldset',
1729
      '#tree' => FALSE,
1730
      '#title' => t('Map preview'),
1731
      '#collapsible' => FALSE,
1732
      '#description' => 'The preview of the map'
1733
       . ($dummy_distribution_query != null ?
1734
           ' may not be accurate in case if image maps, please check the map display in the taxon pages.':
1735
           '.<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.')
1736
  );
1737
  $form['map_preview']['map'] = compose_map(NULL, $dummy_distribution_query, NULL,
1738
      array(
1739
          'move' => "this.cdmOpenlayersMap.printInfo",
1740
          '#execute' => "this.cdmOpenlayersMap.printInfo"
1741
      )
1742
  );
1743

    
1744

    
1745
  /*
1746
   * GEO SERVER
1747
   */
1748
  $form['edit_map_server'] = array(
1749
    '#type' => 'fieldset',
1750
    '#tree' => true,
1751
    '#title' => t('EDIT map service'),
1752
    '#collapsible' => TRUE,
1753
    '#collapsed' => TRUE,
1754
    '#description' => t('Configuration and selection of your geo server.
1755
      The Geo Server is responsible for generating the maps.'),
1756
  );
1757

    
1758
  $form['edit_map_server']['base_uri'] = array(
1759
    '#type' => 'select',
1760
    '#title' => t('EDIT map service') . ':',
1761
    '#default_value' => $current_geoserver_settings['base_uri'],
1762
    '#options' => unserialize(EDIT_MAPSERVER_URI),
1763
    '#description' => t('Select the EDIT map server you want to use within your data portal.'),
1764
  );
1765
  $form['edit_map_server']['version'] = array(
1766
      '#type' => 'select',
1767
      '#title' => t('Version') . ':',
1768
      '#default_value' => $current_geoserver_settings['version'],
1769
      '#options' => unserialize(EDIT_MAPSERVER_VERSION),
1770
      '#description' => t('The version of the EDIT map services'),
1771
  );
1772

    
1773
  $localhostkey = 'ABQIAAAAFho6eHAcUOTHLmH9IYHAeBRi_j0U6kJrkFvY4-OX2XYmEAa76BTsyMmEq-tn6nFNtD2UdEGvfhvoCQ';
1774
  $gmap_api_key = variable_get('gmap_api_key', 'ABQIAAAAFho6eHAcUOTHLmH9IYHAeBRi_j0U6kJrkFvY4-OX2XYmEAa76BTsyMmEq-tn6nFNtD2UdEGvfhvoCQ');
1775
  $form['gmap_api_key'] = array(
1776
      '#type' => 'textfield',
1777
      '#title' => t('Google maps API key') . ':',
1778
      '#default_value' => variable_get('gmap_api_key', $gmap_api_key),
1779
      '#description' => t('If you want to use the Google Maps Layer, a key is
1780
      needed. If you need a key, visit
1781
      <a href="http://code.google.com/intl/en/apis/maps/signup.html">google maps api key</a>.
1782
      <br/><strong>Note:</strong> The following key: <code>!localhostkey</code>
1783
      is the default key for the localhost (127.0.0.1).',
1784
      array('!localhostkey' => $localhostkey)),
1785
  );
1786

    
1787

    
1788
  /*
1789
   * MAP SETTINGS
1790
   */
1791

    
1792
  $form[CDM_MAP_DISTRIBUTION] = array(
1793
    '#type' => 'fieldset',
1794
    '#tree' => TRUE,
1795
    '#title' => t('Maps settings'),
1796
    '#collapsible' => TRUE,
1797
    '#collapsed' => TRUE,
1798
    '#description' => t('General configuration for all map types.'),
1799
  );
1800

    
1801
  /*
1802
   * settings for the distribution map are used also for specimens map!!!!
1803
   */
1804

    
1805
  $form[CDM_MAP_DISTRIBUTION]['width'] = array(
1806
    '#type' => 'textfield',
1807
    '#title' => 'Width',
1808
    '#default_value' => $map_distribution['width'],
1809
    '#maxlength' => 4,
1810
    '#size' => 4,
1811
    '#description' => 'Width of the map. To allow OSM baselayers to zoom out to the full extend of the world the map width must be
1812
      a multiple of 256px since the osm tiles from tile.openstreetmap.org have a size of 256px x 256px and frational zoom
1813
      levels are not possible in this case.',
1814
  );
1815
  $form[CDM_MAP_DISTRIBUTION]['height'] = array(
1816
      '#type' => 'textfield',
1817
      '#title' => 'Height',
1818
      '#default_value' => $map_distribution['height'],
1819
      '#maxlength' => 4,
1820
      '#size' => 4,
1821
      '#description' => 'Height of the map. Depending on the chosen base layer you may want to choose the height equal
1822
      to the width or half of the width. Any other aspect ratio is also possible if desired.',
1823
  );
1824

    
1825
  $form[CDM_MAP_DISTRIBUTION]['bbox'] = array(
1826
    '#type' => 'textfield',
1827
    '#title' => 'Bounding box',
1828
    '#default_value' => $map_distribution['bbox'],
1829
    '#description' => t('The bounding box (left, bottom, right, top) defines the area to be initially displayed in maps.
1830
      Use "-180,-90,180,90" for the whole world. Leave <strong>empty</strong>
1831
      to let the map <strong>automatically zoom</strong> to the bounds enclosing the shown data.</p>
1832
      <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.
1833
      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
1834
      below the map from where you can copy the bbox string.</p>'),
1835
  );
1836

    
1837
  $form[CDM_MAP_DISTRIBUTION]['show_labels'] = array(
1838
    '#type' => 'checkbox',
1839
    '#title' => 'Display area labels',
1840
    '#default_value' => $map_distribution['show_labels'],
1841
    '#description' => t('The map will show name labels of the areas'),
1842
  );
1843

    
1844
  $form[CDM_MAP_DISTRIBUTION]['caption'] = array(
1845
    '#type' => 'textfield',
1846
    '#title' => 'Map caption',
1847
    '#default_value' => $map_distribution['caption'],
1848
    '#description' => t('The caption will be shown below the map.'),
1849
  );
1850

    
1851
  $form[CDM_MAP_DISTRIBUTION]['distribution_opacity'] = array(
1852
    '#type' => 'textfield',
1853
    '#title' => 'Distribution layer opacity',
1854
    '#default_value' => $map_distribution['distribution_opacity'],
1855
    '#description' => t('Valid values range from 0.0 to 1.0. Value 1.0 means the distributions (the countries or regions) will
1856
                           fully visible, while a value near to 0.0 will be not much visible.'),
1857
  );
1858

    
1859
  $form[CDM_MAP_DISTRIBUTION]['map_type'] = array(
1860
    '#type' => 'radios',
1861
    '#title' => 'Map types',
1862
    '#options' => array(
1863
      1 => "OpenLayers dynamic map viewer",
1864
      0 => "Plain image",
1865
    ),
1866
    '#default_value' => $map_distribution['map_type'],
1867
    '#description' => 'Two different map types are available :
1868
      <ul><li><em>OpenLayers</em>: Display the maps in an interactive viewer
1869
      which allows zooming and panning. If enabled you can configure the default layer
1870
      (background of your maps) below.</li>
1871
      <li><em>Plain image</em>: The map will be static non interactive
1872
      image.</li></ul>',
1873
  );
1874
  $open_layers_is_enabled = $map_distribution['map_type'] == 1;
1875

    
1876

    
1877
  // --- Plain Image Settings --- //
1878
  $form[CDM_MAP_DISTRIBUTION]['image_map'] = array(
1879
    '#type' => 'fieldset',
1880
    '#title' => 'Plain image map settings',
1881
    '#tree' => TRUE,
1882
    '#collapsible' => TRUE,
1883
    '#collapsed' => $open_layers_is_enabled,
1884
    '#description' => 'The settings in this section are still expertimental
1885
      and can only be used with the EDIT map service version 1.1 or above.',
1886
  );
1887
  $edit_mapserver_version = get_edit_map_service_version_number();
1888
  if ($edit_mapserver_version < 1.1) {
1889
    $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>'
1890
      . $form[CDM_MAP_DISTRIBUTION]['image_map']['#description'];
1891
  }
1892

    
1893
  $form[CDM_MAP_DISTRIBUTION]['image_map']['base_layer'] = array(
1894
    '#type' => 'textfield',
1895
    '#title' => 'Background layer',
1896
    '#default_value' => $map_distribution['image_map']['base_layer'],
1897
    '#description' => t('Background layer. For available layers inspect !url1 or !url2.', array(
1898
      '!url1' => l('deegree-csw', 'http://edit.africamuseum.be:8080/deegree-csw/md_search.jsp'),
1899
      '!url2' => l('geoserver layers', 'http://edit.africamuseum.be/geoserver/web/'),
1900
    )),
1901
  );
1902

    
1903
  $form[CDM_MAP_DISTRIBUTION]['image_map']['bg_color'] = array(
1904
    '#type' => 'textfield',
1905
    '#title' => 'Background color',
1906
    '#default_value' => $map_distribution['image_map']['bg_color'],
1907
  );
1908

    
1909
  $form[CDM_MAP_DISTRIBUTION]['image_map']['layer_style'] = array(
1910
    '#type' => 'textfield',
1911
    '#title' => 'Background layer style',
1912
     // Only line color by now.
1913
    '#default_value' => $map_distribution['image_map']['layer_style'],
1914
    '#description' => 'Syntax: {Area fill color},{Area stroke color},{Area stroke width},{Area stroke dash style}',
1915
  );
1916

    
1917
  $form[CDM_MAP_DISTRIBUTION]['image_map']['projection'] = array(
1918
      '#type' => 'textfield',
1919
      '#title' => 'Projection',
1920
      '#default_value' => drupal_array_get_nested_value($map_distribution, array('image_map', 'projection')),
1921
      '#description' => 'Spatial Reference System (SRS) identifier ) optional ( Defines projections in WMS GetMap request.
1922
        Using EPSG:4326 (WGS84 lat/long) is the default but can be changed
1923
        on-the-fly to different UTM and much more zone specific. Examples: EPSG:4326, EPSG:900913, EPSG:3857, EPSG:7777777',
1924
  );
1925

    
1926

    
1927
  // --- OpenLayers Settings --- //
1928
  $form[CDM_MAP_DISTRIBUTION]['openlayers'] = array(
1929
    '#type' => 'fieldset',
1930
    '#title' => 'OpenLayers settings',
1931
    '#tree' => TRUE,
1932
    '#collapsible' => TRUE,
1933
    '#collapsed' => !$open_layers_is_enabled,
1934
    '#description' => '',
1935
  );
1936

    
1937

    
1938
  $form[CDM_MAP_DISTRIBUTION]['openlayers']['display_outside_max_extent'] = array(
1939
      '#type' => 'checkbox',
1940
      '#title' => 'Display outside max extent',
1941
      '#default_value' => $map_distribution['openlayers']['display_outside_max_extent'],
1942
      '#description' => t('Allows the map to display parts of the layers which are outside
1943
         the max extent if the aspect ratio of the map and of the baselayer
1944
         are not equal.'),
1945
  );
1946

    
1947

    
1948
  $form[CDM_MAP_DISTRIBUTION]['openlayers']['show_layer_switcher'] = array(
1949
      '#type' => 'checkbox',
1950
      '#title' => 'Show Layer Switcher',
1951
      '#default_value' => $map_distribution['openlayers']['show_layer_switcher'],
1952
      '#description' => 'The Layer Switcher control displays a table of contents
1953
      for the map.  This allows the user interface to switch between
1954
      base layers and to show or hide overlays.  By default the switcher is
1955
      shown minimized on the right edge of the map, the user may expand it
1956
      by clicking on the handle.',
1957
  );
1958

    
1959
  if (!$open_layers_is_enabled) {
1960
    $form[CDM_MAP_DISTRIBUTION]['openlayers']['#description'] = '<div class="messages warning">'
1961
        . 'The Openlayers viewer is currently not enabled! (see section Maps settings above )</div>'
1962
        . $form[CDM_MAP_DISTRIBUTION]['openlayers']['#description'];
1963
  }
1964

    
1965
  $baselayer_options = array(
1966
    /*
1967
   NOTICE: must correspond to the layers defined in
1968
   js/openlayers_,ap.js#getLayersByName()
1969
   */
1970
    'osgeo_vmap0' => "Metacarta Vmap0 (OSGeo server)", // EPSG:4326: EPSG:900913
1971
    'metacarta_vmap0' => "Metacarta Vmap0 (MetaCarta Labs server)", // EPSG:4326, EPSG:900913
1972
    // all others EPSG:900913
1973
    // 'edit-vmap0_world_basic' => 'EDIT Vmap0',
1974
    'edit-etopo1' => "ETOPO1 Global Relief Model",
1975
    'mapnik' => 'OpenStreetMap',
1976
    'mapquest_open' => "MapQuest",
1977
    'mapquest_sat' => "MapQuest Sattelite",
1978
//     'osmarender' => 'OpenStreetMap (Tiles@home)',
1979
    'gmap' => 'Google Streets',
1980
    'gsat' => 'Google Satellite',
1981
    'ghyb' => 'Google Hybrid',
1982
//     'veroad' => 'Virtual Earth Roads',
1983
//     'veaer' => 'Virtual Earth Aerial',
1984
//     'vehyb' => 'Virtual Earth Hybrid',
1985
    // 'yahoo' => 'Yahoo Street',
1986
    // 'yahoosat' => 'Yahoo Satellite',
1987
    // 'yahoohyb' => 'Yahoo Hybrid',
1988
     'custom_wms_base_layer_1' => 'Custom WMS base layer (needs to be manually configured below!)',
1989
  );
1990

    
1991
  $form[CDM_MAP_DISTRIBUTION]['openlayers']['base_layers'] = array(
1992
    '#type' => 'checkboxes_preferred',
1993
    '#title' => 'Base Layers',
1994
    '#options' => $baselayer_options,
1995
    '#default_value' =>  $map_distribution['openlayers']['base_layers'],
1996
    '#description' => 'Choose the baselayer layer you prefer to use as map background in the OpenLayers dynamic mapviewer.',
1997
  );
1998

    
1999
  $form[CDM_MAP_DISTRIBUTION]['openlayers']['custom_wms_base_layer'] = array(
2000
      '#type' => 'fieldset',
2001
      '#title' => 'Custom WMS base layer',
2002
      '#tree' => TRUE,
2003
      '#collapsible' => FALSE,
2004
      '#collapsed' => FALSE,
2005
      '#description' => 'Here you an define a custom wms layer as additional base layer.',
2006
  );
2007

    
2008
  $form[CDM_MAP_DISTRIBUTION]['openlayers']['custom_wms_base_layer']['name'] = array(
2009
      '#type' => 'textfield',
2010
      '#title' => 'Layer name',
2011
      // Only line color by now.
2012
      '#default_value' => $map_distribution['openlayers']['custom_wms_base_layer']['name'],
2013
      '#description' => 'A arbitrary name for the layer.',
2014
  );
2015
  $form[CDM_MAP_DISTRIBUTION]['openlayers']['custom_wms_base_layer']['url'] = array(
2016
      '#type' => 'textfield',
2017
      '#title' => 'WMS url',
2018
      // Only line color by now.
2019
      '#default_value' => $map_distribution['openlayers']['custom_wms_base_layer']['url'],
2020
      '#description' => 'Base url for the WMS (e.g.  http://wms.jpl.nasa.gov/wms.cgi)'
2021
  );
2022
  $form[CDM_MAP_DISTRIBUTION]['openlayers']['custom_wms_base_layer']['params'] = array(
2023
      '#type' => 'textarea',
2024
      '#title' => 'WMS parameters',
2025
      '#element_validate' => array('form_element_validate_json'),
2026
      // Only line color by now.
2027
      '#default_value' => $map_distribution['openlayers']['custom_wms_base_layer']['params'],
2028
      '#description' => 'An javasript object with key/value pairs representing the GetMap query string parameters and parameter values, entered in valid JSON. For example:
2029
<pre> {
2030
  "Layers": "topp:em_tiny_jan2003",
2031
  "Format": "image/png",
2032
  "BGCOLOR": "0xe0faff"
2033
}
2034
</pre>'
2035
  );
2036
  $form[CDM_MAP_DISTRIBUTION]['openlayers']['custom_wms_base_layer']['projection'] = array(
2037
      '#type' => 'textfield',
2038
      '#title' => 'Projection',
2039
      // Only line color by now.
2040
      '#default_value' => $map_distribution['openlayers']['custom_wms_base_layer']['projection'],
2041
      '#description' => 'The desired projection for the layer (e.g. EPSG:4326, EPSG:900913, EPSG:3857)'
2042
  );
2043
  $form[CDM_MAP_DISTRIBUTION]['openlayers']['custom_wms_base_layer']['proj4js_def'] = array(
2044
      '#type' => 'textfield',
2045
      '#maxlength' => 256,
2046
      '#title' => 'proj4js definition',
2047
      // Only line color by now.
2048
      '#default_value' => $map_distribution['openlayers']['custom_wms_base_layer']['proj4js_def'],
2049
      '#description' => 'The <a href="http://trac.osgeo.org/openlayers/wiki/Documentation/Dev/proj4js">proj4js definition</a> for the projection named above.
2050
            The definitions for
2051
            EPSG:102067, EPSG:102757, EPSG:102758, EPSG:21781, EPSG:26591, EPSG:26912, EPSG:27200, EPSG:27563, EPSG:3857,
2052
            EPSG:41001, EPSG:4139, EPSG:4181, EPSG:42304, EPSG:4272, EPSG:4302, EPSG:900913
2053
            are already predefined and must be added here again.  If your dont know the defintion of your desired projection,
2054
            go to  <a href="http://spatialreference.org/">http://spatialreference.org/</a>, search for your projection and
2055
            choose to display the proj4js definition string.
2056
            <h5>Quick Reference on the commion proj4js definition parameters:</h5>
2057
            <pre>
2058
+a         Semimajor radius of the ellipsoid axis
2059
+alpha     ? Used with Oblique Mercator and possibly a few others
2060
+axis      Axis orientation (new in 4.8.0)
2061
+b         Semiminor radius of the ellipsoid axis
2062
+datum     Datum name (see `proj -ld`)
2063
+ellps     Ellipsoid name (see `proj -le`)
2064
+k         Scaling factor (old name)
2065
+k_0       Scaling factor (new name)
2066
+lat_0     Latitude of origin
2067
+lat_1     Latitude of first standard parallel
2068
+lat_2     Latitude of second standard parallel
2069
+lat_ts    Latitude of true scale
2070
+lon_0     Central meridian
2071
+lonc      ? Longitude used with Oblique Mercator and possibly a few others
2072
+lon_wrap  Center longitude to use for wrapping (see below)
2073
+nadgrids  Filename of NTv2 grid file to use for datum transforms (see below)
2074
+no_defs   Don\'t use the /usr/share/proj/proj_def.dat defaults file
2075
+over      Allow longitude output outside -180 to 180 range, disables wrapping (see below)
2076
+pm        Alternate prime meridian (typically a city name, see below)
2077
+proj      Projection name (see `proj -l`)
2078
+south     Denotes southern hemisphere UTM zone
2079
+to_meter  Multiplier to convert map units to 1.0m
2080
+towgs84   3 or 7 term datum transform parameters (see below)
2081
+units     meters, US survey feet, etc.
2082
+vto_meter vertical conversion to meters.
2083
+vunits    vertical units.
2084
+x_0       False easting
2085
+y_0       False northing
2086
+zone      UTM zone
2087
            </pre>
2088
          For the full reference please refer to <a href="http://trac.osgeo.org/proj/wiki/GenParms">http://trac.osgeo.org/proj/wiki/GenParms</a>.'
2089
  );
2090
  $form[CDM_MAP_DISTRIBUTION]['openlayers']['custom_wms_base_layer']['max_extent'] = array(
2091
      '#type' => 'textfield',
2092
      '#title' => 'Maximum extent',
2093
      // Only line color by now.
2094
      '#default_value' => $map_distribution['openlayers']['custom_wms_base_layer']['max_extent'],
2095
      '#description' => 'The maximum extent of the map as bounding box (left, bottom, right, top) in the units of the map.'
2096
  );
2097
  $form[CDM_MAP_DISTRIBUTION]['openlayers']['custom_wms_base_layer']['units'] = array(
2098
      '#type' => 'textfield',
2099
      '#title' => 'Units',
2100
      '#default_value' => $map_distribution['openlayers']['custom_wms_base_layer']['units'],
2101
      '#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.'
2102
  );
2103

    
2104
  /*
2105
   * Map Legend
2106
   */
2107
  $form[CDM_MAP_DISTRIBUTION]['legend'] = array(
2108
    '#type' => 'fieldset',
2109
    '#title' => 'Map legend',
2110
    '#tree' => TRUE,
2111
    '#collapsible' => TRUE,
2112
    '#collapsed' => TRUE,
2113
    '#description' => 'Configure the maps legend.',
2114
  );
2115

    
2116
  $form[CDM_MAP_DISTRIBUTION]['legend']['show'] = array(
2117
    '#type' => 'checkbox',
2118
    '#title' => 'Display a map legend',
2119
    '#default_value' => $map_distribution['legend']['show'],
2120
    '#description' => 'Check this if you like a legend to be displayed with the maps.',
2121
  );
2122

    
2123
  $form[CDM_MAP_DISTRIBUTION]['legend']['opacity'] = array(
2124
    '#type' => 'textfield',
2125
    '#title' => 'Legend opacity',
2126
    '#default_value' => $map_distribution['legend']['opacity'],
2127
    '#description' => 'Valid values range from 0.0 to 1.0. Value 1.0 means the legend will be fully visible, while a value near
2128
                         to 0.0 will be not much visible.',
2129
  );
2130

    
2131
  $form[CDM_MAP_DISTRIBUTION]['legend']['font_size'] = array(
2132
    '#type' => 'textfield',
2133
    '#title' => 'Font size',
2134
    '#default_value' => $map_distribution['legend']['font_size'],
2135
    '#description' => 'Font size in pixels.',
2136
  );
2137

    
2138
  $fontStyles = array(
2139
    0 => "plane",
2140
    1 => "italic",
2141
  );
2142
  $form[CDM_MAP_DISTRIBUTION]['legend']['font_style'] = array(
2143
    '#type' => 'select',
2144
    '#title' => 'Available font styles',
2145
    '#default_value' => $map_distribution['legend']['font_style'],
2146
    '#options' => $fontStyles,
2147
    '#description' => 'Select a font style for the map legend.',
2148
  );
2149

    
2150
  $form[CDM_MAP_DISTRIBUTION]['legend']['icon_width'] = array(
2151
    '#type' => 'textfield',
2152
    '#title' => 'Icon width',
2153
    '#default_value' => $map_distribution['legend']['icon_width'],
2154
    '#description' => 'Legend icon width in pixels.',
2155
  );
2156
  $form[CDM_MAP_DISTRIBUTION]['legend']['icon_height'] = array(
2157
    '#type' => 'textfield',
2158
    '#title' => 'Icon height',
2159
    '#default_value' => $map_distribution['legend']['icon_height'],
2160
    '#description' => 'Legend icon height in pixels.',
2161
  );
2162

    
2163
  // @WA: D7 form api does not support reset buttons,
2164
  // so to mimic the D5 reset button we add one like this.
2165
  $form['actions']['reset'] = array(
2166
    '#markup' => '<input id="reset" type="reset" class="form-submit" value="' . t('Reset to defaults') . '" />',
2167
    '#weight' => 1000,
2168
  );
2169

    
2170
  return system_settings_form($form);
2171
}
2172

    
2173
/**
2174
 * @todo document this function.
2175
 */
2176
function cdm_settings_cache() {
2177

    
2178
  $form = array();
2179

    
2180
  $form['cache_settings'] = array(
2181
    '#type' => 'fieldset',
2182
    '#title' => t('Cache Settings'),
2183
    '#collapsible' => FALSE,
2184
    '#collapsed' => FALSE,
2185
    '#description' => t('<p>When caching is enabled all single taxon sites are
2186
      stored in an internal drupal cache doing the portal response of taxa pages
2187
      faster. This is possible because the sites are loaded from the cache and
2188
      are not created from scratch.</p>'),
2189
  );
2190

    
2191
  $form['cache_settings']['cdm_webservice_cache'] = array(
2192
    '#type' => 'checkbox',
2193
    '#title' => t('<strong>Enable caching</strong>'),
2194
    '#options' => cdm_help_general_cache(),
2195
    '#default_value' => variable_get('cdm_webservice_cache', 1),
2196
    '#description' => t('<p>Enable drupal to load taxa pages from the cache.</p>
2197
       <p><strong>Note:</strong> If taxa are modified by the editor or any other
2198
       application the changes will be not visible till the cache is erased.
2199
       Therefore developers should deactived this feature when they are working
2200
       on the CDM Dataportal Module.</p>'),
2201
  );
2202

    
2203
  $form['cache_settings']['cdm_run_cache'] = array(
2204
    '#markup' => cdm_view_cache_site(),
2205
  );
2206

    
2207
  // @WA: D7 form api does not support reset buttons,
2208
  // so to mimic the D5 reset button we add one like this.
2209
  $form['actions']['reset'] = array(
2210
    '#markup' => '<input id="reset" type="reset" class="form-submit" value="' . t('Reset to defaults') . '" />',
2211
    '#weight' => 1000,
2212
  );
2213
  return system_settings_form($form);
2214
}
2215

    
2216
/**
2217
 * Walk and cache all taxon pages.
2218
 */
2219
function cdm_view_cache_site() {
2220

    
2221
  $out = '';
2222

    
2223
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/cache_all_taxa.js');
2224

    
2225
  $request_params = array();
2226
  $request_params['class'] = "Taxon";
2227

    
2228
  $cdm_ws_page_taxa_url = cdm_compose_url(CDM_WS_TAXON . ".json", NULL, queryString($request_params));
2229
  $cdm_ws_page_taxa_url = uri_uriByProxy($cdm_ws_page_taxa_url);
2230
  $cdm_ws_page_taxa_url = rtrim($cdm_ws_page_taxa_url, '/');
2231

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

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

    
2241
  // Comment @WA: A form within a form is not valid html and not needed here.
2242
  // Also, it would be recommended just to include this part of the form in the
2243
  // rest of the form array in cdm_settings_cache().
2244
  // $out .= '<form id="cache_site">';
2245
  $out .= '<input type="hidden" name="pageTaxaUrl" value="' . $cdm_ws_page_taxa_url . '"/>';
2246
  $out .= '<input type="hidden" name="taxonPageUrl" value="' . url('cdm_dataportal/taxon/') . '"/>';
2247
  $out .= '<input type="button" name="start" value="' . t('Start') . '"/>';
2248
  $out .= '<input type="button" name="stop" value="' . t('Stop') . '"/>';
2249
  // $out .= '</form>';
2250
  $out .= '</div>';
2251
  /*
2252
  foreach($taxonPager->records as $taxon){
2253
    cdm_dataportal_taxon_view($uuid);
2254
  }
2255
  */
2256
  return $out;
2257
}
2258

    
2259

    
2260
function cdm_settings_layout_taxon_submit($form, &$form_state){
2261
  if (isset($form_state['values'][CDM_TAXON_PROFILE_IMAGE]['custom_placeholder_image_fid'])) {
2262
    $file = file_load($form_state['values'][CDM_TAXON_PROFILE_IMAGE]['custom_placeholder_image_fid']);
2263
    if(is_object($file)){
2264
      $file->status = FILE_STATUS_PERMANENT;
2265
      file_save($file);
2266
      file_usage_add($file, 'cdm_dataportal', CDM_TAXON_PROFILE_IMAGE, 0);
2267
    }
2268
  }
2269
  // rebuild the menu if the show tabs setting has changed, otherwise the change will not have a consistent effect
2270
  if(variable_get('cdm_dataportal_taxonpage_tabs', 1) != $form_state['values']['cdm_dataportal_taxonpage_tabs']){
2271
    // we first need to set the variable to persist the changes setting
2272
    variable_set('cdm_dataportal_taxonpage_tabs', $form_state['values']['cdm_dataportal_taxonpage_tabs']);
2273
    menu_rebuild();
2274
  }
2275
}
2276

    
2277
function cdm_settings_layout_search_submit($form, &$form_state){
2278
  // the visibility of media thumbnails also affects the ui of the search results
2279
  // so reset the according session variable
2280
  //    1. in order to give the user immediate
2281
  //       feedback on potential setting changes
2282
  //    2. let refresh the default if it has changed
2283
  if (isset($_SESSION['pageoption']['searchtaxa']['showThumbnails'])) {
2284
    unset($_SESSION['pageoption']['searchtaxa']['showThumbnails']);
2285
  }
2286
}
2287

    
2288
/**
2289
 * Form validation handler for cdm_settings_general
2290
 *
2291
 * @param $form
2292
 * @param $form_state
2293
 */
2294
function cdm_settings_general_validate($form, &$form_state) {
2295

    
2296
  if (!str_endsWith($form_state['values']['cdm_webservice_url'], '/')) {
2297
    $form_state['values']['cdm_webservice_url'] .= '/';
2298
  }
2299

    
2300
}
2301

    
2302
/**
2303
 * Form submit handler for settings general.
2304
 *
2305
 * tasks performed:
2306
 *  - clear the [cdm][taxonomictree_uuid] session variable since this taxonomictree_uuid might no longer bee valid
2307
 *
2308
 * @param $form
2309
 * @param $form_state
2310
 */
2311
function cdm_settings_general_submit($form, &$form_state){
2312
  // clear the [cdm][taxonomictree_uuid] session variable since this taxonomictree_uuid might no longer bee valid
2313
  unset($_SESSION['cdm']['taxonomictree_uuid']);
2314
}
2315

    
2316
/**
2317
 * Form validation handler for cdm_settings_cache
2318
 */
2319
function cdm_settings_cache_validate($form, &$form_state) {
2320
  if ($form_state['values']['cdm_webservice_cache'] != variable_get('cdm_webservice_cache', 1)) {
2321
    cache_clear_all(NULL, 'cache_cdm_ws');
2322
    // Better clear secref_cache since I can not be sure if the cache has not
2323
    // be used during this response.
2324
    cdm_api_secref_cache_clear();
2325
  }
2326

    
2327
}
2328

    
2329
/**
2330
 * Returns an associative array of the currently chosen settings for the EDIT map service or the defaults as
2331
 * specified in EDIT_MAPSERVER_URI_DEFAULT and EDIT_MAPSERVER_VERSION_DEFAULT:
2332
 *  - base_uri: the protocol and host part , e.g.: http://edit.africamuseum.be
2333
 *  - version: the version, e.g.: v1.1
2334
 *
2335
 * @return array
2336
 *    An associative array of the currently chosen settings for the EDIT map service or the defaults.
2337
 */
2338
function get_edit_map_service_settings() {
2339

    
2340
  $settings = variable_get('edit_map_server', array(
2341
      'base_uri' => EDIT_MAPSERVER_URI_DEFAULT,
2342
      'version' => EDIT_MAPSERVER_VERSION_DEFAULT
2343
      )
2344
  );
2345
  // replace old non tree like settings by default
2346
  // TODO to be removed after release 3.1.5
2347
  if(!is_array($settings)){
2348
    variable_del('edit_map_server');
2349
    return get_edit_map_service_settings();
2350
  }
2351

    
2352
  return $settings;
2353
}
2354

    
2355
/**
2356
 * Returns the full edit map service URI e.g.: http://edit.africamuseum.be/edit_wp5/v1.1
2357
 *
2358
 * @return string
2359
 *   The full edit map service URI e.g.: http://edit.africamuseum.be/edit_wp5/v1.1
2360
 */
2361
function get_edit_map_service_full_uri() {
2362
  $settings = get_edit_map_service_settings();
2363
  return $settings['base_uri'] . EDIT_MAPSERVER_PATH .  '/' . $settings['version'];
2364
}
2365

    
2366

    
2367
/**
2368
 * Returns the version number of the currently selected edit mapserver as a float
2369
 *
2370
 * @return float
2371
 *   The version number of the currently selected edit mapserver as a float.
2372
 *   Returns 0 on error.
2373
 */
2374
function get_edit_map_service_version_number() {
2375

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

    
2378
  $settings = get_edit_map_service_settings();
2379
  preg_match($pattern, $settings['version'], $matches, PREG_OFFSET_CAPTURE);
2380
  if (isset($matches[1])) {
2381
    // Convert string to float.
2382
    $version = 1 + $matches[1][0] - 1;
2383
    return $version;
2384
  }
2385
  else {
2386
    // Report error.
2387
    drupal_set_message(t(" Invalid EDIT map service version number: '!version'",
2388
        array(
2389
          '!version' => $settings['version'],
2390
          'warning')
2391
        )
2392
      );
2393
    return 0;
2394
  }
2395
}
2396

    
2397
/**
2398
 * Returns the array of selected items in a options array
2399
 *
2400
 * @param array $options
2401
 *   An options array as generated by a form element like checkoxes, select ...,
2402
 */
2403
function get_selection($options) {
2404
  $selection = array();
2405
  foreach ($options as $key=>$val) {
2406
    if (!empty($val)) {
2407
      $selection[] = $val;
2408
    }
2409
  }
2410
  return $selection;
2411
}
2412

    
2413

    
2414
/**
2415
 * Implements hook_element_info().
2416
 *
2417
 * Allows modules to declare their own Form API element types and specify their default values.
2418
 *
2419
 * @see http://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_element_info/7
2420
 */
2421
function cdm_dataportal_element_info() {
2422
  $type['checkboxes_preferred'] = array(
2423
    '#input' => TRUE,
2424
    '#process' => array('checkboxes_preferred_expand'),
2425
    '#after_build' => array('checkboxes_preferred_after_build'),
2426
    '#theme' => array('checkboxes_preferred'),
2427
    // '#theme_wrapper' => array('form_element'),
2428
  );
2429
  return $type;
2430
}
2431

    
2432
/**
2433
 * #process callback function for the custom form element type 'checkbox_preferred'
2434
 *
2435
 *
2436
 */
2437
function checkboxes_preferred_expand($element, &$form_state, $form) {
2438

    
2439
  // First of all create checkboxes for each of the elements
2440
  $element = form_process_checkboxes($element);
2441

    
2442
  // compose the element name
2443
  $parents = array();
2444
  array_deep_copy($element['#parents'], $parents);
2445
  $parents[count($parents) -1 ] .= '_preferred';
2446
  $element_name = $parents[0];
2447
  for ($i=1; $i < count($parents); $i++){
2448
    $element_name .= '[' . $parents[$i] . ']';
2449
  }
2450

    
2451
  $children = element_children($element);
2452

    
2453
  $element['table_start'] = array(
2454
    '#markup' => '<table class="checkboxes_preferred"><tr><th></th><th>' . t('Enabled') . '</th><th>' . t('Default') . '</th></tr>',
2455
    '#weight' => -1,
2456
  );
2457

    
2458
  // prepare first part each of the table rows which contains the row label
2459
  $weight = 0;
2460
  foreach ($children as $key) {
2461
    $odd_even = $weight % 4 == 0 ? 'odd' : 'even';
2462
    $element[$key]['#weight'] = $weight;
2463
    $element[$key]['#prefix'] = '<tr class="' . $odd_even . '"><td>' . t($element['#options'][$key]) . '</td><td>';
2464
    $element[$key]['#suffix'] = '</td>';
2465
    unset($element[$key]['#title']);
2466
    $weight += 2;
2467
  }
2468
  $weight = 0;
2469

    
2470
  // add a radio button to each of the checkboxes, the
2471
  // check boxes have already been created at the beginning
2472
  // of this function
2473
  if (count($element['#options']) > 0) {
2474
    foreach ($element['#options'] as $key => $choice) {
2475
      if (!isset($element[$key . '_preferred'])) {
2476
        $element[$key . '_preferred'] = array(
2477
          '#type' => 'radio',
2478
          '#name' => $element_name,
2479
          '#return_value' => check_plain($key),
2480
          '#default_value' => empty($element['#default_value_2']) ? NULL : $element['#default_value_2'],
2481
          '#attributes' => $element['#attributes'],
2482
          '#parents' => $element['#parents'],
2483
          // '#spawned' => TRUE,
2484
          '#weight' => $weight + 1,
2485
          '#prefix' => '<td>',        // add a prefix to start a new table cell
2486
          '#suffix' => '</td></tr>',  // add a prefix to close the tabel row
2487
        );
2488
      }
2489
      $weight += 2;
2490
    }
2491
  }
2492

    
2493
  // end the table
2494
  $element['table_end'] = array(
2495
    '#markup' => '</table>',
2496
    '#weight' => $weight++,
2497
  );
2498

    
2499
  return $element;
2500
}
2501

    
2502
/**
2503
 * Theme function for the custom form field 'checkboxes_preferred'.
2504
 */
2505
function theme_checkboxes_preferred($variables) {
2506
  $element = $variables['element'];
2507
  $out = '<div id="edit-baselayers-wrapper" class="form-item">';
2508
  $out .= '<label for="edit-baselayers">' . $element['#title'] . '</label>';
2509
  $out .= drupal_render_children($element);
2510
  $out .= '<div class="description">' . $element['#description'] . '</div>';
2511
  $out .= '</div>';
2512
  return $out;
2513
}
2514

    
2515
/**
2516
 * Callback for checkboxes preferred for widget which will
2517
 * be called after the form or element is built. The call
2518
 * back is configured in the form element by setting it as
2519
 * #after_build parameter.
2520
 *
2521
 * @see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#after_build
2522
 *
2523
 * @param $element
2524
 *   Nested array of form elements that comprise the form.
2525
 * @param $form_state
2526
 *   A keyed array containing the current state of the form.
2527
 *   This includes the current persistent storage data for the form.
2528
 *   Additional information, like the sanitized $_POST data,
2529
 *   is also accumulated here in $form_state['input']
2530
 *
2531
 * @return the modified form array
2532
 */
2533
function checkboxes_preferred_after_build($element, &$form_state) {
2534

    
2535
  $parent_id = $element['#parents'][count($element['#parents']) - 1];
2536

    
2537
  if ($_POST && count($_POST) > 0) {
2538
    // TODO use  $form_state['input'] instead of POST !!!
2539
    // First pass of form processing.
2540
    $parents = array();
2541
    array_deep_copy($element['#parents'], $parents);
2542
    $parents[count($parents) - 1] .= '_preferred';
2543
    $preferred_layer = drupal_array_get_nested_value($_POST, $parents);
2544
    $element['#value']['PREFERRED'] = $preferred_layer;
2545
//     $form_state[$parent_id] = $element['#value'];
2546
//     $form_state['values']['baselayers'] = $element['#value'];
2547
    $form_state_element_values = &drupal_array_get_nested_value($form_state['values'], $element['#parents']);
2548
    $form_state_element_values = $element['#value'];
2549
  }
2550
  else {
2551
    // Second pass of form processing.
2552
    $preferred_layer = $element['#value']['PREFERRED'];
2553
  }
2554

    
2555
  // Also set the chosen value (not sure if this is good Drupal style ....).
2556
  foreach ($children = element_children($element) as $key) {
2557
    if (!empty($element[$key]['#type']) && $element[$key]['#type'] == 'radio') {
2558
      $element[$key]['#value'] = $preferred_layer;
2559
    }
2560
  }
2561
  // The default layer must always be enabled.
2562
  $element[$preferred_layer]['#value'] = $preferred_layer;
2563

    
2564
  return $element;
2565
}
2566

    
2567
function radios_prepare_options_suffix(&$elements){
2568

    
2569
  $childrenKeys = element_children($elements);
2570
  foreach($childrenKeys as $key){
2571
    if(!is_array($elements[$key]['#theme_wrappers'])){
2572
      $elements[$key]['#theme_wrappers'] = array();
2573
    }
2574
    if(isset($elements['#options_suffixes'][$key])){
2575
      $elements[$key]['#theme_wrappers'][] = 'radio_options_suffix';
2576
      $elements[$key]['#options_suffix'] = $elements['#options_suffixes'][$key];
2577
    }
2578
  }
2579
  return $elements;
2580

    
2581
}
2582

    
2583
/**
2584
 * TODO
2585
 * @param unknown $variables
2586
 */
2587
function theme_radio_options_suffix($variables) {
2588
  $element = $variables['element'];
2589
  if(isset($element['#options_suffix'])) {
2590
    $element['#children'] .= $element['#options_suffix'];
2591
  }
2592
  return $element['#children'];
2593
}
2594

    
2595

    
2596
/**
2597
 * Element validate callback for text field and arrays containing json.
2598
 *
2599
 * @param $element
2600
 *   The form element to validate
2601
 * @param $form_state
2602
 *   A keyed array containing the current state of the form.
2603
 * @param $form
2604
 *   Nested array of form elements that comprise the form.
2605
 */
2606
function form_element_validate_json($element, &$form_state, $form) {
2607
   if (!empty($element['#value'])) {
2608
     json_decode($element['#value']);
2609
     if(json_last_error() != JSON_ERROR_NONE){
2610
       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/'));
2611
     }
2612
   }
2613
}
2614

    
2615
/**
2616
 * Form submission handler for textareas and textfields containing JSON.
2617
 *
2618
 * The contained JSON will be converted into an php array
2619
 * or object and will be stored in the variables as such.
2620
 *
2621
 * @see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#submit
2622
 *
2623
 * @param $form
2624
 *   Nested array of form elements that comprise the form.
2625
 * @param $form_state
2626
 *   A keyed array containing the current state of the form.
2627
 *
2628
 */
2629
function submit_json_as_php_array($form, &$form_state) {
2630
  if (is_array($form['#json_elements'])) {
2631
    foreach ($form['#json_elements'] as $element){
2632
      if (trim($form_state['values'][$element])) {
2633
        $form_state['values'][$element] = (array) json_decode($form_state['values'][$element]);
2634
      } else {
2635
        $form_state['values'][$element] = NULL;
2636
      }
2637
    }
2638
  }
2639
}
(14-14/14)