Project

General

Profile

Download (107 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
define('DISTRIBUTION_STATUS_COLORS', 'distribution_status_colors');
92

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

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

    
111
$taxon_tab_options = get_taxon_tabs_list();
112
$taxon_tab_options[CDM_DATAPORTAL_LAST_VISITED_TAB_ARRAY_INDEX] = 'Last visited tab';
113

    
114
define('CDM_DATAPORTAL_DEFAULT_TAXON_TAB', serialize($taxon_tab_options));
115

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

    
126
}
127

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

    
198
define('CDM_SEARCH_TAXA_MODE','cdm_search_taxa_mode');
199
define('CDM_SEARCH_TAXA_MODE_DEFAULT', serialize(
200
    // to unset a default enntry set the value to 0
201
    array(
202
      'doTaxa'=>'doTaxa',
203
      'doSynonyms' => 'doSynonyms',
204
      'doTaxaByCommonNames' => 'doTaxaByCommonNames',
205
      'doMisappliedNames' => 'doMisappliedNames'
206
    )
207
  )
208
);
209

    
210
/* Gallery variables. */
211
$gallery_settings = array(
212
    "cdm_dataportal_show_taxon_thumbnails" => 1,
213
    "cdm_dataportal_show_synonym_thumbnails" => 0,
214
    "cdm_dataportal_show_thumbnail_captions" => 1,
215
    "cdm_dataportal_media_maxextend" => 120,
216
    "cdm_dataportal_media_cols" => 3,
217
    "cdm_dataportal_media_maxRows" => 1,
218
);
219

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

    
260
define('CDM_DISTRIBUTION_FILTER', 'cdm_distribution_filter');
261
define('CDM_DISTRIBUTION_FILTER_DEFAULT', serialize(
262
      array(
263
      'filter_rules' => array(
264
        'statusOrderPreference' => 0,
265
        'subAreaPreference' => 0,
266
      ),
267
      'hideMarkedAreas' => array()
268
     )
269
));
270

    
271

    
272
define('CDM_TAXON_MEDIA_FILTER', 'cdm_taxon_media_filter');
273
define('CDM_TAXON_MEDIA_FILTER_DEFAULT', serialize(
274
    array(
275
        'includeTaxonDescriptions' => 'includeTaxonDescriptions',
276
        'includeOccurrences' => 0,
277
        'includeTaxonNameDescriptions' => 0
278
     )
279
  ));
280

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

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

    
343
    // unserialize if nessecary
344
    if(!is_array($default)){
345
      $default = unserialize($default);
346
    }
347
    $variable = variable_get($variable_name, array());
348
    $result = drupal_array_merge_deep($default, $variable);
349
    return $result;
350
}
351

    
352
/**
353
 * @todo document this function.
354
 */
355
function getGallerySettings($gallery_config_form_name) {
356
  return get_array_variable_merged($gallery_config_form_name, CDM_DATAPORTAL_GALLERY_SETTINGS);
357
}
358

    
359
/**
360
 * Returns the string representation of the default tab.
361
 *
362
 * @param bool $returnTabIndex
363
 *   Defaults to FALSE, if set true this function will return the index number
364
 *   of the default tab. (used to supply default values to form elements).
365
 */
366
function get_default_taxon_tab($returnTabIndex = FALSE) {
367

    
368
  global $user;
369
  $values = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
370
  $user_tab_active = 'cdm_dataportal_' . $user->uid . '_default_tab_active';
371
  $user_tab = 'cdm_dataportal_' . $user->uid . '_default_tab';
372
  // Get the user value if the used has chosen to overwrite the system settings.
373
  $user_tab_on = variable_get($user_tab_active, FALSE);
374
  if ($user_tab_on) {
375
    $user_value = variable_get($user_tab, 0);
376
    $index_value = $user_value;
377
    // Get the system value.
378
  }
379
  else {
380
    $system_value = variable_get('cdm_dataportal_default_tab', 0);
381
    $index_value = $system_value;
382
  }
383

    
384
  // Return the index value or the string representation.
385
  if ($returnTabIndex) {
386
    return $index_value;
387
  }
388
  else {
389
    return ($values[$index_value]);
390
  }
391

    
392
}
393

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

    
429
  $items['admin/config/cdm_dataportal/settings/cachesite'] = array(
430
    'title' => 'Cache',
431
    'description' => 'Cache',
432
    'access arguments' => array('administer cdm_dataportal'),
433
    'page callback' => 'drupal_get_form',
434
    'page arguments' => array('cdm_settings_cache'),
435
    'weight' => 10,
436
    'type' => MENU_LOCAL_TASK,
437
  );
438

    
439
  $items['admin/config/cdm_dataportal/settings/geo'] = array(
440
    'title' => 'Geo & Map',
441
    'description' => 'Geo & Map',
442
    'access arguments' => array('administer cdm_dataportal'),
443
    'page callback' => 'drupal_get_form',
444
    'page arguments' => array('cdm_settings_geo'),
445
    'weight' => 1,
446
    'type' => MENU_LOCAL_TASK,
447
  );
448

    
449
  $items['admin/config/cdm_dataportal/settings/layout'] = array(
450
    'title' => 'Layout',
451
    'description' => 'Configure and adjust the layout of your DataPortal ',
452
    'access arguments' => array('administer cdm_dataportal'),
453
    'page callback' => 'drupal_get_form',
454
    'page arguments' => array('cdm_settings_layout'),
455
    'weight' => 2,
456
    'type' => MENU_LOCAL_TASK,
457
  );
458

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

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

    
501
  $items['admin/config/cdm_dataportal/settings/layout/media'] = array(
502
    'title' => 'Media',
503
    'description' => 'Configure and adjust the layout of your DataPortal ',
504
    'access arguments' => array('administer cdm_dataportal'),
505
    'page callback' => 'drupal_get_form',
506
    'page arguments' => array('cdm_settings_layout_media'),
507
    'weight' => 3,
508
    'type' => MENU_LOCAL_TASK,
509
  );
510

    
511
}
512

    
513
/**
514
 * @todo document this function.
515
 */
516
function cdm_help_general_cache() {
517
  $form = array();
518
  $form['cache_help'] = array(
519
    '#type' => 'fieldset',
520
    '#title' => t('Help'),
521
    '#collapsible' => TRUE,
522
    '#collapsed' => TRUE,
523
  );
524
  $form['cache_help']['test'] = array('#value' => t('probando'));
525
  return drupal_render($form);
526
  $res = array();
527
  $res['default'] = drupal_render($help);
528
  return $res;
529
}
530

    
531
/**
532
 * Configures the settings form for the CDM-API module.
533
 *
534
 * @return array
535
 *   Drupal settings form.
536
 */
537
function cdm_settings_general() {
538

    
539
  $form['cdm_webservice'] = array(
540
    '#type' => 'fieldset',
541
    '#title' => t('CDM Server'),
542
    '#collapsible' => FALSE,
543
    '#collapsed' => FALSE,
544
    '#description' => t('The <em>CDM Server</em> exposes data stored in a
545
        CDM data base to the web via RESTful web services and thus is the source of the data
546
        to be displayed by a CDM DataPotal.'),
547
  );
548

    
549
  $form['cdm_webservice']['cdm_webservice_url'] = array(
550
    '#type' => 'textfield',
551
    '#title' => t('CDM web service URL') . ':',
552
    '#description' => t('This is the URL to the CDM-Server exposing your data
553
      e.g. <em>"http://myserver.net/cdmserver/myproject"</em>'),
554
    '#default_value' => variable_get('cdm_webservice_url', NULL),
555
  );
556

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

    
564
  $form['cdm_webservice']['freetext_index'] = array(
565
    '#type' => 'fieldset',
566
    '#title' => t('Freetext index'),
567
    '#collapsible' => FALSE,
568
    '#collapsed' => FALSE,
569
  );
570

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

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

    
598
  $form['cdm_webservice']['proxy'] = array(
599
    '#type' => 'fieldset',
600
    '#title' => t('Proxy'),
601
    '#collapsible' => TRUE,
602
    '#collapsed' => TRUE,
603
  );
604

    
605
  $form['cdm_webservice']['proxy']['cdm_webservice_proxy_url'] = array(
606
    '#type' => 'textfield',
607
    '#title' => t('Proxy URL') . ':',
608
    '#description' => t('If this proxy url is set the cdm api tries
609
    to connect the web service over the given proxy server.
610
    Otherwise proxy usage is deactivated.'),
611
    '#default_value' => variable_get('cdm_webservice_proxy_url', FALSE),
612
  );
613

    
614
  $form['cdm_webservice']['proxy']['cdm_webservice_proxy_port'] = array(
615
    '#type' => 'textfield',
616
    '#title' => t('Proxy port') . ':',
617
    '#default_value' => variable_get('cdm_webservice_proxy_port', '80'),
618
  );
619

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

    
626
  $form['cdm_webservice']['proxy']['cdm_webservice_proxy_pwd'] = array(
627
    '#type' => 'textfield',
628
    '#title' => t('Password') . ':',
629
    '#default_value' => variable_get('cdm_webservice_proxy_pwd', FALSE),
630
  );
631

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

    
648
  $form['taxon_tree'][CDM_TAXONOMICTREE_UUID] = array(
649
    '#type' => 'select',
650
    '#title' => t('Available classifications') . ':',
651
    '#default_value' => variable_get(CDM_TAXONOMICTREE_UUID, FALSE),
652
    '#options' => cdm_get_taxontrees_as_options(),
653
    '#description' => t('Select the default taxa classification for your
654
      <em>taxon tree</em>, the other classifications will be also available but
655
      with a manual user change.'),
656
  );
657

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

    
669
  $classification_uuids = array_keys(cdm_get_taxontrees_as_options());
670
  $taxontree_includes_default = array_combine($classification_uuids, $classification_uuids);
671
  $form['taxon_tree'][CDM_TAXONTREE_INCLUDES] = array(
672
      '#type' => 'checkboxes',
673
      '#title' => t('Included Classifications') . ':',
674
      '#default_value' => variable_get(CDM_TAXONTREE_INCLUDES, $taxontree_includes_default),
675
      '#options' => cdm_get_taxontrees_as_options(),
676
      '#description' => t('Only the checked classifications will be avaliable in the classification chooser.'),
677
  );
678

    
679
  $form['distribution'] = array(
680
      '#type' => 'fieldset',
681
      '#title' => t('Distributions'),
682
      '#collapsible' => FALSE,
683
      '#description' => 'This section covers general settings regarding distributions, map related settings are found in the '
684
          . l('geo & map tab', 'admin/config/cdm_dataportal/settings/geo') .
685
          '<p>
686
          </p>',
687
  );
688

    
689
  $form['distribution'][CDM_DISTRIBUTION_FILTER] = array(
690
      '#type' => 'fieldset',
691
      '#title' => 'Distribution filter',
692
      '#collapsible' => FALSE,
693
      '#collapsed' => FALSE,
694
      '#tree' => TRUE,
695
      '#description' => 'The Distribution filter offers the following options
696
      <ul>
697
      <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>
698
      <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>
699
      <li><strong>Marked area filter:</strong>Skip distributions where the area has a Marker with one of the specified MarkerTypes</li>
700
      </ul>'
701
  );
702

    
703
  $cdm_distribution_filter = get_array_variable_merged(CDM_DISTRIBUTION_FILTER, CDM_DISTRIBUTION_FILTER_DEFAULT);
704
  $form['distribution'][CDM_DISTRIBUTION_FILTER]['filter_rules'] = array(
705
      '#type' => 'checkboxes',
706
      '#title' => 'Filter rules',
707
      '#default_value' => $cdm_distribution_filter['filter_rules'],
708
      '#options' => array(
709
          'statusOrderPreference' => 'Status order preference rule',
710
          'subAreaPreference' => 'Sub area preference rule'
711
      ),
712
  );
713

    
714
  $marker_type_options = cdm_terms_as_options( cdm_ws_fetch_all('term', array('class' => 'MarkerType' )) );
715
  $form['distribution'][CDM_DISTRIBUTION_FILTER]['hideMarkedAreas'] = array(
716
      '#type' => 'checkboxes',
717
      '#title' => 'Hide marked area filter',
718
      '#default_value' => $cdm_distribution_filter['hideMarkedAreas'],
719
      '#options' => $marker_type_options,
720
      '#description' => 'Check one or more MarkerTypes to define the "hide marked area" filter .',
721
  );
722

    
723
  $form['aggregation'] = array(
724
      '#type' => 'fieldset',
725
      '#title' => t('Aggregation of data'),
726
      '#collapsible' => FALSE,
727
      '#description' => 'This section covers the different aspects of aggregating information.
728
          <p>
729
          </p>',
730
  );
731

    
732
  $form['aggregation'][CDM_TAXON_MEDIA_FILTER] = array(
733
      '#type' => 'checkboxes',
734
      '#title' => 'Taxon media filter',
735
      '#default_value' => variable_get(CDM_TAXON_MEDIA_FILTER, unserialize(CDM_TAXON_MEDIA_FILTER_DEFAULT)),
736
      '#options' => array(
737
          'includeTaxonDescriptions' => 'Media in taxon descriptions',
738
          'includeTaxonNameDescriptions' => 'Media in name descriptions',
739
          'includeOccurrences' => 'Media related to specimens and occurrences',
740
      ),
741
      '#description' => 'This filter configures which images should be taken into account.',
742
  );
743

    
744
  $form['aggregation']['notice'] = array(
745
      '#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
746
          want to make use of the caching capabilities of the dataportal.',
747
  );
748

    
749
  $form['aggregation']['media_aggregation'] = array(
750
      '#type' => 'fieldset',
751
      '#title' => t('Media aggregation'),
752
      '#collapsible' => FALSE,
753
      '#collapsed' => TRUE,
754
      '#description' => t("The media aggregation is also affected by the settigs in \"<strong>Aggregation via taxon relationsships</strong>\" below."),
755

    
756
  );
757
  $form['aggregation']['media_aggregation']['cdm_images_include_children'] = array(
758
      '#type' => 'select',
759
      '#title' => t('Aggregation of taxon pictures') . ':',
760
      '#default_value' => variable_get('cdm_images_include_children', FALSE),
761
      '#options' => array(
762
          0 => "Show only pictures of the current taxon",
763
          1 => "Include pictures of taxonomic children",
764
      ),
765
      '#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."),
766
  );
767

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

    
782
  $taxonRelationshipTypeOptions = cdm_Vocabulary_as_option(UUID_TAXON_RELATIONSHIP_TYPE, '_cdm_relationship_type_term_label_callback');
783
  $aggregate_by_taxon_relationships = variable_get(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS, unserialize(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS_DEFAULT));
784

    
785
  $form['aggregation']['aggregate_by_taxon_relationships'][CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS]['direct'] = array(
786
      '#type' => 'checkboxes',
787
      '#title' => t('Direct'),
788
      '#options' => $taxonRelationshipTypeOptions,
789
      '#default_value' => $aggregate_by_taxon_relationships['direct'],
790
  );
791
  $form['aggregation']['aggregate_by_taxon_relationships'][CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS]['invers'] = array(
792
      '#type' => 'checkboxes',
793
      '#title' => t('Invers'),
794
      '#options' => $taxonRelationshipTypeOptions,
795
      '#default_value' => $aggregate_by_taxon_relationships['invers'],
796
  );
797

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

    
823
  // Comment @WA: D7 form api does not support reset buttons,
824
  // so to mimic the D5 reset button we add one like this.
825
  $form['actions']['reset'] = array(
826
    '#markup' => '<input id="reset" type="reset" class="form-submit" value="' . t('Reset to defaults') . '" />',
827
    '#weight' => 1000,
828
  );
829

    
830
  $form['#submit'][] = 'cdm_settings_general_submit';
831

    
832
  return system_settings_form($form);
833
}
834

    
835

    
836
/**
837
 * LAYOUT settings
838
 * @return unknown_type
839
 *   todo
840
 */
841
function cdm_settings_layout() {
842

    
843
  $form = array();
844

    
845
  $form['about'] = array(
846
    '#markup' => '<h4>' . t('Portal Layout') . '</h4><p>' . t('This settings contains the general configurations
847
      layout. If you want to configure the specific sites layout visit the
848
      respective configuration site for taxon, search or media.') . '</p>',
849
  );
850

    
851
  // ---- footnotes --- //
852
  $form['footnotes'] = array(
853
    '#type' => 'fieldset',
854
    '#title' => t('Footnotes'),
855
    '#collapsible' => FALSE,
856
    '#collapsed' => FALSE,
857
    '#description' => t('Taxa data such authors, synonyms names, descriptions,
858
      media or distribution areas may have annotations or footnotes. When the
859
      footnotes are enabled they will be visible (if they exist).'),
860
  );
861

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

    
869
  $form['footnotes']['cdm_dataportal_annotations_footnotes'] = array(
870
    '#type' => 'checkbox',
871
    '#title' => t('Do not show annotations footnotes'),
872
    '#default_value' => variable_get('cdm_dataportal_annotations_footnotes', CDM_DATAPORTAL_ANNOTATIONS_FOOTNOTES),
873
    '#description' => t('Check this if you do not want to show annotation footnotes'),
874
  );
875

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

    
891
  // --- Advanced Search --- //
892
  $form['asearch'] = array(
893
      '#type' => 'fieldset',
894
      '#title' => t('Advanced search'),
895
      '#collapsible' => FALSE,
896
      '#collapsed' => FALSE,
897
  );
898
  $form['asearch']['cdm_dataportal_show_advanced_search'] = array(
899
      '#type' => 'checkbox',
900
      '#title' => t('Show advanced search link'),
901
      '#default_value' => variable_get('cdm_dataportal_show_advanced_search', 1),
902
      '#description' => t('Check this box if the link to advanced search should be show below the search box.'),
903
  );
904

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

    
916
  drupal_add_js(
917
      'jQuery(document).ready( function( ) {
918
         // pretty print json
919
         var json_text = jQuery(\'#edit-' . CDM_PART_DEFINITIONS . '\').val();
920
         var obj = JSON.parse(json_text);
921
         jQuery(\'#edit-' . CDM_PART_DEFINITIONS . '\').val(JSON.stringify(obj, undefined, 2));
922

    
923
         json_text = jQuery(\'#edit-' . CDM_NAME_RENDER_TEMPLATES . '\').val();
924
         obj = JSON.parse(json_text);
925
         jQuery(\'#edit-' . CDM_NAME_RENDER_TEMPLATES . '\').val(JSON.stringify(obj, undefined, 2));
926
       });'
927
      ,array(
928
          'type' => 'inline',
929
          'scope' => 'footer'
930
      )
931
  );
932

    
933
  $default_part_definitions = unserialize(CDM_PART_DEFINITIONS_DEFAULT);
934

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

    
1023
  $default_render_templates = unserialize(CDM_NAME_RENDER_TEMPLATES_DEFAULT);
1024

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

    
1064
  // @WA: D7 form api does not support reset buttons,
1065
  // so to mimic the D5 reset button we add one like this.
1066
  $form['actions']['reset'] = array(
1067
    '#markup' => '<input id="reset" type="reset" class="form-submit" value="' . t('Reset to defaults') . '" />',
1068
    '#weight' => 1000,
1069
  );
1070

    
1071
  $form['#submit'] = array('submit_json_as_php_array');
1072
  // #json_elements especially defined for submit_json_as_php_array()
1073
  $form['#json_elements'] = array(CDM_NAME_RENDER_TEMPLATES, CDM_PART_DEFINITIONS);
1074
  return system_settings_form($form);
1075
}
1076

    
1077

    
1078
/**
1079
 * @todo Please document this function.
1080
 * @see http://drupal.org/node/1354
1081
 */
1082
function cdm_dataportal_create_gallery_settings_form($form_name, $form_title, $collapsed, $form_description = '') {
1083
  $form[$form_name] = array(
1084
    '#type' => 'fieldset',
1085
    '#title' => t($form_title),
1086
    '#collapsible' => TRUE,
1087
    '#collapsed' => $collapsed,
1088
    '#tree' => TRUE,
1089
    '#description' => t($form_description),
1090
  );
1091

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

    
1111
    $form[$form_name]['cdm_dataportal_show_synonym_thumbnails'] = array(
1112
      '#type' => 'checkbox',
1113
      '#title' => t('Show media thumbnails for synonyms'),
1114
      '#default_value' => $gallery_settings['cdm_dataportal_show_synonym_thumbnails'],
1115
      '#description' => '',
1116
    );
1117
  }
1118

    
1119
  // $showCaption = variable_get('cdm_dataportal_findtaxa_show_thumbnail_captions', 0);
1120
  $form[$form_name]['cdm_dataportal_show_thumbnail_captions'] = array(
1121
    '#type' => 'checkbox',
1122
    '#title' => t('Show captions under thumbnails'),
1123
    '#default_value' => $gallery_settings['cdm_dataportal_show_thumbnail_captions'],
1124
    '#description' => '',
1125
  );
1126

    
1127
  $form[$form_name]['cdm_dataportal_media_maxextend'] = array(
1128
    '#type' => 'textfield',
1129
    '#title' => t('Thumbnail size') . ':',
1130
    '#default_value' => $gallery_settings['cdm_dataportal_media_maxextend'],
1131
    '#description' => t('Select the size of each individual thumbnail.'),
1132
  );
1133

    
1134
  if ($form_name != CDM_DATAPORTAL_MEDIA_GALLERY_NAME) {
1135
    $form[$form_name]['cdm_dataportal_media_cols'] = array(
1136
      '#type' => 'textfield',
1137
      '#title' => t('Number of columns') . ':',
1138
      '#default_value' => $gallery_settings['cdm_dataportal_media_cols'],
1139
      '#description' => t('Group the thumbnails in columns: select how many
1140
        columns the gallery should display.'),
1141
    );
1142
  }
1143

    
1144
  if ($form_name == CDM_DATAPORTAL_SEARCH_GALLERY_NAME) {
1145
    $form[$form_name]['cdm_dataportal_media_maxRows'] = array(
1146
      '#type' => 'textfield',
1147
      '#title' => t('Maximum number of rows') . ':',
1148
      '#default_value' => $gallery_settings['cdm_dataportal_media_maxRows'],
1149
      '#description' => t('You can group the thumbnails in rows, select in how
1150
        many rows should be the thumbnails grouped.<br/><strong>Note:</strong>
1151
        If you want an unlimited number of rows please set to 0.'),
1152
    );
1153
  }
1154

    
1155
  return $form;
1156
}
1157

    
1158
/**
1159
 * @todo document this function.
1160
 */
1161
function cdm_settings_layout_taxon() {
1162
  $collapsed = FALSE;
1163
  $form = array();
1164

    
1165
  $form['#submit'][] = 'cdm_settings_layout_taxon_submit';
1166

    
1167
  $form['cdm_dataportal_show_back_to_search_results'] = array(
1168
      '#type' => 'checkbox',
1169
      '#title' => t('Show <em>Back to search results</em> link at the taxon site.'),
1170
      '#default_value' => variable_get('cdm_dataportal_show_back_to_search_results', 1),
1171
      '#description' => t('<p>If checked the link to search results is rendered at
1172
       the top of the taxon site. Clicking on the link the last search performed
1173
       is rendered again.</p>'),
1174
  );
1175

    
1176
  // --------- TABBED TAXON ------- //
1177
  $form['taxon_tabs'] = array(
1178
    '#type' => 'fieldset',
1179
    '#title' => t('Taxon tabs'),
1180
    '#collapsible' => TRUE,
1181
    '#collapsed' => FALSE,
1182
    '#description' => t('If tabbed taxon page is enabled the taxon profile will
1183
      be splitted in four diferent tabs; General, Synonymy, Images and
1184
      Specimens. If the taxon has no information for any of the tabs/sections
1185
      such tab will be not displayed.'),
1186
  );
1187

    
1188
  $form['taxon_tabs']['cdm_dataportal_taxonpage_tabs'] = array(
1189
    '#type' => 'checkbox',
1190
    '#title' => t('Tabbed taxon page'),
1191
    '#default_value' => variable_get('cdm_dataportal_taxonpage_tabs', 1),
1192
    '#description' => t('<p>If selected split the taxon page into individual
1193
      tabs for description, images, synonymy and specimens. If not the taxon
1194
      data is rendered as a long single page without tabs.</p>'),
1195
  );
1196

    
1197
  $form['taxon_tabs']['cdm_taxonpage_tabs_visibility'] = array(
1198
    '#type' => 'checkboxes',
1199
    '#title' => t('Tabs visibility options') . ':',
1200
    '#default_value' => variable_get('cdm_taxonpage_tabs_visibility', get_taxon_options_list()),
1201
    '#options' => get_taxon_options_list(),
1202
    '#description' => t('Enable or disable Tabs in the Tabbed page display'),
1203
  );
1204

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

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

    
1235
  /* ======  TAXON_PROFILE ====== */
1236
  $form['taxon_profile'] = array(
1237
    '#type' => 'fieldset',
1238
    '#title' => t('Taxon profile (tab)'),
1239
    '#description' => t('<p>This section covers the settings related to the taxon
1240
      profile tab, also known as the <strong>"General"</strong> tab.</p>'),
1241
    '#collapsible' => TRUE,
1242
    '#collapsed' => TRUE,
1243
  );
1244

    
1245
  // ---- PROFILE PICTURE ----//
1246

    
1247
  $form['taxon_profile'][CDM_TAXON_PROFILE_IMAGE] = array(
1248
    '#type' => 'fieldset',
1249
    '#tree' => TRUE,
1250
    '#title' => t('Taxon profile picture'),
1251
    '#collapsible' => TRUE,
1252
    '#collapsed' => FALSE,
1253
    '#description' => t('This sections allows configuring the display of the so called taxon profile image which is displayed in the taxon profile tab.'),
1254
  );
1255

    
1256
  //FIXME migrate variables:
1257
  //  cdm_dataportal_show_default_image ---> CDM_TAXON_PROFILE_IMAGE['show']
1258
  // FIXME
1259
  //  eanable file modul in profile and in update
1260

    
1261
  $taxon_profile_image_settings = variable_get(CDM_TAXON_PROFILE_IMAGE, unserialize(CDM_TAXON_PROFILE_IMAGE_DEFAULT));
1262
  /*
1263
   * 'show' => 1,
1264
   * 'maxextend' => 184,
1265
   * 'media_uri_query' => ''
1266
   * 'custom_placeholder_image_on' => 1,
1267
   * 'custom_placeholder_image_fid' => ''
1268
   */
1269
  $form['taxon_profile'][CDM_TAXON_PROFILE_IMAGE]['show'] = array(
1270
    '#type' => 'checkbox',
1271
    '#title' => t('Enable profil picture'),
1272
    '#description' => t('Show the profil picture.'),
1273
    '#default_value' => $taxon_profile_image_settings['show'],
1274
  );
1275

    
1276
  $form['taxon_profile'][CDM_TAXON_PROFILE_IMAGE]['maxextend'] = array(
1277
      '#type' => 'textfield',
1278
      '#tree' => TRUE,
1279
      '#title' => t('Profil picture maximum extend'),
1280
      '#default_value' =>  $taxon_profile_image_settings['maxextend'],
1281
      '#field_suffix' => 'px',
1282
      '#maxlength' => 4,
1283
      '#size' => 4,
1284
      '#description' => t('The maximum extend in either dimension, width or height, of the profil picture in pixels.')
1285
  );
1286

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

    
1300
  $form['taxon_profile'][CDM_TAXON_PROFILE_IMAGE]['custom_placeholder_image_on'] = array(
1301
      '#type' => 'checkbox',
1302
      '#title' => t('Use a custom placeholder image'),
1303
      '#description' => t("This image is shown as replacement if no image of the taxon is available."),
1304
      '#default_value' => $taxon_profile_image_settings['custom_placeholder_image_on']
1305
  );
1306

    
1307
  if($taxon_profile_image_settings['custom_placeholder_image_on'] == 1){
1308
    $form['taxon_profile'][CDM_TAXON_PROFILE_IMAGE]['custom_placeholder_image_fid'] = array(
1309
        '#type' => 'managed_file',
1310
        '#title' => t('Custom placeholder image file'),
1311
        '#progress_indicator' => 'bar',
1312
        '#default_value' => $taxon_profile_image_settings['custom_placeholder_image_fid'],
1313
    //       '#name' => 'custom_placeholder_image',
1314
        '#upload_location' => 'public://' . CDM_TAXON_PROFILE_IMAGE .'/'
1315
    );
1316

    
1317
    if($taxon_profile_image_settings['custom_placeholder_image_fid']){
1318
      $profile_image_file = file_load($taxon_profile_image_settings['custom_placeholder_image_fid']);
1319
      $url = file_create_url($profile_image_file->uri);
1320
      $form['taxon_profile'][CDM_TAXON_PROFILE_IMAGE]['preview'] = array(
1321
                '#type' => 'item',
1322
                '#markup' => '<div class="image-preview"><img src="' . $url . '"/></div>',
1323
      );
1324
    }
1325
  } else {
1326
    $form['taxon_profile'][CDM_TAXON_PROFILE_IMAGE]['custom_placeholder_image_fid'] = array(
1327
        '#type' => 'hidden',
1328
        '#default_value' => $taxon_profile_image_settings['custom_placeholder_image_fid']
1329
    );
1330
  }
1331

    
1332

    
1333

    
1334
  $options = cdm_rankVocabulary_as_option();
1335
  array_unshift($options, '-- DISABLED --');
1336
  $form['taxon_profile']['picture']['image_hide_rank'] = array(
1337
    '#type' => 'select',
1338
    '#title' => t('Hide profile picture for higher ranks') . ':',
1339
    '#default_value' => variable_get('image_hide_rank', '0'),
1340
    '#options' => $options,
1341
    '#description' => t('The taxon profile picture will not be shown for taxa with rank higher that the selected.'),
1342
  );
1343

    
1344
  // -- MEDIA THUMBNAILS -- //
1345
  $form_name = CDM_DATAPORTAL_DESCRIPTION_GALLERY_NAME;
1346
  $form_title = 'Taxon Profile Images';
1347
  $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>';
1348
  $form['taxon_profile'][] = cdm_dataportal_create_gallery_settings_form($form_name, $form_title, $collapsed, $form_description);
1349

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

    
1395
  // ---- LAYOUT PER FEATURE ---- //
1396
  $feature_tree = get_profile_featureTree();
1397
  if (isset($feature_tree->root->childNodes)) {
1398

    
1399
    $form_feature_list_layout = array(
1400
      '#title' => t('Taxon profile layout'),
1401
      '#collapsible' => TRUE,
1402
      '#collapsed' => FALSE,
1403
      '#type' => 'fieldset',
1404
      '#description' => t('Will be available in a future release.'),
1405
    );
1406

    
1407
    $feature_list_layout_settings_disabled = TRUE;
1408
    foreach ($feature_tree->root->childNodes as $featureNode) {
1409

    
1410
      if (!$feature_list_layout_settings_disabled && isset($featureNode->feature)) {
1411
        // Must not exceed 45 characters !!!
1412
        $subform_id = LAYOUT_SETTING_PREFIX . $featureNode->feature->uuid;
1413

    
1414
        $settings = mixed_variable_get($subform_id, FEATURE_TREE_LAYOUT_DEFAULTS);
1415
        $systemDefaults = unserialize(FEATURE_TREE_LAYOUT_DEFAULTS);
1416

    
1417
        $form_feature_list_layout[$subform_id] = array(
1418
          '#tree' => TRUE,
1419
          '#title' => 'test' . $featureNode->feature->representation_L10n,
1420
          '#collapsible' => FALSE,
1421
          '#collapsed' => FALSE,
1422
          '#type' => 'fieldset',
1423
          '#description' => t(''),
1424
        );
1425

    
1426
        $form_feature_list_layout[$subform_id]['enabled'] = array(
1427
          '#type' => 'checkbox',
1428
          '#title' => t('Enable'),
1429
          '#default_value' => $settings['enabled'],
1430
          '#description' => t('Enable user defined layout for this feature'),
1431
        );
1432

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

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

    
1449
        $form_feature_list_layout[$subform_id]['glue'] = array(
1450
          '#type' => 'textfield',
1451
          '#title' => t('Glue'),
1452
          '#disabled' => !$settings['enabled'],
1453
          '#default_value' => $settings['glue'],
1454
          '#description' => t('Default is: ') . "'<code>" . $systemDefaults['glue'] . "</code>'",
1455
        );
1456

    
1457
      }
1458

    
1459
      $form['taxon_profile']['feature_list_layout'] = $form_feature_list_layout;
1460
    }
1461
  }
1462

    
1463
  // ---- DISTRIBUTION LAYOUT ---- //
1464
  $form['taxon_profile']['distribution_layout'] = array(
1465
    '#title' => t('Distribution'),
1466
    '#collapsible' => TRUE,
1467
    '#collapsed' => FALSE,
1468
    '#type' => 'fieldset',
1469
    '#description' => t('Select if you want to sort or not the distribution text
1470
      located below the distribution map.'),
1471
  );
1472

    
1473
  $form['taxon_profile']['distribution_layout']['distribution_sort'] = array(
1474
    '#type' => 'radios',
1475
    '#title' => t('Sort') . ':',
1476
    '#default_value' => variable_get('distribution_sort', 'NO_SORT'),
1477
    '#options' => array(
1478
      'NO_SORT' => t('Standard (No sort)'),
1479
      'HIDE_TDWG2' => t('Sorted without TDWG Level 2'),
1480
    ),
1481
  );
1482

    
1483
  $form['taxon_profile']['distribution_layout'][DISTRIBUTION_TEXTDATA_DISPLAY_ON_TOP] = array(
1484
    '#type' => 'checkbox',
1485
    '#title' => t('Show TextData elements on top of the map'),
1486
    '#default_value' => variable_get(DISTRIBUTION_TEXTDATA_DISPLAY_ON_TOP, 0),
1487
    '#description' => t('Check this if you want to appear all <code>TextData</code>
1488
      elements on top of the map. Otherwise all <code>TextData</code>
1489
      distribution elements will be listed below the other area elements.
1490
      This option is useful if you need to have descriptive texts for each
1491
      distribution map.'),
1492
  );
1493

    
1494
  $form['taxon_profile'][DISTRIBUTION_STATUS_COLORS] = array(
1495
      '#type' => 'textarea',
1496
      '#title' => t('Custom status colors'),
1497
      '#element_validate' => array('form_element_validate_json'),
1498
      '#default_value' => variable_get(DISTRIBUTION_STATUS_COLORS, ''),
1499
      '#description' => t('<strong>EXPERIMENTAL!</strong><br/>This may be changed in the next release without notification.
1500
          A json map object with StatusTerm.idInVocabulary as key and a hex color as value. e.g: <code>{"n":"#ff0000","p":"#00ff00"}</code>.
1501
          reference list of the idInVocabulary valued of absence and presence terms:
1502
<pre>
1503
c = CULTIVATED
1504
e = ENDEMIC_FOR_THE_RELEVANT_AREA
1505
i = INTRODUCED
1506
ia = INTRODUCED_ADVENTITIOUS
1507
ic = INTRODUCED_CULTIVATED
1508
id = INTRODUCED_DOUBTFULLY_INTRODUCED
1509
in = INTRODUCED_NATURALIZED
1510
ip = INTRODUCED_UNCERTAIN_DEGREE_OF_NATURALISATION
1511
iq = INTRODUCED_PRESENCE_QUESTIONABLE
1512
n = NATIVE
1513
nd = NATIVE_DOUBTFULLY_NATIVE
1514
nq = NATIVE_PRESENCE_QUESTIONABLE
1515
p = PRESENT
1516
na = NATURALISED
1517
iv = INVASIVE
1518
cf = CULTIVATED_REPORTED_IN_ERROR
1519
if = INTRODUCED_REPORTED_IN_ERROR
1520
nf = NATIVE_REPORTED_IN_ERROR
1521
ne = NATIVE_FORMERLY_NATIVE
1522
ie = INTRODUCED_FORMERLY_INTRODUCED
1523
</pre>'),
1524
  );
1525

    
1526

    
1527
  /* ====== SYNONYMY ====== */
1528
  $form['taxon_synonymy'] = array(
1529
    '#type' => 'fieldset',
1530
    '#title' => t('Taxon synonymy (tab)'),
1531
    '#collapsible' => TRUE,
1532
    '#collapsed' => TRUE,
1533
    '#description' => t('This section covers the settings related to the taxon
1534
      <strong>synonymy</strong> tab.'),
1535
  );
1536

    
1537
  $form['taxon_synonymy']['cdm_dataportal_nomref_in_title'] = array(
1538
    '#type' => 'checkbox',
1539
    '#title' => t('Show accepted taxon on top of the synonymy'),
1540
    '#default_value' => variable_get('cdm_dataportal_nomref_in_title', CDM_DATAPORTAL_NOMREF_IN_TITLE),
1541
    '#description' => t('If checked, the first homotypic taxon is a repetition
1542
      of the accepted taxon most likely with the full nomenclatural reference
1543
      (depending on the currently chosen theme).'),
1544
  );
1545

    
1546
  $form['taxon_synonymy']['cdm_dataportal_display_is_accepted_for'] = array(
1547
    '#type' => 'checkbox',
1548
    '#title' => t('Display <em>is accepted for ...</em> on taxon pages when
1549
      coming from a synonym link.'),
1550
    '#default_value' => variable_get('cdm_dataportal_display_is_accepted_for', CDM_DATAPORTAL_DISPLAY_IS_ACCEPTED_FOR),
1551
    '#description' => t('Check this if after doing a search and clicking on a
1552
      synonym you want to see the "accept of" text for the accepted synonym.'),
1553
  );
1554

    
1555
  /* === currently unused ===
1556
  $nameRelationshipTypeOptions = cdm_Vocabulary_as_option(UUID_NAME_RELATIONSHIP_TYPE);
1557
  $form['taxon_synonymy']['name_relationships']['name_relationships_to_show'] = array(
1558
    '#type' => 'checkboxes',
1559
    '#title' => t('Display name relationships') . ':',
1560
    '#default_value' => variable_get('name_relationships_to_show', 0),
1561
    '#options' => $nameRelationshipTypeOptions,
1562
    '#description' => t('Select the name relationships you want to show for the
1563
      accepted taxa.'),
1564
  );
1565
 */
1566

    
1567
  $form['taxon_synonymy'][CDM_DATAPORTAL_DISPLAY_TAXON_RELATIONSHIPS] = array(
1568
    '#type' => 'checkbox',
1569
    '#title' => t('Show taxon relations ships of accepted taxon'),
1570
    '#default_value' => variable_get(CDM_DATAPORTAL_DISPLAY_TAXON_RELATIONSHIPS, CDM_DATAPORTAL_DISPLAY_TAXON_RELATIONSHIPS_DEFAULT),
1571
    '#description' => t('If this option is enabled the synonymy will show the
1572
      below selected taxon relationships of accepted taxa.'),
1573
  );
1574

    
1575
  $taxonRelationshipTypeOptions = cdm_Vocabulary_as_option(UUID_TAXON_RELATIONSHIP_TYPE, '_cdm_relationship_type_term_label_callback');
1576
  $form['taxon_synonymy'][CDM_TAXON_RELATIONSHIP_TYPES] = array(
1577
    '#type' => 'checkboxes',
1578
    '#title' => t('Taxon relationship types') . ':',
1579
    '#description' => t('Only taxon relationships of the selected type will be
1580
      displayed'),
1581
    '#options' => $taxonRelationshipTypeOptions,
1582
    '#default_value' => variable_get(CDM_TAXON_RELATIONSHIP_TYPES, unserialize(CDM_TAXON_RELATIONSHIP_TYPES_DEFAULT)),
1583
    '#disabled' => !variable_get(CDM_DATAPORTAL_DISPLAY_TAXON_RELATIONSHIPS, CDM_DATAPORTAL_DISPLAY_TAXON_RELATIONSHIPS_DEFAULT),
1584
  );
1585

    
1586
  // ====== SPECIMENS ====== //
1587
  $form['taxon_specimens'] = array(
1588
    '#type' => 'fieldset',
1589
    '#title' => t('Taxon specimens (tab)'),
1590
    '#collapsible' => TRUE,
1591
    '#collapsed' => TRUE,
1592
    '#description' => t('This section covers the settings related to the taxon
1593
      <strong>specimens</strong> tab.'),
1594
  );
1595

    
1596
  $featureTrees = cdm_get_featureTrees_as_options(TRUE);
1597
  $saved_uuid = variable_get(CDM_OCCURRENCE_FEATURETREE_UUID, UUID_DEFAULT_FEATURETREE);
1598
  if(!isset($featureTrees['options'][$saved_uuid])) {
1599
    $saved_uuid = UUID_DEFAULT_FEATURETREE;
1600
  }
1601
  $form['taxon_specimens']['feature_trees'][CDM_OCCURRENCE_FEATURETREE_UUID] = array(
1602
      '#type' => 'radios',
1603
      '#title' => t('Specimen description feature tree') . ':',
1604
      '#default_value' => $saved_uuid,
1605
      '#options' =>  $featureTrees['options'],
1606
      '#pre_render' => array('form_pre_render_conditional_form_element', 'radios_prepare_options_suffix'),
1607
      '#options_suffixes' => $featureTrees['treeRepresentations'],
1608
      '#description' => t('Select the feature tree to be used for displaying specimen descriptions. Click "Show Details" to see the Feature Tree elements.'
1609
      ),
1610
  );
1611

    
1612
  $form_name = CDM_DATAPORTAL_SPECIMEN_GALLERY_NAME;
1613
  $form_title = t('Specimen media');
1614
  $form_description = t('Specimens may have media which is displayed at the
1615
     Specimen tab/section as a gallery. It is possible to configure the
1616
     thumbnails gallery here, however for configuring how a single media should
1617
     be displayed please go to !url.</p>',
1618
     array(
1619
       '!url' => l(t('Layout -> Media'), 'admin/config/cdm_dataportal/settings/layout/media'),
1620
     ));
1621
  $form['taxon_specimens'][] = cdm_dataportal_create_gallery_settings_form($form_name, $form_title, FALSE, $form_description);
1622

    
1623
  // --- MEDIA GALLERY ---- //
1624
  $form_name = CDM_DATAPORTAL_TAXON_MEDIA_GALLERY_NAME_TAB;
1625
  $form_title = 'Media gallery (tab)';
1626
  $form_description = '<p>This section covers the settings related to the taxon <strong>media</strong> tab.
1627
   Taxa may have media (usually images) and they are as thumbnails displayed. It is possible to configure
1628
   the thumbnails gallery here, however for configuring how a single media should be displayed please go to
1629
   <a href="./?q=admin/settings/cdm_dataportal/layout/media">Layout -&gt; Media</a></p>
1630
   <p><strong>Note:</strong> These settings are only taken into account when the standard
1631
   gallery viewer is selected at <a href="./?q=admin/settings/cdm_dataportal/layout/media">Layout -&gt; Media</a>.</p>';
1632
  $form['taxon_media'][] = cdm_dataportal_create_gallery_settings_form($form_name, $form_title, TRUE, $form_description);
1633

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

    
1643
/**
1644
 * @todo document this function.
1645
 */
1646
function cdm_settings_layout_search() {
1647

    
1648
  $form = array();
1649

    
1650
  $form['#submit'][] = 'cdm_settings_layout_search_submit';
1651

    
1652
  $form['search_settings'] = array(
1653
    '#type' => 'fieldset',
1654
    '#title' => t('Taxa Search'),
1655
    '#collapsible' => FALSE,
1656
    '#collapsed' => FALSE,
1657
    '#description' => t('<p>The data portal allows the users to perform searchs.</p><p>To perform searchs
1658
         the block <em>CDM Taxon Search</em> should be enabled and visible for users
1659
         where they can write the text to be searched. You can find Drupal block configuration
1660
         site at <a href="./?q=admin/build/block">Administer&#45&#62Site building&#45&#62Blocks</a></p> '),
1661
  );
1662

    
1663
  $form['search_settings']['simple_search_ignore_classification'] = array(
1664
      '#type' => 'checkbox',
1665
      '#title' => t('Ignore the chosen classification in simple search'),
1666
      '#default_value' => variable_get('simple_search_ignore_classification', TRUE),
1667
      '#description' => t('The simple search, which can be executed via the search block,
1668
          will by default search on all classifications. Remove the tick if you want your
1669
          portal to search on the classification selected in the classification browser
1670
          selector.'),
1671
  );
1672

    
1673
  $form['search_settings']['cdm_dataportal_search_items_on_page'] = array(
1674
    '#type' => 'textfield',
1675
    '#title' => t('Results per page') . ':',
1676
    '#default_value' => variable_get('cdm_dataportal_search_items_on_page', CDM_DATAPORTAL_SEARCH_ITEMS_ON_PAGE),
1677
    '#description' => t('Number of results to display per page.'),
1678
  );
1679

    
1680
  $search_mode_default = get_array_variable_merged(CDM_SEARCH_TAXA_MODE, CDM_SEARCH_TAXA_MODE_DEFAULT);
1681
  $form['search_settings']['cdm_search_taxa_mode'] = array(
1682
      '#type' => 'checkboxes',
1683
      '#title' => 'Search mode',
1684
      '#description' => 'The taxon search can operate in different modes in order to find only taxa, synonyms,
1685
          taxa by its common name and even taxa which have been used as misappied names. The settings made here will affect the default
1686
          for the advance search form and the behaviour of the simple search form which always will behave according to the
1687
          defaults set here.',
1688
      '#options' => drupal_map_assoc(array_keys(unserialize(CDM_SEARCH_TAXA_MODE_DEFAULT))),
1689
      '#default_value' => $search_mode_default
1690
      );
1691

    
1692
  // --- SEARCH TAXA GALLERY ---- //
1693
  $items = variable_get('cdm_dataportal_search_items_on_page', CDM_DATAPORTAL_SEARCH_ITEMS_ON_PAGE);
1694
  $collapsed = FALSE;
1695
  $form_name = CDM_DATAPORTAL_SEARCH_GALLERY_NAME;
1696
  $form_title = 'Taxa Search thumbnails';
1697
  $form_description = 'Search results may show thumbnails. ';
1698
  $form[] = cdm_dataportal_create_gallery_settings_form($form_name, $form_title, $collapsed, $form_description);
1699

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

    
1709
/**
1710
 * @todo document this function.
1711
 */
1712
function cdm_settings_layout_media() {
1713

    
1714
  $form = array();
1715

    
1716
  $form['media_settings'] = array(
1717
    '#type' => 'fieldset',
1718
    '#title' => t('Media settings'),
1719
    '#collapsible' => FALSE,
1720
    '#collapsed' => FALSE,
1721
    '#description' => 'This section covers layout settings for media pages.'
1722
      . 'Further media related settings may be found under the taxon layout settings and on the general settings.',
1723
  );
1724

    
1725
  $form['media_settings']['image_gallery_viewer'] = array(
1726
    '#type' => 'select',
1727
    '#title' => t('Image viewer') . ':',
1728
    '#default_value' => variable_get('image_gallery_viewer', 'default'),
1729
    '#options' => array(
1730
      'default' => t('Standard image viewer'),
1731
      'fsi' => t('FSI viewer (requires FSI server!)'),
1732
    ),
1733
  );
1734

    
1735
  // --- MEDIA GALLERY ---- //
1736
  $form_name = CDM_DATAPORTAL_MEDIA_GALLERY_NAME;
1737
  $form_title = 'Standard viewer';
1738
  $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>';
1739
  // $form[] = cdm_dataportal_create_gallery_settings_form($form_name, $form_title, $collapsed);
1740
  $form['media_settings'][] = cdm_dataportal_create_gallery_settings_form($form_name, $form_title, FALSE, $form_description);
1741

    
1742
  // @WA: D7 form api does not support reset buttons,
1743
  // so to mimic the D5 reset button we add one like this.
1744
  $form['actions']['reset'] = array(
1745
    '#markup' => '<input id="reset" type="reset" class="form-submit" value="' . t('Reset to defaults') . '" />',
1746
    '#weight' => 1000,
1747
  );
1748
  return system_settings_form($form);
1749
}
1750

    
1751
/**
1752
 * GEOSERVICE and Map settings.
1753
 */
1754
function cdm_settings_geo($form, &$form_state) {
1755

    
1756
  $current_geoserver_settings = get_edit_map_service_settings();
1757
  $map_distribution = get_array_variable_merged(CDM_MAP_DISTRIBUTION, CDM_MAP_DISTRIBUTION_DEFAULT);
1758
  // The default layer must always be enabled
1759
  $preferred_layer = $map_distribution['openlayers']['base_layers']['PREFERRED'];
1760
  $map_distribution['openlayers']['base_layers'][$preferred_layer] = $preferred_layer;
1761

    
1762
  $form = array();
1763

    
1764
  $dummy_distribution_query = NULL;
1765
  if($map_distribution['map_type'] != 1){
1766
    // we need to apply a dummy query since the map serice requires for image maps
1767
    // at least as and ad to be defined
1768
    $dummy_distribution_query = "as=a:339966&ad=tdwg1:a:1,2,3,4,5,6,7,8,9";
1769
  }
1770
  $form['map_preview'] = array(
1771
      '#type' => 'fieldset',
1772
      '#tree' => FALSE,
1773
      '#title' => t('Map preview'),
1774
      '#collapsible' => FALSE,
1775
      '#description' => 'The preview of the map'
1776
       . ($dummy_distribution_query != null ?
1777
           ' may not be accurate in case if image maps, please check the map display in the taxon pages.':
1778
           '.<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.')
1779
  );
1780
  $form['map_preview']['map'] = compose_map(NULL, $dummy_distribution_query, NULL,
1781
      array(
1782
          'move' => "this.cdmOpenlayersMap.printInfo",
1783
          '#execute' => "this.cdmOpenlayersMap.printInfo"
1784
      )
1785
  );
1786

    
1787

    
1788
  /*
1789
   * GEO SERVER
1790
   */
1791
  $form['edit_map_server'] = array(
1792
    '#type' => 'fieldset',
1793
    '#tree' => true,
1794
    '#title' => t('EDIT map service'),
1795
    '#collapsible' => TRUE,
1796
    '#collapsed' => TRUE,
1797
    '#description' => t('Configuration and selection of your geo server.
1798
      The Geo Server is responsible for generating the maps.'),
1799
  );
1800

    
1801
  $form['edit_map_server']['base_uri'] = array(
1802
    '#type' => 'select',
1803
    '#title' => t('EDIT map service') . ':',
1804
    '#default_value' => $current_geoserver_settings['base_uri'],
1805
    '#options' => unserialize(EDIT_MAPSERVER_URI),
1806
    '#description' => t('Select the EDIT map server you want to use within your data portal.'),
1807
  );
1808
  $form['edit_map_server']['version'] = array(
1809
      '#type' => 'select',
1810
      '#title' => t('Version') . ':',
1811
      '#default_value' => $current_geoserver_settings['version'],
1812
      '#options' => unserialize(EDIT_MAPSERVER_VERSION),
1813
      '#description' => t('The version of the EDIT map services'),
1814
  );
1815

    
1816
  $localhostkey = 'ABQIAAAAFho6eHAcUOTHLmH9IYHAeBRi_j0U6kJrkFvY4-OX2XYmEAa76BTsyMmEq-tn6nFNtD2UdEGvfhvoCQ';
1817
  $gmap_api_key = variable_get('gmap_api_key', 'ABQIAAAAFho6eHAcUOTHLmH9IYHAeBRi_j0U6kJrkFvY4-OX2XYmEAa76BTsyMmEq-tn6nFNtD2UdEGvfhvoCQ');
1818
  $form['gmap_api_key'] = array(
1819
      '#type' => 'textfield',
1820
      '#title' => t('Google maps API key') . ':',
1821
      '#default_value' => variable_get('gmap_api_key', $gmap_api_key),
1822
      '#description' => t('If you want to use the Google Maps Layer, a key is
1823
      needed. If you need a key, visit
1824
      <a href="http://code.google.com/intl/en/apis/maps/signup.html">google maps api key</a>.
1825
      <br/><strong>Note:</strong> The following key: <code>!localhostkey</code>
1826
      is the default key for the localhost (127.0.0.1).',
1827
      array('!localhostkey' => $localhostkey)),
1828
  );
1829

    
1830

    
1831
  /*
1832
   * MAP SETTINGS
1833
   */
1834

    
1835
  $form[CDM_MAP_DISTRIBUTION] = array(
1836
    '#type' => 'fieldset',
1837
    '#tree' => TRUE,
1838
    '#title' => t('Maps settings'),
1839
    '#collapsible' => TRUE,
1840
    '#collapsed' => TRUE,
1841
    '#description' => t('General configuration for all map types.'),
1842
  );
1843

    
1844
  /*
1845
   * settings for the distribution map are used also for specimens map!!!!
1846
   */
1847

    
1848
  $form[CDM_MAP_DISTRIBUTION]['width'] = array(
1849
    '#type' => 'textfield',
1850
    '#title' => 'Width',
1851
    '#default_value' => $map_distribution['width'],
1852
    '#maxlength' => 4,
1853
    '#size' => 4,
1854
    '#description' => 'Width of the map. To allow OSM baselayers to zoom out to the full extend of the world the map width must be
1855
      a multiple of 256px since the osm tiles from tile.openstreetmap.org have a size of 256px x 256px and frational zoom
1856
      levels are not possible in this case.',
1857
  );
1858
  $form[CDM_MAP_DISTRIBUTION]['height'] = array(
1859
      '#type' => 'textfield',
1860
      '#title' => 'Height',
1861
      '#default_value' => $map_distribution['height'],
1862
      '#maxlength' => 4,
1863
      '#size' => 4,
1864
      '#description' => 'Height of the map. Depending on the chosen base layer you may want to choose the height equal
1865
      to the width or half of the width. Any other aspect ratio is also possible if desired.',
1866
  );
1867

    
1868
  $form[CDM_MAP_DISTRIBUTION]['bbox'] = array(
1869
    '#type' => 'textfield',
1870
    '#title' => 'Bounding box',
1871
    '#default_value' => $map_distribution['bbox'],
1872
    '#description' => t('The bounding box (left, bottom, right, top) defines the area to be initially displayed in maps.
1873
      Use "-180,-90,180,90" for the whole world. Leave <strong>empty</strong>
1874
      to let the map <strong>automatically zoom</strong> to the bounds enclosing the shown data.</p>
1875
      <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.
1876
      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
1877
      below the map from where you can copy the bbox string.</p>'),
1878
  );
1879

    
1880
  $form[CDM_MAP_DISTRIBUTION]['show_labels'] = array(
1881
    '#type' => 'checkbox',
1882
    '#title' => 'Display area labels',
1883
    '#default_value' => $map_distribution['show_labels'],
1884
    '#description' => t('The map will show name labels of the areas'),
1885
  );
1886

    
1887
  $form[CDM_MAP_DISTRIBUTION]['caption'] = array(
1888
    '#type' => 'textfield',
1889
    '#title' => 'Map caption',
1890
    '#default_value' => $map_distribution['caption'],
1891
    '#description' => t('The caption will be shown below the map.'),
1892
  );
1893

    
1894
  $form[CDM_MAP_DISTRIBUTION]['distribution_opacity'] = array(
1895
    '#type' => 'textfield',
1896
    '#title' => 'Distribution layer opacity',
1897
    '#default_value' => $map_distribution['distribution_opacity'],
1898
    '#description' => t('Valid values range from 0.0 to 1.0. Value 1.0 means the distributions (the countries or regions) will
1899
                           fully visible, while a value near to 0.0 will be not much visible.'),
1900
  );
1901

    
1902
  $form[CDM_MAP_DISTRIBUTION]['map_type'] = array(
1903
    '#type' => 'radios',
1904
    '#title' => 'Map types',
1905
    '#options' => array(
1906
      1 => "OpenLayers dynamic map viewer",
1907
      0 => "Plain image",
1908
    ),
1909
    '#default_value' => $map_distribution['map_type'],
1910
    '#description' => 'Two different map types are available :
1911
      <ul><li><em>OpenLayers</em>: Display the maps in an interactive viewer
1912
      which allows zooming and panning. If enabled you can configure the default layer
1913
      (background of your maps) below.</li>
1914
      <li><em>Plain image</em>: The map will be static non interactive
1915
      image.</li></ul>',
1916
  );
1917
  $open_layers_is_enabled = $map_distribution['map_type'] == 1;
1918

    
1919

    
1920
  // --- Plain Image Settings --- //
1921
  $form[CDM_MAP_DISTRIBUTION]['image_map'] = array(
1922
    '#type' => 'fieldset',
1923
    '#title' => 'Plain image map settings',
1924
    '#tree' => TRUE,
1925
    '#collapsible' => TRUE,
1926
    '#collapsed' => $open_layers_is_enabled,
1927
    '#description' => 'The settings in this section are still expertimental
1928
      and can only be used with the EDIT map service version 1.1 or above.',
1929
  );
1930
  $edit_mapserver_version = get_edit_map_service_version_number();
1931
  if ($edit_mapserver_version < 1.1) {
1932
    $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>'
1933
      . $form[CDM_MAP_DISTRIBUTION]['image_map']['#description'];
1934
  }
1935

    
1936
  $form[CDM_MAP_DISTRIBUTION]['image_map']['base_layer'] = array(
1937
    '#type' => 'textfield',
1938
    '#title' => 'Background layer',
1939
    '#default_value' => $map_distribution['image_map']['base_layer'],
1940
    '#description' => t('Background layer. For available layers inspect !url1 or !url2.', array(
1941
      '!url1' => l('deegree-csw', 'http://edit.africamuseum.be:8080/deegree-csw/md_search.jsp'),
1942
      '!url2' => l('geoserver layers', 'http://edit.africamuseum.be/geoserver/web/'),
1943
    )),
1944
  );
1945

    
1946
  $form[CDM_MAP_DISTRIBUTION]['image_map']['bg_color'] = array(
1947
    '#type' => 'textfield',
1948
    '#title' => 'Background color',
1949
    '#default_value' => $map_distribution['image_map']['bg_color'],
1950
  );
1951

    
1952
  $form[CDM_MAP_DISTRIBUTION]['image_map']['layer_style'] = array(
1953
    '#type' => 'textfield',
1954
    '#title' => 'Background layer style',
1955
     // Only line color by now.
1956
    '#default_value' => $map_distribution['image_map']['layer_style'],
1957
    '#description' => 'Syntax: {Area fill color},{Area stroke color},{Area stroke width},{Area stroke dash style}',
1958
  );
1959

    
1960
  $form[CDM_MAP_DISTRIBUTION]['image_map']['projection'] = array(
1961
      '#type' => 'textfield',
1962
      '#title' => 'Projection',
1963
      '#default_value' => drupal_array_get_nested_value($map_distribution, array('image_map', 'projection')),
1964
      '#description' => 'Spatial Reference System (SRS) identifier ) optional ( Defines projections in WMS GetMap request.
1965
        Using EPSG:4326 (WGS84 lat/long) is the default but can be changed
1966
        on-the-fly to different UTM and much more zone specific. Examples: EPSG:4326, EPSG:900913, EPSG:3857, EPSG:7777777',
1967
  );
1968

    
1969

    
1970
  // --- OpenLayers Settings --- //
1971
  $form[CDM_MAP_DISTRIBUTION]['openlayers'] = array(
1972
    '#type' => 'fieldset',
1973
    '#title' => 'OpenLayers settings',
1974
    '#tree' => TRUE,
1975
    '#collapsible' => TRUE,
1976
    '#collapsed' => !$open_layers_is_enabled,
1977
    '#description' => '',
1978
  );
1979

    
1980

    
1981
  $form[CDM_MAP_DISTRIBUTION]['openlayers']['display_outside_max_extent'] = array(
1982
      '#type' => 'checkbox',
1983
      '#title' => 'Display outside max extent',
1984
      '#default_value' => $map_distribution['openlayers']['display_outside_max_extent'],
1985
      '#description' => t('Allows the map to display parts of the layers which are outside
1986
         the max extent if the aspect ratio of the map and of the baselayer
1987
         are not equal.'),
1988
  );
1989

    
1990

    
1991
  $form[CDM_MAP_DISTRIBUTION]['openlayers']['show_layer_switcher'] = array(
1992
      '#type' => 'checkbox',
1993
      '#title' => 'Show Layer Switcher',
1994
      '#default_value' => $map_distribution['openlayers']['show_layer_switcher'],
1995
      '#description' => 'The Layer Switcher control displays a table of contents
1996
      for the map.  This allows the user interface to switch between
1997
      base layers and to show or hide overlays.  By default the switcher is
1998
      shown minimized on the right edge of the map, the user may expand it
1999
      by clicking on the handle.',
2000
  );
2001

    
2002
  if (!$open_layers_is_enabled) {
2003
    $form[CDM_MAP_DISTRIBUTION]['openlayers']['#description'] = '<div class="messages warning">'
2004
        . 'The Openlayers viewer is currently not enabled! (see section Maps settings above )</div>'
2005
        . $form[CDM_MAP_DISTRIBUTION]['openlayers']['#description'];
2006
  }
2007

    
2008
  $baselayer_options = array(
2009
    /*
2010
   NOTICE: must correspond to the layers defined in
2011
   js/openlayers_,ap.js#getLayersByName()
2012
   */
2013
    'osgeo_vmap0' => "Metacarta Vmap0 (OSGeo server)", // EPSG:4326: EPSG:900913
2014
    'metacarta_vmap0' => "Metacarta Vmap0 (MetaCarta Labs server)", // EPSG:4326, EPSG:900913
2015
    // all others EPSG:900913
2016
    // 'edit-vmap0_world_basic' => 'EDIT Vmap0',
2017
    'edit-etopo1' => "ETOPO1 Global Relief Model",
2018
    'mapnik' => 'OpenStreetMap',
2019
    'mapquest_open' => "MapQuest",
2020
    'mapquest_sat' => "MapQuest Sattelite",
2021
//     'osmarender' => 'OpenStreetMap (Tiles@home)',
2022
    'gmap' => 'Google Streets',
2023
    'gsat' => 'Google Satellite',
2024
    'ghyb' => 'Google Hybrid',
2025
//     'veroad' => 'Virtual Earth Roads',
2026
//     'veaer' => 'Virtual Earth Aerial',
2027
//     'vehyb' => 'Virtual Earth Hybrid',
2028
    // 'yahoo' => 'Yahoo Street',
2029
    // 'yahoosat' => 'Yahoo Satellite',
2030
    // 'yahoohyb' => 'Yahoo Hybrid',
2031
     'custom_wms_base_layer_1' => 'Custom WMS base layer (needs to be manually configured below!)',
2032
  );
2033

    
2034
  $form[CDM_MAP_DISTRIBUTION]['openlayers']['base_layers'] = array(
2035
    '#type' => 'checkboxes_preferred',
2036
    '#title' => 'Base Layers',
2037
    '#options' => $baselayer_options,
2038
    '#default_value' =>  $map_distribution['openlayers']['base_layers'],
2039
    '#description' => 'Choose the baselayer layer you prefer to use as map background in the OpenLayers dynamic mapviewer.',
2040
  );
2041

    
2042
  $form[CDM_MAP_DISTRIBUTION]['openlayers']['custom_wms_base_layer'] = array(
2043
      '#type' => 'fieldset',
2044
      '#title' => 'Custom WMS base layer',
2045
      '#tree' => TRUE,
2046
      '#collapsible' => FALSE,
2047
      '#collapsed' => FALSE,
2048
      '#description' => 'Here you an define a custom wms layer as additional base layer.',
2049
  );
2050

    
2051
  $form[CDM_MAP_DISTRIBUTION]['openlayers']['custom_wms_base_layer']['name'] = array(
2052
      '#type' => 'textfield',
2053
      '#title' => 'Layer name',
2054
      // Only line color by now.
2055
      '#default_value' => $map_distribution['openlayers']['custom_wms_base_layer']['name'],
2056
      '#description' => 'A arbitrary name for the layer.',
2057
  );
2058
  $form[CDM_MAP_DISTRIBUTION]['openlayers']['custom_wms_base_layer']['url'] = array(
2059
      '#type' => 'textfield',
2060
      '#title' => 'WMS url',
2061
      // Only line color by now.
2062
      '#default_value' => $map_distribution['openlayers']['custom_wms_base_layer']['url'],
2063
      '#description' => 'Base url for the WMS (e.g.  http://wms.jpl.nasa.gov/wms.cgi)'
2064
  );
2065
  $form[CDM_MAP_DISTRIBUTION]['openlayers']['custom_wms_base_layer']['params'] = array(
2066
      '#type' => 'textarea',
2067
      '#title' => 'WMS parameters',
2068
      '#element_validate' => array('form_element_validate_json'),
2069
      // Only line color by now.
2070
      '#default_value' => $map_distribution['openlayers']['custom_wms_base_layer']['params'],
2071
      '#description' => 'An javasript object with key/value pairs representing the GetMap query string parameters and parameter values, entered in valid JSON. For example:
2072
<pre> {
2073
  "Layers": "topp:em_tiny_jan2003",
2074
  "Format": "image/png",
2075
  "BGCOLOR": "0xe0faff"
2076
}
2077
</pre>'
2078
  );
2079
  $form[CDM_MAP_DISTRIBUTION]['openlayers']['custom_wms_base_layer']['projection'] = array(
2080
      '#type' => 'textfield',
2081
      '#title' => 'Projection',
2082
      // Only line color by now.
2083
      '#default_value' => $map_distribution['openlayers']['custom_wms_base_layer']['projection'],
2084
      '#description' => 'The desired projection for the layer (e.g. EPSG:4326, EPSG:900913, EPSG:3857)'
2085
  );
2086
  $form[CDM_MAP_DISTRIBUTION]['openlayers']['custom_wms_base_layer']['proj4js_def'] = array(
2087
      '#type' => 'textfield',
2088
      '#maxlength' => 256,
2089
      '#title' => 'proj4js definition',
2090
      // Only line color by now.
2091
      '#default_value' => $map_distribution['openlayers']['custom_wms_base_layer']['proj4js_def'],
2092
      '#description' => 'The <a href="http://trac.osgeo.org/openlayers/wiki/Documentation/Dev/proj4js">proj4js definition</a> for the projection named above.
2093
            The definitions for
2094
            EPSG:102067, EPSG:102757, EPSG:102758, EPSG:21781, EPSG:26591, EPSG:26912, EPSG:27200, EPSG:27563, EPSG:3857,
2095
            EPSG:41001, EPSG:4139, EPSG:4181, EPSG:42304, EPSG:4272, EPSG:4302, EPSG:900913
2096
            are already predefined and must be added here again.  If your dont know the defintion of your desired projection,
2097
            go to  <a href="http://spatialreference.org/">http://spatialreference.org/</a>, search for your projection and
2098
            choose to display the proj4js definition string.
2099
            <h5>Quick Reference on the commion proj4js definition parameters:</h5>
2100
            <pre>
2101
+a         Semimajor radius of the ellipsoid axis
2102
+alpha     ? Used with Oblique Mercator and possibly a few others
2103
+axis      Axis orientation (new in 4.8.0)
2104
+b         Semiminor radius of the ellipsoid axis
2105
+datum     Datum name (see `proj -ld`)
2106
+ellps     Ellipsoid name (see `proj -le`)
2107
+k         Scaling factor (old name)
2108
+k_0       Scaling factor (new name)
2109
+lat_0     Latitude of origin
2110
+lat_1     Latitude of first standard parallel
2111
+lat_2     Latitude of second standard parallel
2112
+lat_ts    Latitude of true scale
2113
+lon_0     Central meridian
2114
+lonc      ? Longitude used with Oblique Mercator and possibly a few others
2115
+lon_wrap  Center longitude to use for wrapping (see below)
2116
+nadgrids  Filename of NTv2 grid file to use for datum transforms (see below)
2117
+no_defs   Don\'t use the /usr/share/proj/proj_def.dat defaults file
2118
+over      Allow longitude output outside -180 to 180 range, disables wrapping (see below)
2119
+pm        Alternate prime meridian (typically a city name, see below)
2120
+proj      Projection name (see `proj -l`)
2121
+south     Denotes southern hemisphere UTM zone
2122
+to_meter  Multiplier to convert map units to 1.0m
2123
+towgs84   3 or 7 term datum transform parameters (see below)
2124
+units     meters, US survey feet, etc.
2125
+vto_meter vertical conversion to meters.
2126
+vunits    vertical units.
2127
+x_0       False easting
2128
+y_0       False northing
2129
+zone      UTM zone
2130
            </pre>
2131
          For the full reference please refer to <a href="http://trac.osgeo.org/proj/wiki/GenParms">http://trac.osgeo.org/proj/wiki/GenParms</a>.'
2132
  );
2133
  $form[CDM_MAP_DISTRIBUTION]['openlayers']['custom_wms_base_layer']['max_extent'] = array(
2134
      '#type' => 'textfield',
2135
      '#title' => 'Maximum extent',
2136
      // Only line color by now.
2137
      '#default_value' => $map_distribution['openlayers']['custom_wms_base_layer']['max_extent'],
2138
      '#description' => 'The maximum extent of the map as bounding box (left, bottom, right, top) in the units of the map.'
2139
  );
2140
  $form[CDM_MAP_DISTRIBUTION]['openlayers']['custom_wms_base_layer']['units'] = array(
2141
      '#type' => 'textfield',
2142
      '#title' => 'Units',
2143
      '#default_value' => $map_distribution['openlayers']['custom_wms_base_layer']['units'],
2144
      '#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.'
2145
  );
2146

    
2147
  /*
2148
   * Map Legend
2149
   */
2150
  $form[CDM_MAP_DISTRIBUTION]['legend'] = array(
2151
    '#type' => 'fieldset',
2152
    '#title' => 'Map legend',
2153
    '#tree' => TRUE,
2154
    '#collapsible' => TRUE,
2155
    '#collapsed' => TRUE,
2156
    '#description' => 'Configure the maps legend.',
2157
  );
2158

    
2159
  $form[CDM_MAP_DISTRIBUTION]['legend']['show'] = array(
2160
    '#type' => 'checkbox',
2161
    '#title' => 'Display a map legend',
2162
    '#default_value' => $map_distribution['legend']['show'],
2163
    '#description' => 'Check this if you like a legend to be displayed with the maps.',
2164
  );
2165

    
2166
  $form[CDM_MAP_DISTRIBUTION]['legend']['opacity'] = array(
2167
    '#type' => 'textfield',
2168
    '#title' => 'Legend opacity',
2169
    '#default_value' => $map_distribution['legend']['opacity'],
2170
    '#description' => 'Valid values range from 0.0 to 1.0. Value 1.0 means the legend will be fully visible, while a value near
2171
                         to 0.0 will be not much visible.',
2172
  );
2173

    
2174
  $form[CDM_MAP_DISTRIBUTION]['legend']['font_size'] = array(
2175
    '#type' => 'textfield',
2176
    '#title' => 'Font size',
2177
    '#default_value' => $map_distribution['legend']['font_size'],
2178
    '#description' => 'Font size in pixels.',
2179
  );
2180

    
2181
  $fontStyles = array(
2182
    0 => "plane",
2183
    1 => "italic",
2184
  );
2185
  $form[CDM_MAP_DISTRIBUTION]['legend']['font_style'] = array(
2186
    '#type' => 'select',
2187
    '#title' => 'Available font styles',
2188
    '#default_value' => $map_distribution['legend']['font_style'],
2189
    '#options' => $fontStyles,
2190
    '#description' => 'Select a font style for the map legend.',
2191
  );
2192

    
2193
  $form[CDM_MAP_DISTRIBUTION]['legend']['icon_width'] = array(
2194
    '#type' => 'textfield',
2195
    '#title' => 'Icon width',
2196
    '#default_value' => $map_distribution['legend']['icon_width'],
2197
    '#description' => 'Legend icon width in pixels.',
2198
  );
2199
  $form[CDM_MAP_DISTRIBUTION]['legend']['icon_height'] = array(
2200
    '#type' => 'textfield',
2201
    '#title' => 'Icon height',
2202
    '#default_value' => $map_distribution['legend']['icon_height'],
2203
    '#description' => 'Legend icon height in pixels.',
2204
  );
2205

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

    
2213
  return system_settings_form($form);
2214
}
2215

    
2216
/**
2217
 * @todo document this function.
2218
 */
2219
function cdm_settings_cache() {
2220

    
2221
  $form = array();
2222

    
2223
  $form['cache_settings'] = array(
2224
    '#type' => 'fieldset',
2225
    '#title' => t('Cache Settings'),
2226
    '#collapsible' => FALSE,
2227
    '#collapsed' => FALSE,
2228
    '#description' => t('<p>When caching is enabled all single taxon sites are
2229
      stored in an internal drupal cache doing the portal response of taxa pages
2230
      faster. This is possible because the sites are loaded from the cache and
2231
      are not created from scratch.</p>'),
2232
  );
2233

    
2234
  $form['cache_settings']['cdm_webservice_cache'] = array(
2235
    '#type' => 'checkbox',
2236
    '#title' => t('<strong>Enable caching</strong>'),
2237
    '#options' => cdm_help_general_cache(),
2238
    '#default_value' => variable_get('cdm_webservice_cache', 1),
2239
    '#description' => t('<p>Enable drupal to load taxa pages from the cache.</p>
2240
       <p><strong>Note:</strong> If taxa are modified by the editor or any other
2241
       application the changes will be not visible till the cache is erased.
2242
       Therefore developers should deactived this feature when they are working
2243
       on the CDM Dataportal Module.</p>'),
2244
  );
2245

    
2246
  $form['cache_settings']['cdm_run_cache'] = array(
2247
    '#markup' => cdm_view_cache_site(),
2248
  );
2249

    
2250
  // @WA: D7 form api does not support reset buttons,
2251
  // so to mimic the D5 reset button we add one like this.
2252
  $form['actions']['reset'] = array(
2253
    '#markup' => '<input id="reset" type="reset" class="form-submit" value="' . t('Reset to defaults') . '" />',
2254
    '#weight' => 1000,
2255
  );
2256
  return system_settings_form($form);
2257
}
2258

    
2259
/**
2260
 * Walk and cache all taxon pages.
2261
 */
2262
function cdm_view_cache_site() {
2263

    
2264
  $out = '';
2265

    
2266
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/cache_all_taxa.js');
2267

    
2268
  $request_params = array();
2269
  $request_params['class'] = "Taxon";
2270

    
2271
  $cdm_ws_page_taxa_url = cdm_compose_url(CDM_WS_TAXON . ".json", NULL, queryString($request_params));
2272
  $cdm_ws_page_taxa_url = uri_uriByProxy($cdm_ws_page_taxa_url);
2273
  $cdm_ws_page_taxa_url = rtrim($cdm_ws_page_taxa_url, '/');
2274

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

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

    
2284
  // Comment @WA: A form within a form is not valid html and not needed here.
2285
  // Also, it would be recommended just to include this part of the form in the
2286
  // rest of the form array in cdm_settings_cache().
2287
  // $out .= '<form id="cache_site">';
2288
  $out .= '<input type="hidden" name="pageTaxaUrl" value="' . $cdm_ws_page_taxa_url . '"/>';
2289
  $out .= '<input type="hidden" name="taxonPageUrl" value="' . url('cdm_dataportal/taxon/') . '"/>';
2290
  $out .= '<input type="button" name="start" value="' . t('Start') . '"/>';
2291
  $out .= '<input type="button" name="stop" value="' . t('Stop') . '"/>';
2292
  // $out .= '</form>';
2293
  $out .= '</div>';
2294
  /*
2295
  foreach($taxonPager->records as $taxon){
2296
    cdm_dataportal_taxon_view($uuid);
2297
  }
2298
  */
2299
  return $out;
2300
}
2301

    
2302

    
2303
function cdm_settings_layout_taxon_submit($form, &$form_state){
2304
  if (isset($form_state['values'][CDM_TAXON_PROFILE_IMAGE]['custom_placeholder_image_fid'])) {
2305
    $file = file_load($form_state['values'][CDM_TAXON_PROFILE_IMAGE]['custom_placeholder_image_fid']);
2306
    if(is_object($file)){
2307
      $file->status = FILE_STATUS_PERMANENT;
2308
      file_save($file);
2309
      file_usage_add($file, 'cdm_dataportal', CDM_TAXON_PROFILE_IMAGE, 0);
2310
    }
2311
  }
2312
  // rebuild the menu if the show tabs setting has changed, otherwise the change will not have a consistent effect
2313
  if(variable_get('cdm_dataportal_taxonpage_tabs', 1) != $form_state['values']['cdm_dataportal_taxonpage_tabs']){
2314
    // we first need to set the variable to persist the changes setting
2315
    variable_set('cdm_dataportal_taxonpage_tabs', $form_state['values']['cdm_dataportal_taxonpage_tabs']);
2316
    menu_rebuild();
2317
  }
2318
}
2319

    
2320
function cdm_settings_layout_search_submit($form, &$form_state){
2321
  // the visibility of media thumbnails also affects the ui of the search results
2322
  // so reset the according session variable
2323
  //    1. in order to give the user immediate
2324
  //       feedback on potential setting changes
2325
  //    2. let refresh the default if it has changed
2326
  if (isset($_SESSION['pageoption']['searchtaxa']['showThumbnails'])) {
2327
    unset($_SESSION['pageoption']['searchtaxa']['showThumbnails']);
2328
  }
2329
}
2330

    
2331
/**
2332
 * Form validation handler for cdm_settings_general
2333
 *
2334
 * @param $form
2335
 * @param $form_state
2336
 */
2337
function cdm_settings_general_validate($form, &$form_state) {
2338

    
2339
  if (!str_endsWith($form_state['values']['cdm_webservice_url'], '/')) {
2340
    $form_state['values']['cdm_webservice_url'] .= '/';
2341
  }
2342

    
2343
}
2344

    
2345
/**
2346
 * Form submit handler for settings general.
2347
 *
2348
 * tasks performed:
2349
 *  - clear the [cdm][taxonomictree_uuid] session variable since this taxonomictree_uuid might no longer bee valid
2350
 *
2351
 * @param $form
2352
 * @param $form_state
2353
 */
2354
function cdm_settings_general_submit($form, &$form_state){
2355
  // clear the [cdm][taxonomictree_uuid] session variable since this taxonomictree_uuid might no longer bee valid
2356
  unset($_SESSION['cdm']['taxonomictree_uuid']);
2357
}
2358

    
2359
/**
2360
 * Form validation handler for cdm_settings_cache
2361
 */
2362
function cdm_settings_cache_validate($form, &$form_state) {
2363
  if ($form_state['values']['cdm_webservice_cache'] != variable_get('cdm_webservice_cache', 1)) {
2364
    cache_clear_all(NULL, 'cache_cdm_ws');
2365
    // Better clear secref_cache since I can not be sure if the cache has not
2366
    // be used during this response.
2367
    cdm_api_secref_cache_clear();
2368
  }
2369

    
2370
}
2371

    
2372
/**
2373
 * Returns an associative array of the currently chosen settings for the EDIT map service or the defaults as
2374
 * specified in EDIT_MAPSERVER_URI_DEFAULT and EDIT_MAPSERVER_VERSION_DEFAULT:
2375
 *  - base_uri: the protocol and host part , e.g.: http://edit.africamuseum.be
2376
 *  - version: the version, e.g.: v1.1
2377
 *
2378
 * @return array
2379
 *    An associative array of the currently chosen settings for the EDIT map service or the defaults.
2380
 */
2381
function get_edit_map_service_settings() {
2382

    
2383
  $settings = variable_get('edit_map_server', array(
2384
      'base_uri' => EDIT_MAPSERVER_URI_DEFAULT,
2385
      'version' => EDIT_MAPSERVER_VERSION_DEFAULT
2386
      )
2387
  );
2388
  // replace old non tree like settings by default
2389
  // TODO to be removed after release 3.1.5
2390
  if(!is_array($settings)){
2391
    variable_del('edit_map_server');
2392
    return get_edit_map_service_settings();
2393
  }
2394

    
2395
  return $settings;
2396
}
2397

    
2398
/**
2399
 * Returns the full edit map service URI e.g.: http://edit.africamuseum.be/edit_wp5/v1.1
2400
 *
2401
 * @return string
2402
 *   The full edit map service URI e.g.: http://edit.africamuseum.be/edit_wp5/v1.1
2403
 */
2404
function get_edit_map_service_full_uri() {
2405
  $settings = get_edit_map_service_settings();
2406
  return $settings['base_uri'] . EDIT_MAPSERVER_PATH .  '/' . $settings['version'];
2407
}
2408

    
2409

    
2410
/**
2411
 * Returns the version number of the currently selected edit mapserver as a float
2412
 *
2413
 * @return float
2414
 *   The version number of the currently selected edit mapserver as a float.
2415
 *   Returns 0 on error.
2416
 */
2417
function get_edit_map_service_version_number() {
2418

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

    
2421
  $settings = get_edit_map_service_settings();
2422
  preg_match($pattern, $settings['version'], $matches, PREG_OFFSET_CAPTURE);
2423
  if (isset($matches[1])) {
2424
    // Convert string to float.
2425
    $version = 1 + $matches[1][0] - 1;
2426
    return $version;
2427
  }
2428
  else {
2429
    // Report error.
2430
    drupal_set_message(t(" Invalid EDIT map service version number: '!version'",
2431
        array(
2432
          '!version' => $settings['version'],
2433
          'warning')
2434
        )
2435
      );
2436
    return 0;
2437
  }
2438
}
2439

    
2440
/**
2441
 * Returns the array of selected items in a options array
2442
 *
2443
 * @param array $options
2444
 *   An options array as generated by a form element like checkoxes, select ...,
2445
 */
2446
function get_selection($options) {
2447
  $selection = array();
2448
  foreach ($options as $key=>$val) {
2449
    if (!empty($val)) {
2450
      $selection[] = $val;
2451
    }
2452
  }
2453
  return $selection;
2454
}
2455

    
2456

    
2457
/**
2458
 * Implements hook_element_info().
2459
 *
2460
 * Allows modules to declare their own Form API element types and specify their default values.
2461
 *
2462
 * @see http://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_element_info/7
2463
 */
2464
function cdm_dataportal_element_info() {
2465
  $type['checkboxes_preferred'] = array(
2466
    '#input' => TRUE,
2467
    '#process' => array('checkboxes_preferred_expand'),
2468
    '#after_build' => array('checkboxes_preferred_after_build'),
2469
    '#theme' => array('checkboxes_preferred'),
2470
    // '#theme_wrapper' => array('form_element'),
2471
  );
2472
  return $type;
2473
}
2474

    
2475
/**
2476
 * #process callback function for the custom form element type 'checkbox_preferred'
2477
 *
2478
 *
2479
 */
2480
function checkboxes_preferred_expand($element, &$form_state, $form) {
2481

    
2482
  // First of all create checkboxes for each of the elements
2483
  $element = form_process_checkboxes($element);
2484

    
2485
  // compose the element name
2486
  $parents = array();
2487
  array_deep_copy($element['#parents'], $parents);
2488
  $parents[count($parents) -1 ] .= '_preferred';
2489
  $element_name = $parents[0];
2490
  for ($i=1; $i < count($parents); $i++){
2491
    $element_name .= '[' . $parents[$i] . ']';
2492
  }
2493

    
2494
  $children = element_children($element);
2495

    
2496
  $element['table_start'] = array(
2497
    '#markup' => '<table class="checkboxes_preferred"><tr><th></th><th>' . t('Enabled') . '</th><th>' . t('Default') . '</th></tr>',
2498
    '#weight' => -1,
2499
  );
2500

    
2501
  // prepare first part each of the table rows which contains the row label
2502
  $weight = 0;
2503
  foreach ($children as $key) {
2504
    $odd_even = $weight % 4 == 0 ? 'odd' : 'even';
2505
    $element[$key]['#weight'] = $weight;
2506
    $element[$key]['#prefix'] = '<tr class="' . $odd_even . '"><td>' . t($element['#options'][$key]) . '</td><td>';
2507
    $element[$key]['#suffix'] = '</td>';
2508
    unset($element[$key]['#title']);
2509
    $weight += 2;
2510
  }
2511
  $weight = 0;
2512

    
2513
  // add a radio button to each of the checkboxes, the
2514
  // check boxes have already been created at the beginning
2515
  // of this function
2516
  if (count($element['#options']) > 0) {
2517
    foreach ($element['#options'] as $key => $choice) {
2518
      if (!isset($element[$key . '_preferred'])) {
2519
        $element[$key . '_preferred'] = array(
2520
          '#type' => 'radio',
2521
          '#name' => $element_name,
2522
          '#return_value' => check_plain($key),
2523
          '#default_value' => empty($element['#default_value_2']) ? NULL : $element['#default_value_2'],
2524
          '#attributes' => $element['#attributes'],
2525
          '#parents' => $element['#parents'],
2526
          // '#spawned' => TRUE,
2527
          '#weight' => $weight + 1,
2528
          '#prefix' => '<td>',        // add a prefix to start a new table cell
2529
          '#suffix' => '</td></tr>',  // add a prefix to close the tabel row
2530
        );
2531
      }
2532
      $weight += 2;
2533
    }
2534
  }
2535

    
2536
  // end the table
2537
  $element['table_end'] = array(
2538
    '#markup' => '</table>',
2539
    '#weight' => $weight++,
2540
  );
2541

    
2542
  return $element;
2543
}
2544

    
2545
/**
2546
 * Theme function for the custom form field 'checkboxes_preferred'.
2547
 */
2548
function theme_checkboxes_preferred($variables) {
2549
  $element = $variables['element'];
2550
  $out = '<div id="edit-baselayers-wrapper" class="form-item">';
2551
  $out .= '<label for="edit-baselayers">' . $element['#title'] . '</label>';
2552
  $out .= drupal_render_children($element);
2553
  $out .= '<div class="description">' . $element['#description'] . '</div>';
2554
  $out .= '</div>';
2555
  return $out;
2556
}
2557

    
2558
/**
2559
 * Callback for checkboxes preferred for widget which will
2560
 * be called after the form or element is built. The call
2561
 * back is configured in the form element by setting it as
2562
 * #after_build parameter.
2563
 *
2564
 * @see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#after_build
2565
 *
2566
 * @param $element
2567
 *   Nested array of form elements that comprise the form.
2568
 * @param $form_state
2569
 *   A keyed array containing the current state of the form.
2570
 *   This includes the current persistent storage data for the form.
2571
 *   Additional information, like the sanitized $_POST data,
2572
 *   is also accumulated here in $form_state['input']
2573
 *
2574
 * @return the modified form array
2575
 */
2576
function checkboxes_preferred_after_build($element, &$form_state) {
2577

    
2578
  $parent_id = $element['#parents'][count($element['#parents']) - 1];
2579

    
2580
  if ($_POST && count($_POST) > 0) {
2581
    // TODO use  $form_state['input'] instead of POST !!!
2582
    // First pass of form processing.
2583
    $parents = array();
2584
    array_deep_copy($element['#parents'], $parents);
2585
    $parents[count($parents) - 1] .= '_preferred';
2586
    $preferred_layer = drupal_array_get_nested_value($_POST, $parents);
2587
    $element['#value']['PREFERRED'] = $preferred_layer;
2588
//     $form_state[$parent_id] = $element['#value'];
2589
//     $form_state['values']['baselayers'] = $element['#value'];
2590
    $form_state_element_values = &drupal_array_get_nested_value($form_state['values'], $element['#parents']);
2591
    $form_state_element_values = $element['#value'];
2592
  }
2593
  else {
2594
    // Second pass of form processing.
2595
    $preferred_layer = $element['#value']['PREFERRED'];
2596
  }
2597

    
2598
  // Also set the chosen value (not sure if this is good Drupal style ....).
2599
  foreach ($children = element_children($element) as $key) {
2600
    if (!empty($element[$key]['#type']) && $element[$key]['#type'] == 'radio') {
2601
      $element[$key]['#value'] = $preferred_layer;
2602
    }
2603
  }
2604
  // The default layer must always be enabled.
2605
  $element[$preferred_layer]['#value'] = $preferred_layer;
2606

    
2607
  return $element;
2608
}
2609

    
2610
function radios_prepare_options_suffix(&$elements){
2611

    
2612
  $childrenKeys = element_children($elements);
2613
  foreach($childrenKeys as $key){
2614
    if(!is_array($elements[$key]['#theme_wrappers'])){
2615
      $elements[$key]['#theme_wrappers'] = array();
2616
    }
2617
    if(isset($elements['#options_suffixes'][$key])){
2618
      $elements[$key]['#theme_wrappers'][] = 'radio_options_suffix';
2619
      $elements[$key]['#options_suffix'] = $elements['#options_suffixes'][$key];
2620
    }
2621
  }
2622
  return $elements;
2623

    
2624
}
2625

    
2626
/**
2627
 * TODO
2628
 * @param unknown $variables
2629
 */
2630
function theme_radio_options_suffix($variables) {
2631
  $element = $variables['element'];
2632
  if(isset($element['#options_suffix'])) {
2633
    $element['#children'] .= $element['#options_suffix'];
2634
  }
2635
  return $element['#children'];
2636
}
2637

    
2638

    
2639
/**
2640
 * Element validate callback for text field and arrays containing json.
2641
 *
2642
 * @param $element
2643
 *   The form element to validate
2644
 * @param $form_state
2645
 *   A keyed array containing the current state of the form.
2646
 * @param $form
2647
 *   Nested array of form elements that comprise the form.
2648
 */
2649
function form_element_validate_json($element, &$form_state, $form) {
2650
   if (!empty($element['#value'])) {
2651
     json_decode($element['#value']);
2652
     if(json_last_error() != JSON_ERROR_NONE){
2653
       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/'));
2654
     }
2655
   }
2656
}
2657

    
2658
/**
2659
 * Form submission handler for textareas and textfields containing JSON.
2660
 *
2661
 * The contained JSON will be converted into an php array
2662
 * or object and will be stored in the variables as such.
2663
 *
2664
 * @see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#submit
2665
 *
2666
 * @param $form
2667
 *   Nested array of form elements that comprise the form.
2668
 * @param $form_state
2669
 *   A keyed array containing the current state of the form.
2670
 *
2671
 */
2672
function submit_json_as_php_array($form, &$form_state) {
2673
  if (is_array($form['#json_elements'])) {
2674
    foreach ($form['#json_elements'] as $element){
2675
      if (trim($form_state['values'][$element])) {
2676
        $form_state['values'][$element] = (array) json_decode($form_state['values'][$element]);
2677
      } else {
2678
        $form_state['values'][$element] = NULL;
2679
      }
2680
    }
2681
  }
2682
}
(14-14/14)