Project

General

Profile

Download (86.8 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/**
3
 * @file
4
 * Module to provide a CDM Dataportal.
5
 *
6
 * @copyright
7
 *   (C) 2007-2012 EDIT
8
 *   European Distributed Institute of Taxonomy
9
 *   http://www.e-taxonomy.eu
10
 *
11
 *   The contents of this module are subject to the Mozilla
12
 *   Public License Version 1.1.
13
 * @see http://www.mozilla.org/MPL/MPL-1.1.html
14
 *
15
 * @author
16
 *   - Andreas Kohlbecker <a.kohlbecker@BGBM.org>
17
 *   - Wouter Addink <w.addink@eti.uva.nl> (migration from Drupal 5 to Drupal7)
18
 */
19

    
20
  module_load_include('php', 'cdm_dataportal', 'node_types');
21
  module_load_include('php', 'cdm_dataportal', 'settings');
22
  module_load_include('php', 'cdm_dataportal', 'help');
23
  module_load_include('php', 'cdm_dataportal', 'cdm_dataportal.search');
24

    
25
  module_load_include('inc', 'cdm_dataportal', 'includes/common');
26
  module_load_include('inc', 'cdm_dataportal', 'includes/name');
27
  module_load_include('inc', 'cdm_dataportal', 'includes/taxon');
28
  module_load_include('inc', 'cdm_dataportal', 'includes/references');
29
  module_load_include('inc', 'cdm_dataportal', 'includes/pages');
30
  module_load_include('inc', 'cdm_dataportal', 'includes/media');
31
  module_load_include('inc', 'cdm_dataportal', 'includes/maps');
32
  module_load_include('inc', 'cdm_dataportal', 'includes/occurrences');
33
  module_load_include('inc', 'cdm_dataportal', 'includes/descriptions');
34
  module_load_include('inc', 'cdm_dataportal', 'includes/pre-drupal8');
35

    
36
  module_load_include('inc', 'cdm_dataportal', 'theme/theme_registry');
37
  module_load_include('theme', 'cdm_dataportal', 'theme/cdm_dataportal.common');
38
  module_load_include('theme', 'cdm_dataportal', 'theme/cdm_dataportal.descriptions');
39
  module_load_include('theme', 'cdm_dataportal', 'theme/cdm_dataportal.media');
40
  module_load_include('theme', 'cdm_dataportal', 'theme/cdm_dataportal.occurrence');
41
  module_load_include('theme', 'cdm_dataportal', 'theme/cdm_dataportal.page');
42
  module_load_include('theme', 'cdm_dataportal', 'theme/cdm_dataportal.taxon');
43
  module_load_include('theme', 'cdm_dataportal', 'theme/cdm_dataportal.name');
44
  module_load_include('theme', 'cdm_dataportal', 'theme/cdm_dataportal.references');
45

    
46
  module_load_include('php', 'cdm_dataportal', 'classes/footnotemanager');
47
  module_load_include('php', 'cdm_dataportal', 'classes/footnote');
48
  module_load_include('php', 'cdm_dataportal', 'classes/footnotekey');
49
  module_load_include('php', 'cdm_dataportal', 'classes/renderhints');
50

    
51

    
52
  /* ============================ java script functions ============================= */
53

    
54

    
55
  /**
56
  * loads external java script files asynchronously.
57
  *
58
  * @param unknown_type $script_url
59
  */
60
  function drupal_add_js_async($script_url, $callback){
61

    
62
    drupal_add_js("
63
          jQuery(document).ready(function() {
64
            jQuery.ajax({
65
              url: '" . $script_url . "',
66
              dataType: 'script',
67
              cache: true, // otherwise will get fresh copy every page load
68
              success: function() {
69
                    " . $callback . "
70
              }
71
            });
72
          });"
73
    , 'inline');
74
  }
75

    
76
  /**
77
   */
78
  function drupal_add_js_rowToggle($tableId){
79

    
80
      drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/table_modification.js');
81
      drupal_add_js('jQuery(document).ready(function(){
82
          addRowToggle("' . $tableId . '");
83
      });
84
      ', array('type' => 'inline'));
85
  }
86

    
87
  /**
88
   * @param unknown_type $link_element_selector
89
   * @param unknown_type $progress_element_selector
90
   */
91
  function _add_js_cdm_ws_progressbar($link_element_selector, $progress_element_selector){
92

    
93
    $callback = "jQuery('" . $link_element_selector . "').cdm_ws_progress('" . $progress_element_selector . "');";
94

    
95
    drupal_add_js_async(variable_get('cdm_webservice_url', '').'js/cdm_ws_progress.js', $callback);
96

    
97
    //   drupal_add_js("
98
    //   	  if (Drupal.jsEnabled) {
99
    //         $(document).ready(function() {
100
    //       		$('" . $link_element_selector . "').cdm_ws_progress('" . $progress_element_selector . "');
101
    //         });
102
    //       }", 'inline');
103
    }
104

    
105
  /**
106
   * @todo Please document this function.
107
   * @see http://drupal.org/node/1354
108
   */
109
  function _add_js_treeselector() {
110
    // drupal_add_js(drupal_get_path('module', 'cdm_dataportal').'/js/treeselector.js');
111
    drupal_add_js("
112
        jQuery(document).ready(function() {
113
           jQuery('#cdm-taxonomictree-selector-form #edit-val').change(function () {
114
                jQuery('#cdm-taxonomictree-selector-form').submit();
115
            });
116

    
117
        });
118
      ",
119
      array(
120
        'type' => 'inline',
121
        'scope' => 'footer'
122
      )
123
    );
124
  }
125

    
126
  function _add_js_resizable_element($selector, $y_axis_only) {
127

    
128
    _add_jquery_ui();
129
    $options = "";
130
    if($y_axis_only) {
131
      $options = "resize: function(event, ui) {
132
        ui.size.width = ui.originalSize.width;
133
        },
134
        handles: \"s\"";
135

    
136
    }
137
    drupal_add_js("
138
          jQuery(document).ready(function() {
139
             jQuery('" . $selector . "').resizable({". $options ."});
140
          });
141
        ",
142
      array(
143
        'type' => 'inline',
144
        'scope' => 'footer'
145
      )
146
    );
147
  }
148

    
149
  function _add_js_openlayers() {
150

    
151
    $openlayers = '/js/map/OpenLayers-2.13.1/OpenLayers.js';
152
    $proj4js = '/js/map/proj4js-1.1.0/proj4js-compressed.js';
153

    
154
    if(variable_get('cdm_js_devel_mode', FALSE)){
155
      // develooper mode libs
156
  //     $openlayers = '/js/map/OpenLayers-2.13.1/lib/OpenLayers.js';
157
      $openlayers = '/js/map/OpenLayers-2.13.1/OpenLayers.debug.js';
158
      $proj4js = '/js/map/proj4js-1.1.0/proj4js-combined.js';
159
    }
160

    
161
    drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $openlayers,
162
      array(
163
        'type' => 'file',
164
        'group' => JS_LIBRARY,
165
        'weight' => 0,
166
        'cache' => TRUE,
167
        'preprocess' => FALSE
168
      )
169
    );
170

    
171
    // see https://github.com/proj4js/proj4js
172
    // http://openlayers.org/dev/examples/using-proj4js.html
173
    drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $proj4js,
174
      array(
175
        'type' => 'file',
176
        'group' => JS_LIBRARY,
177
        'weight' => -1, // before open layers
178
        'cache' => TRUE,
179
      )
180
    );
181

    
182
    // configure the theme
183
    $openlayers_theme_path = drupal_get_path('module', 'cdm_dataportal') . '/js/map/OpenLayers-2.13.1/theme/default/';
184
    $openlayers_imp_path = drupal_get_path('module', 'cdm_dataportal') . '/js/map/img/dark/';
185
    drupal_add_js('OpenLayers.ImgPath="' . base_path() . $openlayers_imp_path . '";', array(
186
        'type' => 'inline',
187
        'group' => JS_LIBRARY,
188
        'weight' => 1, // after openlayers
189
        'cache' => TRUE,
190
        'preprocess' => FALSE
191
      ));
192

    
193
    drupal_add_css($openlayers_theme_path . 'style.tidy.css',
194
      array(
195
        'type' => 'file',
196
        'cache' => TRUE,
197
        'preprocess' => FALSE
198
      )
199
    );
200

    
201
  }
202

    
203
  /**
204
   * @todo Please document this function.
205
   * @see http://drupal.org/node/1354
206
   */
207
  function _add_js_thickbox() {
208
    // ---- jQuery thickbox:
209
    /*
210
    * bug: compat-1.0.js && thickbox.js line 237 .trigger("unload") -> event is
211
    * not triggered because of problems with compat-1.0.js' see INSTALL.txt
212
    */
213
    // drupal_add_js(drupal_get_path('module',
214
    // 'cdm_dataportal').'/js/jquery.imagetool.min.js');
215
    //
216
    // Add a setting for the path to cdm_dataportal module, used to find the path
217
    // for the loading animation image in thickbox.
218
    drupal_add_js(array(
219
    'cdm_dataportal' => array(
220
    'cdm_dataportal_path' => base_path() . drupal_get_path('module', 'cdm_dataportal'),
221
    )
222
    ),
223
    'setting'
224
        );
225
        drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/thickbox/thickbox.js');
226
        drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/thickbox/cdm_thickbox.css');
227
  }
228

    
229
  /**
230
   * @todo Please document this function.
231
   * @see http://drupal.org/node/1354
232
   */
233
  function _add_js_lightbox($galleryID) {
234
    /*
235
     * Important Notice: The jquery.lightbox-0.5.js has been modified in order to
236
     * allow using the "alt" attribute for captions instead of the "title"
237
     * attribute
238
     */
239
    $lightbox_base_path =  drupal_get_path('module', 'cdm_dataportal') . '/js/jquery-lightbox-0.5';
240
    $lightbox_image_path = base_path() . $lightbox_base_path . '/images/';
241
    drupal_add_js($lightbox_base_path . '/js/jquery.lightbox-0.5.js');
242
    drupal_add_css($lightbox_base_path . '/css/jquery.lightbox-0.5.css');
243
    drupal_add_js('jQuery(document).ready(function() {
244
        jQuery(\'#' . $galleryID . ' a.lightbox\').lightBox({
245
          fixedNavigation:  true,
246
          imageLoading:     \'' . $lightbox_image_path . 'lightbox-ico-loading.gif\',
247
          imageBtnPrev:     \'' . $lightbox_image_path . 'lightbox-btn-prev.gif\',
248
          imageBtnNext:     \'' . $lightbox_image_path . 'lightbox-btn-next.gif\',
249
          imageBtnClose:    \'' . $lightbox_image_path . 'lightbox-btn-close.gif\',
250
          imageBlank:       \'' . $lightbox_image_path . 'lightbox-blank.gif\',
251
          adjustToWindow: true
252
        });
253
      });
254
      ', array('type' => 'inline'));
255
  }
256

    
257
  /**
258
   * @todo Please document this function.
259
   * @see http://drupal.org/node/1354
260
   */
261
  function _add_js_footnotes() {
262
    _add_js_domEvent();
263
    drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/footnotes.js');
264
  }
265

    
266
  /**
267
   * @todo Please document this function.
268
   * @see http://drupal.org/node/1354
269
   */
270
  function _add_js_ahah() {
271

    
272
    _add_js_domEvent(); // requires domEvent.js
273
    drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/ahah-content.js');
274
  }
275

    
276
/**
277
 * @todo Please document this function.
278
 * @see http://drupal.org/node/1354
279
 */
280
function _add_js_taxonomic_children($jquery_selector) {
281

    
282
  global $base_url;
283

    
284

    
285
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/jquery.cdm.taxonomic_children.js');
286
  
287
  drupal_add_js('jQuery(document).ready(function() {
288
        jQuery(\'' . $jquery_selector . '\').taxonomic_children({
289
          // hoverClass: "fa-rotate-90",
290
          // activeClass: "fa-rotate-90",
291
          classificationUuid: "' . get_current_classification_uuid() . '",
292
          taxonUuid: "' . get_current_taxon_uuid() . '",
293
          cdmWebappBaseUri: "' . variable_get('cdm_webservice_url', '') . '",
294
          proxyBaseUri: "' . $base_url . '",
295
          
296
        });
297
      });
298
      ', array('type' => 'inline'));
299
}
300

    
301
  /**
302
   * Adds the external javascript file for domEvent.js.
303
   *
304
   * @see drupal_add_js()
305
   */
306
  function _add_js_domEvent() {
307
    drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/domEvent.js');
308
  }
309

    
310
  function _add_jquery_ui()
311
  {
312
    drupal_add_css(drupal_get_path('module',
313
        'cdm_dataportal') . '/js/jquery-ui-1.8.24/themes/base/jquery.ui.all.css');
314
    drupal_add_js(drupal_get_path('module',
315
        'cdm_dataportal') . '/js/jquery-ui-1.8.24/ui/jquery-ui.js',
316
      array(
317
        'type' => 'file',
318
        'weight' => JS_LIBRARY,
319
        'cache' => TRUE,
320
        'preprocess' => FALSE
321
      )
322
    );
323
  }
324

    
325
  /**
326
   * Provides the markup for an font awesome icon.
327
   *
328
   * The icons is created in default size without any extra features.
329
   *
330
   * The available icons are listed here http://fontawesome.io/cheatsheet/
331
   * fontawesome icons have much more features than implemented here in this function,
332
   * for spinning icons, fixed width icons, rotation, etc please checkout the
333
   * examples at http://fontawesome.io/examples/
334
   *
335
   * @parameter $icon_name
336
   *  The name of the icon which starts with 'fa-'
337
   *
338
   * @return String
339
   *    the markup for the icon in an <i> tag
340
   *
341
   */
342
  function font_awesome_icon_markup($icon_name = NULL, $attributes = array()){
343

    
344

    
345
    //<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
346

    
347
    $font_awesome_css_uri = base_path() . drupal_get_path('module', 'cdm_dataportal').'/fonts/font-awesome-4.6.3/css/font-awesome.min.css';
348
    //$font_awesome_css_uri="//maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css";
349

    
350
    drupal_add_html_head_link(
351
      array(
352
        'href' => $font_awesome_css_uri,
353
        'rel' => 'stylesheet'
354
      )
355
    );
356

    
357
    if($icon_name){
358
      if(!isset($attributes['class'])){
359
        $attributes['class'] = array();
360
      }
361
      $attributes['class'][] = 'fa';
362
      $attributes['class'][] = $icon_name;
363

    
364
      return '<i ' . drupal_attributes($attributes) . '></i>';
365
    }
366

    
367
    return '';
368
  }
369

    
370

    
371
  /* ====================== hook implementations ====================== */
372
  /**
373
   * Implements hook_permission().
374
   *
375
   * Valid permissions for this module.
376
   *
377
   * @return array
378
   *   An array of valid permissions for the cdm_dataportal module.
379
   */
380
  function cdm_dataportal_permission() {
381
    return array(
382
      'administer cdm_dataportal' => array(
383
        'title' => t('Administer CDM DataPortal settings'),
384
        'description' => t("Access the settings pages specific for the cdm_dataportal module"),
385
      ),
386
      'access cdm content' => array(
387
        'title' => t('Access CDM content'),
388
        'description' => t("Access content (taxa, names, specimens, etc.) served by the CDM web service."),
389
      ),
390
    );
391
  }
392

    
393
/**
394
 * Implements hook_menu().
395
 */
396
function cdm_dataportal_menu() {
397
  $items = array();
398

    
399
  // @see settings.php.
400
  cdm_dataportal_menu_admin($items);
401
  cdm_dataportal_menu_help($items);
402

    
403
  $items['cdm_dataportal/names'] = array(
404
    'page callback' => 'cdm_dataportal_view_names',
405
    'access arguments' => array('access cdm content'),
406
    'type' => MENU_CALLBACK,
407
  );
408

    
409
  // Optional callback arguments: page.
410
  $items['cdm_dataportal/taxon'] = array(
411
    'page callback' => 'cdm_dataportal_taxon_page_view',
412
    'access arguments' => array('access cdm content'),
413
    'type' => MENU_CALLBACK,
414
    // Expected callback arguments: uuid.
415
  );
416

    
417
  $items['cdm_dataportal/specimen'] = array(
418
      'page callback' => 'cdm_dataportal_specimen_page_view',
419
      'access arguments' => array('access cdm content'),
420
      'type' => MENU_CALLBACK,
421
      // Expected callback arguments: uuid.
422
  );
423

    
424
  $items['cdm_dataportal/named_area'] = array(
425
    'page callback' => 'cdm_dataportal_named_area_page_view',
426
    'access arguments' => array('access cdm content'),
427
    'type' => MENU_CALLBACK,
428
    // Expected callback arguments: uuid.
429
  );
430

    
431
  $items['cdm_dataportal/name'] = array(
432
    'page callback' => 'cdm_dataportal_name_page_view',
433
      /*
434
    'page arguments' => array(
435
       'taxon_name_uuid',
436
       'taxon_to_hide_uuid',
437
       'synonym_uuid' => NULL
438
      ),
439
      */
440
    'access arguments' => array('access cdm content'),
441
    'type' => MENU_CALLBACK,
442
    // Expected callback arguments: uuid.
443
  );
444

    
445
  $items['cdm_dataportal/reference'] = array(
446
    'page callback' => 'cdm_dataportal_view_reference',
447
    'access arguments' => array('access cdm content'),
448
    'type' => MENU_CALLBACK,
449
    // Expected callback arguments: uuid.
450
  );
451

    
452
  $items['cdm_dataportal/reference/list'] = array(
453
    'page callback' => 'cdm_dataportal_view_reference_list',
454
    'access arguments' => array('access cdm content'),
455
    'type' => MENU_CALLBACK,
456
    // Expected callback arguments: uuid.
457
  );
458

    
459
  $items['cdm_dataportal/media'] = array(
460
    'page callback' => 'cdm_dataportal_view_media',
461
    'access arguments' => array('access cdm content'),
462
    'type' => MENU_CALLBACK,
463
    // Expected callback arguments:
464
    // uuid, mediarepresentation_uuid, part_uuid or part#.
465
  );
466

    
467
  $items['cdm_dataportal/polytomousKey'] = array(
468
    'page callback' => 'cdm_dataportal_view_polytomousKey',
469
    'access arguments' => array('access cdm content'),
470
    'type' => MENU_CALLBACK,
471
    // Expected callback arguments: polytomousKey->uuid.
472
  );
473

    
474
  $items['cdm_dataportal/search'] = array(
475
    'page callback' => 'cdm_dataportal_view_search_advanced',
476
    'access arguments' => array('access cdm content'),
477
    'type' => MENU_CALLBACK,
478
  );
479

    
480
  $items['cdm_dataportal/search/advanced'] = array(
481
    'title' => 'Advanced', // will be passed through t()
482
    'page callback' => 'cdm_dataportal_view_search_advanced',
483
    'access arguments' => array('access cdm content'),
484
    'type' => MENU_DEFAULT_LOCAL_TASK,
485
  );
486

    
487
  $items['cdm_dataportal/search/taxon_by_description'] = array(
488
    'title' => 'By content category', // will be passed through t()
489
    'page callback' => 'cdm_dataportal_view_search_taxon_by_description',
490
    'access arguments' => array('access cdm content'),
491
    'type' => MENU_LOCAL_TASK,
492
  );
493

    
494
  $items['cdm_dataportal/search/results/taxon'] = array(
495
    'page callback' => 'cdm_dataportal_view_search_results_taxon',
496
    'access arguments' => array('access cdm content'),
497
    'type' => MENU_CALLBACK,
498
  );
499
  $items['cdm_dataportal/search/registration'] = array(
500
    'page callback' => 'cdm_dataportal_view_search_registrations_results',
501
    'access arguments' => array('access cdm content'),
502
    'type' => MENU_CALLBACK,
503
  );
504
  // Optional callback arguments: page.
505
  $items['cdm_dataportal/registration'] = array(
506
    'page callback' => 'cdm_dataportal_registration_page_view',
507
    'access arguments' => array('access cdm content'),
508
    'type' => MENU_CALLBACK,
509
    // Expected callback arguments: uuid.
510
  );
511

    
512
  /*
513
   $items['cdm/xml2json'] = array(
514
   'page callback' => 'cdm_view_xml2json',
515
   'access arguments' => array('access cdm content'),
516
   'type' => MENU_CALLBACK,
517
   );
518
   */
519

    
520
  // if (arg(0)=='user' && ($uid=arg(1)) && is_numeric($uid)) {
521
  // User configuration of cdm_dataportal.
522
  $items['user/%/cdm_dataportal'] = array(
523
    'title' => 'cdm_dataportal',
524
    'access arguments' => array('access cdm content'),
525
    'page callback' => 'drupal_get_form',
526
    'page arguments' => array('cdm_dataportal_user_form'),
527
    'type' => MENU_LOCAL_TASK,
528
    'weight' => 10,
529
  );
530
  // }
531

    
532
  // 'May not cache' in D5.
533
  $items['cdm_dataportal/name/%'] = array(
534
    // 'page callback' => 'cdm_dataportal_view_name',
535
    'page callback' => 'cdm_dataportal_name_page_view',
536
    'page arguments' => array(2, 3, 4),
537
    'access arguments' => array('access cdm content'),
538
    'type' => MENU_CALLBACK,
539
  );
540

    
541
  // --- Local tasks for Taxon.
542
  // --- tabbed taxon page
543
  if (variable_get('cdm_dataportal_taxonpage_tabs', 1)) {
544
    $items['cdm_dataportal/taxon/%'] = array(
545
      'title' => cdm_taxonpage_tab_label('General'),
546
      'page callback' => 'cdm_dataportal_taxon_page_view',
547
      'access arguments' => array('access cdm content'),
548
      'type' => MENU_CALLBACK,
549
      'weight' => 1,
550
      'page arguments' => array(2, "description")
551
      , // Expected callback arguments: taxon_uuid.
552
    );
553

    
554
    $items['cdm_dataportal/taxon/%/all'] = array(
555
      'title' => cdm_taxonpage_tab_label('General'),
556
      'page callback' => 'cdm_dataportal_taxon_page_view',
557
      'access arguments' => array('access cdm content'),
558
      'type' => MENU_CALLBACK,
559
      'weight' => 2,
560
      'page arguments' => array(2, "all")
561
      , // Expected callback arguments: taxon_uuid.
562
    );
563

    
564
    $items['cdm_dataportal/taxon/%/description'] = array(
565
      'title' => cdm_taxonpage_tab_label('General'),
566
      'page callback' => 'cdm_dataportal_taxon_page_view',
567
      'access arguments' => array('access cdm content'),
568
      'type' => MENU_DEFAULT_LOCAL_TASK,
569
      'weight' => 2,
570
      'page arguments' => array(2, "description")
571
      , // Expected callback arguments: taxon_uuid.
572
    );
573

    
574
    $items['cdm_dataportal/taxon/%/synonymy'] = array(
575
      'title' => cdm_taxonpage_tab_label('Synonymy'),
576
      'page callback' => 'cdm_dataportal_taxon_page_view',
577
      'access arguments' => array('access cdm content'),
578
      'type' => MENU_LOCAL_TASK,
579
      'weight' => 4,
580
      'page arguments' => array(2, "synonymy", 4)
581
      , // Expected callback arguments: taxon_uuid and ...
582
    );
583
    $items['cdm_dataportal/taxon/%/images'] = array( // Images
584
      'title' => cdm_taxonpage_tab_label('Images'),
585
      'page callback' => 'cdm_dataportal_taxon_page_view',
586
      'access arguments' => array('access cdm content'),
587
      'type' => MENU_LOCAL_TASK,
588
      'weight' => 5,
589
      'page arguments' => array(2, "images")
590
      , // Expected callback arguments: taxon_uuid.
591
    );
592

    
593
    $items['cdm_dataportal/taxon/%/specimens'] = array( // Specimens
594
      'title' => cdm_taxonpage_tab_label('Specimens'),
595
      'page callback' => 'cdm_dataportal_taxon_page_view',
596
      'access arguments' => array('access cdm content'),
597
      'type' => MENU_LOCAL_TASK,
598
      'weight' => 6,
599
      'page arguments' => array(2, "specimens")
600
      , // Expected callback arguments: taxon_uuid.
601
    );
602

    
603
    $items['cdm_dataportal/taxon/%/keys'] = array( // Keys
604
      'title' => cdm_taxonpage_tab_label('Keys'),
605
      'page callback' => 'cdm_dataportal_taxon_page_view',
606
      'access arguments' => array('access cdm content'),
607
      'type' => MENU_LOCAL_TASK,
608
      'weight' => 6,
609
      'page arguments' => array(2, "keys")
610
      , // Expected callback arguments: taxon_uuid.
611
    );
612

    
613
    $items['cdm_dataportal/taxon/%/experts'] = array( // Experts
614
      'title' => cdm_taxonpage_tab_label('Experts'),
615
        'page callback' => 'cdm_dataportal_taxon_page_view',
616
        'access arguments' => array('access cdm content'),
617
        'type' => MENU_LOCAL_TASK,
618
        'weight' => 6,
619
        'page arguments' => array(2, "experts")
620
    , // Expected callback arguments: taxon_uuid.
621
    );
622

    
623
    $items['cdm_dataportal/taxon/autosuggest/%/%/%/'] = array(
624
        'page callback' => 'cdm_dataportal_taxon_autosuggest',
625
        'access arguments' => array('access cdm content'),
626
        'page arguments' => array(3,4,5),
627
        'type' => MENU_CALLBACK
628
    );
629
  }
630

    
631
  // --- refresh link for all cdmnode types
632
  foreach (cdm_get_nodetypes() as $type=>$name) {
633
    $items['cdm_dataportal/' . $name . '/%/refresh'] = array(
634
        'title' => 'Refresh',
635
        'page callback' => 'cdm_dataportal_refresh_node',
636
        'access arguments' => array('administer cdm_dataportal'),
637
        'type' => MENU_LOCAL_TASK,
638
        'weight' => 100,
639
        'page arguments' => array($name, 2)
640
    );
641
  }
642

    
643
  return $items;
644
}
645

    
646
/**
647
 * Implements hook_init().
648
 *
649
 */
650
function cdm_dataportal_init() {
651
  if (!path_is_admin(current_path())) {
652
    //FIXME To add CSS or JS that should be present on all pages, modules
653
    //      should not implement this hook, but declare these files in their .info file.
654
    drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/cdm_dataportal.css');
655
    // drupal_add_css(drupal_get_path('module', 'cdm_dataportal').'/cdm_dataportal_print.css', 'print');
656
    drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/cdm_dataportal_screen.css', array('type' => 'screen'));
657
  } else {
658
    drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/cdm_dataportal_settings.css');
659
  }
660

    
661
  if(variable_get('cdm_debug_mode', FALSE)){
662
    $file = 'temporary://drupal_debug.txt';
663
    file_put_contents($file, 'CDM DEBUG LOG for ' . $_GET['q']. "\n"); // will overwrite the file
664
  }
665

    
666
  $bibliography_settings = get_bibliography_settings();
667
  $enclosing_tag = $bibliography_settings['enabled'] == 1 ? 'div' : 'span';
668
  FootnoteManager::registerFootnoteSet('BIBLIOGRAPHY', $enclosing_tag, $bibliography_settings['key_format']);
669
}
670

    
671
function cdm_dataportal_refresh_node($cdm_node_name, $uuid, $parameters = array()){
672

    
673
  $base_path = 'cdm_dataportal/' . $cdm_node_name . '/' . $uuid;
674

    
675
  if($cdm_node_name == 'taxon' && variable_get('cdm_dataportal_taxonpage_tabs', 1)){
676
    // force reloading of all and notify user about this special loading
677
    drupal_set_message(t('The level 2 cache has been cleared for all tabs of this taxon page at once, please click here to return to the tabbed page: ')
678
        . l('Back to tabbed taxon page', $base_path));
679
    $base_path .= '/all';
680
  } else {
681
    drupal_set_message(t('The level 2 cache has been cleared for this page'));
682
  }
683

    
684
  $parameters['cacheL2_refresh'] ='1';
685

    
686

    
687
  drupal_goto($base_path, array('query' => $parameters));
688
}
689

    
690
/**
691
 * Implements hook_requirements($phase)
692
 */
693
function cdm_dataportal_requirements($phase) {
694
    $requirements = array();
695
    if($phase == 'runtime'){
696

    
697
    }
698
    return $requirements;
699
}
700

    
701

    
702
/**
703
 * The function generate form for own user cdm dataportal configurations.
704
 */
705
function cdm_dataportal_user_form($form, &$form_state) {
706

    
707
  global $user;
708
  $checkbox_value = 'cdm_dataportal_' . $user->uid . '_default_tab_active';
709

    
710
  $form['taxon_page_tabs'] = array(
711
      '#type' => 'fieldset',
712
      '#tree' => true,
713
      '#title' => t('Taxon page tabs'),
714
  );
715

    
716
  $form['taxon_page_tabs']['user_defined'] = array(
717
    '#type' => 'checkbox',
718
    '#title' => t('Activate user default configuration'),
719
    '#default_value' => variable_get($checkbox_value, 0),
720
    '#description' => t('Check this if you want configure your own default tab from the below menu.'),
721
  );
722

    
723
  $form['taxon_page_tabs']['default_tab'] = array(
724
    '#type' => 'select',
725
    '#title' => t('Default tab to display'),
726
    '#default_value' => get_default_taxon_tab(TRUE),
727
    '#options' => unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB),
728
    '#description' => t('<p>Select the default tab to display when visiting a taxon page. Only available if Tabbed Taxon Page is enable.</p>
729
              <strong>Note:</strong> After performing a search and clicking in any synonym, the taxon tab
730
              to be rendered will be the synonymy of the accepted taxon and not the above selected tab.'),
731
  );
732

    
733

    
734
  if(false){
735
    $form['developer_options'] = array(
736
        '#type' => 'fieldset',
737
        '#tree' => true,
738
        '#title' => t('Developer options'),
739
    );
740

    
741
    $form['developer_options']['show_render_path'] = array(
742
      '#type' => 'checkbox',
743
      '#title' => t('Display the render path for each taxon name.'),
744
      '#default_value' => variable_get($checkbox_value, 0),
745
      '#description' => t('This option is very helpful if you are editing the !link for taxon names.',
746
        array(
747
            '!link' => l(
748
              'render template', 'admin/config/cdm_dataportal/settings/layout', array('fragment' => 'edit-cdm-name-render-templates'))
749
            )
750
        ),
751
    );
752
  }
753

    
754
  $form['submit'] = array(
755
    '#type' => 'submit',
756
    '#value' => t('Submit'),
757
  );
758

    
759
  return $form;
760
}
761

    
762
/**
763
 * Form submission handler for user_form().
764
 *
765
 * Submits the user cdm dataportal configurations.
766
 */
767
function cdm_dataportal_user_form_submit($form, &$form_state) {
768
  global $user;
769
  $msg_type = 'status';
770
  $username = $user->name;
771
  $variable_to_use = 'cdm_dataportal_' . $user->uid . '_default_tab';
772

    
773
  // FIXME: this is completely wrong, see user_profile_form_submit()
774

    
775
  // it is only possible to change own user settings
776
  if (arg(0) == 'user' && is_numeric(arg(1)) && $user->uid == arg(1)) {
777

    
778
    // DEFAULT_TAXON_TAB
779
    $variable = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
780
    variable_set($variable_to_use . '_active', $form_state['values']['taxon_page_tabs']['user_defined']);
781
    variable_set($variable_to_use, $form_state['values']['taxon_page_tabs']['default_tab']);
782
    if ($form_state['values']['taxon_page_tabs']['user_defined']) {
783
      drupal_set_message(check_plain(t('The user default tab will be used for the next taxon site visit.')));
784
      drupal_set_message(check_plain(t('The user default tab has been changed to: !tab for the user !user', array(
785
        '!tab' => $variable[variable_get($variable_to_use, 0)],
786
        '!user' => $username,
787
      ))), $msg_type);
788
    }
789
    else {
790
      drupal_set_message(check_plain(t('The user default tab wont be used for
791
        the next taxon site, check the box if you want to use the user default configuration.')));
792
    }
793

    
794
  }
795
  else {
796
    // Problem with the user id => variables wont be saved.
797
    $msg_type = 'warning';
798
    drupal_set_message(check_plain(t('Default tab has not been saved due to user id problems')), $msg_type);
799
  }
800
}
801

    
802
/**
803
 * Implements hook_block_info().
804
 */
805
function cdm_dataportal_block_info() {
806

    
807
    // $block[0]["info"] = t("CDM DataPortal DevLinks");
808
    // $block[1]["info"] = t("CDM DataPortal Credits");
809
    $block["2"] = array(
810
        "info" => t("CDM - Search Taxa"),
811
        "cache" => DRUPAL_NO_CACHE
812
      );
813
    // $block[3]["info"] = t("CDM Filters");
814
    $block["4"]["info"] = t("CDM  - Dataportal Print");
815
    $block["keys"]["info"] = t("CDM - Identification keys");
816
    $block["fundedByEDIT"]["info"] = t('CDM - Powered by EDIT');
817
    $block["classification_breadcrumbs"] =  array(
818
        'info' => t('CDM - Classification breadcrumbs'),
819
        'cache' => DRUPAL_CACHE_PER_PAGE
820
      );
821
    $block["taxonomic_children"] =  array(
822
      'info' => t('CDM - Taxonomic children'),
823
      'cache' => DRUPAL_CACHE_PER_PAGE
824
    );
825
    $block["back_to_search_results"] =  array(
826
      'title' => '<none>',
827
      'info' => t('CDM - Back to search Results'),
828
      'cache' => DRUPAL_CACHE_PER_PAGE,
829
      'visibility' => BLOCK_VISIBILITY_LISTED,
830
      'pages' => "cdm_dataportal/taxon/*", // multiple page paths separated by "\n"!!!
831
    );
832
  $block['registrations_search_filter'] =  array(
833
    'title' => '<none>',
834
    'info' => t('CDM - Registrations search filter'),
835
    'cache' => DRUPAL_CACHE_PER_PAGE,
836
    'visibility' => BLOCK_VISIBILITY_LISTED,
837
    'pages' => "cdm_dataportal/search/registration\ncdm_dataportal/search/registration/*", // multiple page paths separated by "\n"!!!
838
  );
839

    
840
    return $block;
841
}
842

    
843
/**
844
 * Implements hook_block_view().
845
 */
846
function cdm_dataportal_block_view($delta) {
847
  // TODO Rename block deltas (e.g. '2') to readable strings.
848
  switch ($delta) {
849
    // case 'delta-1':
850
    // $block['subject'] = t('Credits');
851
    // $block['content'] = theme('cdm_credits');
852
    // return $block;
853
    case '2':
854
      $block['subject'] = t('Search taxa');
855
      $form = drupal_get_form('cdm_dataportal_search_taxon_form');
856
      $block['content'] = drupal_render($form);
857

    
858
      if (variable_get('cdm_dataportal_show_advanced_search', 1)) {
859
        $block['content'] .= '<div>' . l(t('Advanced Search'), 'cdm_dataportal/search') . '</div>';
860
      }
861
      return $block;
862
    case '4':
863
      $block['subject'] = '';
864
      $block['content'] = theme('cdm_print_button');
865
      return $block;
866
    case "keys":
867
      $block['subject'] = t('Identification Keys');
868
      $block['content'] = theme('cdm_block_IdentificationKeys', array('taxonUuid' => NULL));
869
      return $block;
870
    case "fundedByEDIT":
871
      // t('Funded by EDIT');
872
      $text = '<none>';
873
      $block['subject'] = $text;
874
      $img_tag = '<img src="' . base_path() . drupal_get_path('module', 'cdm_dataportal') . '/images/powered_by_edit.png' . '" alt="' . $text . '"/>';
875
      $block['content'] = l($img_tag, "http://cybertaxonomy.org/", array(
876
        'attributes' => array("target" => "EDIT"),
877
        'absolute' => TRUE,
878
        'html' => TRUE,
879
      ));
880
      return $block;
881
    case 'classification_breadcrumbs':
882
      $taxon_uuid = get_current_taxon_uuid();
883
      $block['subject'] = '<none>';
884
      $block['content'] = compose_classification_breadcrumbs($taxon_uuid);
885
      return $block;
886
    case 'taxonomic_children':
887
      $taxon_uuid = get_current_taxon_uuid();
888
      $block['subject'] = '<none>';
889
      $block['content'] = compose_taxonomic_children($taxon_uuid);
890
      return $block;
891
    case 'back_to_search_results':
892
      $block['subject'] = '<none>';
893
      if (isset($_SESSION['cdm']['search'])) {
894
        $block['content'] = l(t('Back to search result'), "http://" . $_SERVER['SERVER_NAME'] . $_SESSION['cdm']['last_search']);
895
      }
896
      return $block;
897
    case 'registrations_search_filter':
898
      $block['subject'] = '<none>';
899
      $block['content'] = $form = drupal_get_form('cdm_dataportal_search_registration_form'); // see cdm_dataportal_search_registration_form($form, &$form_state)
900
      return $block;
901
    default:
902
      return null;
903
  }
904
}
905

    
906
/**
907
 * Provides the uuid of the taxon for pages with the path ./taxon/{taxon_uuid}
908
 *
909
 * @return string
910
 *   the taxon uuid or NULL
911
 */
912
function get_current_taxon_uuid()
913
{
914
  static $taxon_uuid;
915

    
916
  if(!isset($taxon_uuid)){
917
    if(isset($_REQUEST['currentTaxon']) && is_uuid($_REQUEST['currentTaxon'])) {
918
      $taxon_uuid = $_REQUEST['currentTaxon'];
919
    } else if (arg(1) == 'taxon' && is_uuid(arg(2))) {
920
      $taxon_uuid = arg(2);
921
    } else {
922
      $taxon_uuid = null;
923
    }
924
  }
925

    
926
  return $taxon_uuid;
927
}
928

    
929
/**
930
 * Returns the currently classification tree in use.
931
 *
932
 * @return string
933
 *   The uuid of the currently focused classification
934
 */
935
function get_current_classification_uuid() {
936
  if (isset($_SESSION['cdm']['taxonomictree_uuid']) && is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
937
    return $_SESSION['cdm']['taxonomictree_uuid'];
938
  }
939
  else {
940
    return variable_get(CDM_TAXONOMICTREE_UUID, FALSE);
941
  }
942
}
943

    
944
/*
945
 function cdm_dataportal_session_clear($cdm_ws_uri_update = FALSE){
946
 $_SESSION['cdm'] = NULL;
947
 if(is_string($cdm_ws_uri_update)){
948
 $_SESSION['cdm'] = array('ws_uri'=>$cdm_ws_uri_update);
949
 }
950
 }
951

    
952
 function cdm_dataportal_session_validate(){
953
 if(!isset($_SESSION['cdm']['ws_uri'])){
954
 $_SESSION['cdm'] = array('ws_uri'=>variable_get('cdm_webservice_url', FALSE));
955
 } else if($_SESSION['cdm']['ws_uri'] != variable_get('cdm_webservice_url', FALSE)){
956
 cdm_dataportal_session_clear(variable_get('cdm_webservice_url', FALSE));
957
 }
958
 }
959
 */
960

    
961
/**
962
 * creates a  selector form for taxonomic trees.
963
 *
964
 * @return array
965
 *  a drupal form array
966
 */
967
function cdm_taxonomictree_selector() {
968
  _add_js_treeselector();
969

    
970
  $form = drupal_get_form('cdm_taxonomictree_selector_form');
971
  return $form;
972
}
973

    
974
/**
975
 * @todo Please document this function.
976
 * @see http://drupal.org/node/1354
977
 *
978
 * @deprecated use compose_classification_selector instead
979
 */
980
function cdm_taxonomictree_selector_form($form, &$form_state) {
981

    
982
  $url = url('cdm_api/setvalue/session', array('query' => NULL));
983
  $form['#action'] = $url;
984

    
985
  $form['var'] = array(
986
    '#weight' => -3,
987
    '#type' => 'hidden',
988
    '#value' => '[cdm][taxonomictree_uuid]',
989
  );
990

    
991
  $destination_array = drupal_get_destination();
992
  $destination = $destination_array['destination'];
993

    
994
  $form['destination'] = array(
995
    '#weight' => -3,
996
    '#type' => 'hidden',
997
    '#value' =>  $destination,
998
  );
999

    
1000
  $options = cdm_get_taxontrees_as_options();
1001
  $taxontree_includes = variable_get(CDM_TAXONTREE_INCLUDES, null);
1002
  if($taxontree_includes){
1003
    $filtered_options = array();
1004
    foreach($options as $uuid=>$label){
1005
      if(!empty($taxontree_includes[$uuid])){
1006
        $filtered_options[$uuid] = $label;
1007
      }
1008
    }
1009
    $options = $filtered_options;
1010
  }
1011

    
1012
  $form['val'] = array(
1013
    '#type' => 'select',
1014
    '#title' => t('Available classifications'),
1015
    '#default_value' => get_current_classification_uuid(),
1016
    '#options' => $options,
1017
    '#attributes' => array('class' => array('highlite-first-child')),
1018
  );
1019

    
1020
  return $form;
1021

    
1022
}
1023

    
1024
/**
1025
 *
1026
 * @ingroup compose
1027
 */
1028
function compose_classification_selector() {
1029

    
1030
  $destination_array = drupal_get_destination();
1031
  $destination = $destination_array['destination'];
1032

    
1033
  $options = cdm_get_taxontrees_as_options();
1034
  $items = array();
1035
  $taxontree_includes = variable_get(CDM_TAXONTREE_INCLUDES, null);
1036

    
1037
  $current_classification_uuid = get_current_classification_uuid();
1038

    
1039

    
1040
  foreach($options as $uuid=>$label){
1041
    if(!$taxontree_includes || !empty($taxontree_includes[$uuid])){
1042

    
1043
      $class_attributes = '';
1044
      if($current_classification_uuid == $uuid){
1045
        $class_attributes  = array('focused');
1046
      }
1047
      $items[] = array(
1048
        'data' => l($label,
1049
          'cdm_api/setvalue/session',
1050
          array(
1051
            'query' => array(
1052
              'destination' => $destination,
1053
              'val' => $uuid,
1054
              'var' => '[cdm][taxonomictree_uuid]'
1055
            ),
1056
          )
1057
        ),
1058
        'class' => $class_attributes
1059
      );
1060
    }
1061
  }
1062

    
1063
  $render_array = array(
1064
    '#theme' => 'item_list',
1065
    '#type' => 'ul',
1066
    '#items' => $items
1067
  );
1068

    
1069
  return $render_array;
1070
}
1071

    
1072

    
1073
/* UNREACHABLE since action of form directly links to view.
1074
 function cdm_dataportal_search_taxon_form_submit($form_id, $form_values) {
1075

    
1076
 $_SESSION['cdm']['search'] = $form_values;
1077
 //return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['vernacular']?'1':'0').'/'.$form_values['language'];
1078
 return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['onlyAccepted']?'1':'0');
1079
 //$paramstr = compose_url_prameterstr($form_values);
1080
 //return url('/cdm_dataportal/search/taxon/', array('query' => $paramstr));
1081
 }
1082
 */
1083
/* ====================== menu callback functions ====================== */
1084
/**
1085
 * @todo Please document this function.
1086
 * @see http://drupal.org/node/1354
1087
 */
1088
/*
1089
function cdm_dataportal_form_alter(&$form, &$form_state, $form_id) {
1090
  static $comment_node_disabled =  0;
1091
  static $comment_node_read_only =  1;
1092
  static $comment_node_read_write =  2;
1093

    
1094
  if ($form_id == 'node_type_form'
1095
   && isset($form['identity']['type'])
1096
   && array_key_exists($form['#node_type']->type, cdm_get_nodetypes())
1097
  ) {
1098
    $form['workflow']['comment'] = array(
1099
      '#type' => 'radios',
1100
      '#title' => t('Default comment setting'),
1101
      '#default_value' => variable_get('comment__' . $node->type . $form['#node_type']->type, $comment_node_disabled),
1102
      '#options' => array(t('Disabled'), t('Read only'), t('Read/Write')),
1103
      '#description' => t('Users with the <em>administer comments</em> permission will be able to override this setting.'),
1104
    );
1105
  }
1106
}
1107
*/
1108

    
1109
/**
1110
 * Displays a list of the known taxonomic names.
1111
 *
1112
 * When the list of taxonomic names is displayed, long lists are split up into
1113
 * multiple pages.
1114
 *
1115
 * TODO: Parameters are still preliminary.
1116
 *
1117
 * @param string $beginsWith
1118
 * @param string $page
1119
 *   Page number to diplay defaults to page 1.
1120
 * @param bool $onlyAccepted
1121
 */
1122
function cdm_dataportal_view_names($beginsWith = 'A', $page = 1, $onlyAccepted = FALSE) {
1123

    
1124
  $out = t('<h3>Sorry, the name list feature is not yet available in this version of the DataPortal software<h3>');
1125

    
1126
  /*
1127
  // FIXME the filter for accepted names will be a form element, thus this
1128
  // widget should be generated via form api preferably as block.
1129
  $out  = theme('cdm_dataportal_widget_filter_accepted', $onlyAccepted);
1130
  $out .= theme('cdm_dataportal_widget_names_list', $names, $page);
1131
  $out .= theme('cdm_listof_taxa', $taxonPager);
1132
  return $out;
1133
  */
1134
}
1135

    
1136
/**
1137
 * @todo Please document this function.
1138
 * @see http://drupal.org/node/1354
1139
 */
1140
function cdm_dataportal_view_reference($uuid, $arg2 = NULL) {
1141

    
1142
  cdm_check_valid_portal_page();
1143

    
1144
  $reference = cdm_ws_get(CDM_WS_REFERENCE, $uuid);
1145
  return theme('cdm_reference_page', array('reference' => $reference));
1146
}
1147

    
1148
/**
1149
 * Creates a view on a all references contained in the portal.
1150
 *
1151
 * This function is used at the path cdm_dataportal/reference/list
1152
 */
1153
function cdm_dataportal_view_reference_list($pageNumber) {
1154
  $referencePager = cdm_ws_page(CDM_WS_REFERENCE, variable_get('cdm_dataportal_search_items_on_page', CDM_DATAPORTAL_SEARCH_ITEMS_ON_PAGE), $pageNumber);
1155
  cdm_reference_pager($referencePager, 'cdm_dataportal/reference/list/');
1156
}
1157

    
1158
/**
1159
 * @todo Please document this function.
1160
 * @see http://drupal.org/node/1354
1161
 */
1162
function cdm_dataportal_view_media($mediaUuid, $mediarepresentation_uuid = FALSE, $part = 0) {
1163

    
1164
  cdm_check_valid_portal_page();
1165

    
1166
  $media = cdm_ws_get(CDM_WS_PORTAL_MEDIA, $mediaUuid);
1167
  return theme('cdm_media_page', array(
1168
    'media' => $media,
1169
    'mediarepresentation_uuid' => $mediarepresentation_uuid,
1170
    'partId' => $part,
1171
    ));
1172
}
1173

    
1174
/**
1175
 * @todo Please document this function.
1176
 * @see http://drupal.org/node/1354
1177
 */
1178
function _load_taxonBase(&$taxonBase) {
1179
  if (isset($taxonBase->uuid)) {
1180
    $taxonBase->name = cdm_ws_get(CDM_WS_TAXON, array($taxonBase->uuid, "name"));
1181
    $taxonBase->name->taggedName = cdm_ws_get(CDM_WS_NAME, array($taxonBase->name->uuid, "taggedName"));
1182
    $taxonBase->name->nomenclaturalReference = cdm_ws_get(CDM_WS_NAME, array($taxonBase->name->uuid, "nomenclaturalReference"));
1183
  }
1184
}
1185

    
1186
/**
1187
 * Loads the media associated to the given taxon from the cdm server.
1188
 * The aggregation settings regarding taxon relathionships and
1189
 * taxonnomic childen are taken into account.
1190
 *
1191
 * The media lists are cached in a static variable.
1192
 *
1193
 * @param Taxon $taxon
1194
 *   A CDM Taxon entitiy
1195
 *
1196
 * @return array
1197
 *   An array of CDM Media entities
1198
 *
1199
 */
1200
function _load_media_for_taxon($taxon) {
1201

    
1202
  static $media = NULL;
1203

    
1204
  if(!isset($media)) {
1205
    $media = array();
1206
  }
1207
  if (!isset($media[$taxon->uuid])) {
1208

    
1209
    // --- GET Images --- //
1210
    $mediaQueryParameters = array(
1211
        "type" => "ImageFile",
1212
    );
1213

    
1214
    $relationship_choice = variable_get(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS, unserialize(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS_DEFAULT));
1215
    $mediaQueryParameters['relationships'] = implode(',', get_selection($relationship_choice['direct']));
1216
    $mediaQueryParameters['relationshipsInvers'] = implode(',', get_selection($relationship_choice['invers']));
1217

    
1218
    $taxon_media_filter_choice = variable_get(CDM_TAXON_MEDIA_FILTER, unserialize(CDM_TAXON_MEDIA_FILTER_DEFAULT));
1219
    $mediaQueryParameters['includeTaxonDescriptions'] = (boolean) $taxon_media_filter_choice['includeTaxonDescriptions'] != 0;
1220
    $mediaQueryParameters['includeOccurrences'] = (boolean) $taxon_media_filter_choice['includeOccurrences'] != 0;
1221
    $mediaQueryParameters['includeTaxonNameDescriptions'] = (boolean) $taxon_media_filter_choice['includeTaxonNameDescriptions'] != 0;
1222

    
1223
    $ws_endpoint = NULL;
1224
    if ( variable_get('cdm_images_include_children', 0) == 0) {
1225
      $ws_endpoint = CDM_WS_PORTAL_TAXON_MEDIA;
1226
    } else {
1227
      $ws_endpoint = CDM_WS_PORTAL_TAXON_SUBTREE_MEDIA;
1228
    }
1229

    
1230
    $media[$taxon->uuid] = cdm_ws_get($ws_endpoint,
1231
        array(
1232
            $taxon->uuid,
1233
        ),
1234
        queryString($mediaQueryParameters)
1235
       );
1236
  }
1237

    
1238
  return $media[$taxon->uuid];
1239
}
1240

    
1241
/**
1242
 *
1243
 * @param Taxon $taxon
1244
 *   A CDM Taxon entitiy
1245
 *
1246
 * @return array
1247
 *   An array of CDM SpecimenOrObservation entities
1248
 *
1249
function _load_occurences_for_taxon($taxon){
1250

    
1251
  static $occurences = NULL;
1252

    
1253
  if(!isset($occurences)) {
1254
    $occurences = array();
1255
  }
1256

    
1257
  if (!isset($occurences[$taxon->uuid])){
1258

    
1259
    $relationship_choice = variable_get(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS, unserialize(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS_DEFAULT));
1260
    $relationship_choice['direct'] = get_selection($relationship_choice['direct']);
1261
    $relationship_choice['invers'] = get_selection($relationship_choice['invers']);
1262

    
1263
    $by_associatedtaxon_query = http_build_query(array(
1264
        'relationshipsInvers' => implode(',', $relationship_choice['invers']),
1265
        'relationships' => implode(',', $relationship_choice['direct']),
1266
        'pageSize' => null // all hits in one page
1267
    )
1268
    );
1269

    
1270
    $pager = cdm_ws_get(CDM_WS_OCCURRENCE_BY_ASSOCIATEDTAXON,
1271
        null,
1272
        $by_associatedtaxon_query . '&taxonUuid=' . $taxon->uuid
1273
    );
1274

    
1275

    
1276
    if(isset($pager->records[0])){
1277
      $occurences[$taxon->uuid] =  $pager->records;
1278
    }
1279
  }
1280
  return $occurences[$taxon->uuid];
1281
}
1282
 */
1283

    
1284
/**
1285
 * Gets a Drupal variable, string or array and returns it.
1286
 *
1287
 * Similar to the variable_get() function of Drupal, except that this function
1288
 * is able to handle arrays correctly. This function is especially useful
1289
 * when dealing with collections of settings form elements (#tree = TRUE).
1290
 *
1291
 * @param string $variableKey
1292
 *   The Unique key of the Drupal variable in the Drupal variables table.
1293
 * @param string $defaultValueString
1294
 *   A string as for example derived from a CONSTANT.
1295
 *
1296
 * @return mixed
1297
 *   usually an array, depending on the nature of the variable.
1298
 *
1299
 * TODO compare with get_array_variable_merged() duplicate functions?
1300
 * @deprecated rather use get_array_variable_merged() since this function
1301
 * used an array as second parameter
1302
 */
1303
function mixed_variable_get($variableKey, $defaultValueString) {
1304
  $systemDefaults = unserialize($defaultValueString);
1305
  $storedSettings = variable_get($variableKey, array());
1306
  if (is_array($storedSettings)) {
1307
    // TODO better use drupal_array_merge_deep() ?
1308
    $settings = array_merge($systemDefaults, $storedSettings);
1309
  }
1310
  else {
1311
    $settings = $systemDefaults;
1312
  }
1313
  return $settings;
1314
}
1315

    
1316
/**
1317
 * Recursive function to convert an object into an array.
1318
 * also subordinate objects will be converted.
1319
 *
1320
 * @param object $object
1321
 *  the object to be converted
1322
 * @return array
1323
 *  The array
1324
 */
1325
function object_to_array($object) {
1326
  if(is_object($object) || is_array($object)) {
1327
    $array = (array)$object;
1328
    foreach ($array as $key=>$value){
1329
      $array[$key] = object_to_array($value);
1330
    }
1331
    return $array;
1332
  } else {
1333
    return $object;
1334
  }
1335
}
1336

    
1337
/**
1338
 * Searches the $collection for the cdm entitiy given as $element.
1339
 *
1340
 * The elements are compared by their UUID.
1341
 *
1342
 * @param $element
1343
 *  the CDM entitiy to search for
1344
 * @param $collection
1345
 *  the list of CDM entities to search in
1346
 *
1347
 * @return boolean TRUE if the $collection contains the $element, otheriwse FALSE
1348
 *
1349
 */
1350
function contains_cdm_entitiy($element, $collection) {
1351
  $result = FALSE;
1352
  foreach ($collection as $a) {
1353
    if ($a->uuid == $element->uuid) {
1354
      $result = TRUE;
1355
    }
1356
  }
1357
  return $result;
1358
}
1359

    
1360
/**
1361
 * Fiters the array $entity_list of CDM entities by the list
1362
 * of $excludes. Any element contained in the $excludes will be removed
1363
 * from included int the retuned list.
1364
 *
1365
 * If the $entity_list is not an array the $excludes will be returned.
1366
 */
1367
function filter_cdm_entity_list($entity_list, $excludes) {
1368
  if (is_array($entity_list)) {
1369
    $result = $entity_list;
1370
    if ($excludes) {
1371
      foreach ($excludes as $exclude) {
1372
        if (!contains_cdm_entitiy($exclude, $entity_list)) {
1373
          $result[] = $exclude;
1374
        }
1375
      }
1376
    }
1377
  }
1378
  else {
1379
    $result = $excludes;
1380
  }
1381
  return $result;
1382
}
1383

    
1384
/**
1385
 * Wraps the given $html string into a render array suitable for drupal_render()
1386
 *
1387
 * @param $html
1388
 *   the html string, see
1389
 *   http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#markup
1390
 * @param $weight
1391
 *   A positive or negative number (integer or decimal).
1392
 *   see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#weightval
1393
 * @param $prefix
1394
 *   Optional markup for the '#prefix' element of the render array
1395
 * @param $suffix
1396
 *   Optional markup for the '#suffix' element of the render array
1397
 *
1398
 * @return array
1399
 *   A render array
1400
 *
1401
 */
1402
function markup_to_render_array($html, $weight = FALSE, $prefix = NULL, $suffix = NULL) {
1403
  $render_array = array(
1404
    '#markup' => $html
1405
      );
1406
  if (is_numeric($weight)) {
1407
    $render_array['#weight'] = $weight;
1408
  }
1409
  if($prefix){
1410
    $render_array['#prefix'] = $prefix;
1411
  }
1412
  if($suffix) {
1413
    $render_array['#suffix'] = $suffix;
1414
  }
1415
  return $render_array;
1416
}
1417

    
1418
/**
1419
 * Loads the subgraph of a given PolytomousKeyNode.
1420
 *
1421
 * Loads the subgraph of the given PolytomousKeyNode recursively from
1422
 * the CDM REST service.
1423
 *
1424
 * @param mixed $polytomousKeyNode
1425
 *   PolytomousKeyNode passed by reference.
1426
 *
1427
 * @return void
1428
 */
1429
function _load_polytomousKeySubGraph(&$polytomousKeyNode) {
1430

    
1431
  if (!$polytomousKeyNode) {
1432
    return;
1433
  }
1434
  if ($polytomousKeyNode->class != "PolytomousKeyNode") {
1435
    drupal_set_message('_load_polytomousKeySubGraph(): ' . t('invalid type given.'), 'error');
1436
    return;
1437
  }
1438
  if (!is_uuid($polytomousKeyNode->uuid)) {
1439
    drupal_set_message('_load_polytomousKeySubGraph(): ' . t('invalid type given.'), 'error');
1440
    return;
1441
  }
1442

    
1443
  $polytomousKeyNode = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, $polytomousKeyNode->uuid);
1444

    
1445
  if (!$polytomousKeyNode) {
1446
    // drupal_set_message("_load_polytomousKeyChildNodes() : could not load polytomousKeyNode", "error");
1447
    return;
1448
  }
1449

    
1450
  // Load children.
1451
  foreach ($polytomousKeyNode->children as &$childNode) {
1452
    _load_polytomousKeySubGraph($childNode);
1453
  }
1454

    
1455
  // Load subkey.
1456
  $polytomousKeyNode->subkey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "subkey"));
1457

    
1458
  // Load taxon.
1459
  $polytomousKeyNode->taxon = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "taxon"));
1460
  _load_taxonBase($polytomousKeyNode->taxon);
1461
  return;
1462
}
1463

    
1464
/**
1465
 * @todo Please document this function.
1466
 * @see http://drupal.org/node/1354
1467
 */
1468
function cdm_dataportal_view_polytomousKey($polytomousKeyUuid) {
1469

    
1470
  cdm_check_valid_portal_page();
1471

    
1472
  $polytomousKey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, $polytomousKeyUuid);
1473

    
1474
  $sourcePager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'sources'));
1475
  if (is_array($sourcePager->records)) {
1476
    $polytomousKey->sources = $sourcePager->records;
1477
    // $polytomousKey->sources->citation = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'sources'));
1478
  }
1479

    
1480
  $annotationPager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'annotations'));
1481
  if (is_array($annotationPager->records)) {
1482
    $polytomousKey->annotations = $annotationPager->records;
1483
  }
1484

    
1485
  _load_polytomousKeySubGraph($polytomousKey->root);
1486
  return theme('cdm_polytomousKey_page', array('polytomousKey' => $polytomousKey));
1487
}
1488

    
1489
/**
1490
 * Creates a taxon page view or a chapter of it.
1491
 *
1492
 * The taxon page gives detailed information on a taxon, it shows:
1493
 *  - Taxon name.
1494
 *  - Full list of synonyms homotypic synonyms on top, followed by the
1495
 *    heterotypic and finally followed by misapplied names.
1496
 *    The list is ordered historically.
1497
 *  - All description associated with the taxon.
1498
 *
1499
 * @param string $uuid
1500
 * @param string $chapter
1501
 *   Name of the part to display, valid values are:
1502
 *   'description', 'images', 'synonymy', 'specimens', 'all'.
1503
 *
1504
 * @return string
1505
 */
1506
function cdm_dataportal_taxon_page_view($uuid, $chapter = 'all') {
1507

    
1508
  cdm_check_valid_taxon_page($chapter);
1509
  cdm_dd("START OF TAXON PAGE [" . $chapter . "] " . $uuid . ' for ' . $_GET['q']);
1510
  // show a warning in case the javascript development mode is anabled
1511
  if(variable_get('cdm_js_devel_mode', FALSE)) {
1512
    drupal_set_message(t('The !url1 is enabled.
1513
        WARNING: this is a performance penalty and must be turned off on production websites.', array(
1514
          '!url1' => l('java-script development mode', 'admin/config/cdm_dataportal/settings', array('fragment' => 'edit-cdm-js-devel-mode'))
1515
    )),
1516
    'warning'
1517
        );
1518
  }
1519

    
1520
  // Display the page for the taxon defined by $uuid.
1521
  // set_last_taxon_page_tab(arg(3));
1522
  $taxonpage = cdm_dataportal_taxon_view($uuid, $chapter);
1523
  if (!empty($taxonpage)) {
1524
    cdm_dd("END OF TAXON PAGE [" . $chapter . "] " . $uuid);
1525
    return cdm_node_show(NODETYPE_TAXON, $uuid, $taxonpage->title, $taxonpage->content);
1526
  }
1527
  else {
1528
    cdm_dd("END OF TAXON PAGE [" . $chapter . "] " . $uuid . ' !!! PAGE IS EMPTY !!!');
1529
    return '';
1530
  }
1531
}
1532

    
1533
/**
1534
 * This function will genreate the taxon page part ($chapter) and returns a taxonpage object
1535
 * which has two fields, one for the page title and one for the content. Later on in the
1536
 * process chain the value contained in these fields will be passed to the cdm_node_show()
1537
 * function as the function parameters $title and $content.
1538
 *
1539
 * @param string $uuid
1540
 *   the uuid of the taxon to show
1541
 * @param string $chapter
1542
 *   Name of the part to display, valid values are:
1543
 *   'description', 'images', 'synonymy', 'all'.
1544
 *
1545
 * @return object with the following fields:
1546
 *   - title : the title of the page
1547
 *   - content: the content of the page
1548
 *
1549
 */
1550
function cdm_dataportal_taxon_view($uuid, $chapter = 'all') {
1551
  // Taxon object.
1552
  $taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON, $uuid);
1553
  if (empty($taxon)) {
1554
    drupal_set_title(t('Taxon does not exist'), PASS_THROUGH);
1555
    return FALSE;
1556
  }
1557
  $taxonpage = new stdClass();
1558

    
1559
  $taxonpage->title = theme('cdm_taxon_page_title', array(
1560
    'taxon' => $taxon
1561
  ));
1562

    
1563
  // Check if the taxon id contained in the currently selected tree.
1564
  $taxon_in_current_classification = taxon_in_current_classification($uuid);
1565

    
1566
  if (!$taxon_in_current_classification) {
1567
    $classifications = get_classifications_for_taxon($taxon);
1568
    RenderHints::pushToRenderStack('not_in_current_classification');
1569
    $taxon_name_markup = render_taxon_or_name($taxon);
1570

    
1571
    if (count($classifications) == 0) {
1572
      drupal_set_message(t('This concept of the taxon !taxonname is not contained as an accepted taxon in the currently chosen classification.',
1573
        array(
1574
        '!taxonname' => $taxon_name_markup,
1575
        )
1576
      ), 'warning');
1577
    }
1578
    else {
1579
      $trees = '';
1580
      foreach ($classifications as $classification) {
1581
        if (isset($classification->titleCache)) {
1582
          $trees .= ($trees ? ', ' : '') . '<strong>' . $classification->titleCache . '</strong>';
1583
        }
1584
      }
1585

    
1586
      drupal_set_message(format_plural(count($trees),
1587
          'This concept of the taxon !taxonname is not contained as an accepted taxon in the currently chosen classification, but in this one: !trees',
1588
          'This concept of the taxon !taxonname is not contained as an accepted taxon in the currently chosen classification, but in one of these: !trees',
1589
          array('!taxonname' => $taxon_name_markup, '!trees' => $trees)
1590
        ) ,
1591
        'warning');
1592
    }
1593
    RenderHints::popFromRenderStack();
1594
  }
1595

    
1596
  // Render the taxon page.
1597
  $render_array = compose_cdm_taxon_page($taxon, $chapter);
1598
  $taxonpage->content = drupal_render($render_array);
1599

    
1600
  return $taxonpage;
1601
}
1602

    
1603
/**
1604
 * Creates a specimen page view.
1605
 * @param string $uuid the UUID of the specimen
1606
 * @return array|string
1607
 */
1608
function cdm_dataportal_specimen_page_view($uuid) {
1609

    
1610
    //cdm_check_valid_taxon_page($chapter);
1611
    //cdm_dd("START OF TAXON PAGE [" . $chapter . "] " . $uuid . ' for ' . $_GET['q']);
1612
    // show a warning in case the javascript development mode is anabled
1613
    if(variable_get('cdm_js_devel_mode', FALSE)) {
1614
        drupal_set_message(t('The !url1 is enabled.
1615
        WARNING: this is a performance penalty and must be turned off on production websites.', array(
1616
            '!url1' => l('java-script development mode', 'admin/config/cdm_dataportal/settings', array('fragment' => 'edit-cdm-js-devel-mode'))
1617
        )),
1618
            'warning'
1619
        );
1620
    }
1621

    
1622
    // Display the page for the specimen defined by $uuid.
1623
    $specimenpage = cdm_dataportal_specimen_view($uuid);
1624
    if (!empty($specimenpage)) {
1625
        return cdm_node_show(NODETYPE_TAXON, $uuid, $specimenpage->title, $specimenpage->content);
1626
    }
1627
    else {
1628
        return '';
1629
    }
1630
}
1631

    
1632
/**
1633
 *
1634
 * Creates a specimen view.
1635
 * @param string $uuid the UUID of the specimen
1636
 * @return array|string
1637
 */
1638
function cdm_dataportal_specimen_view($uuid) {
1639
    $specimen = cdm_ws_get(CDM_WS_PORTAL_OCCURRENCE, $uuid);
1640
    if (empty($specimen)) {
1641
        drupal_set_title(t('Specimen does not exist'), PASS_THROUGH);
1642
        return FALSE;
1643
    }
1644
    $specimenpage = new stdClass();
1645

    
1646
    $specimenpage->title = theme('cdm_specimen_page_title', array(
1647
        'specimen' => $specimen
1648
    ));
1649

    
1650
    // Render the specimen page.
1651
    $render_array = compose_cdm_specimen_page($uuid);
1652
    $specimenpage->content = drupal_render($render_array);
1653

    
1654
    return $specimenpage;
1655
}
1656

    
1657
/**
1658
 *
1659
 * Creates a named area view.
1660
 * @param string $uuid the UUID of the specimen
1661
 *  * @return object
1662
 *   An object with two fields:
1663
 *     - title: the page title
1664
 *     - content: the page content
1665
 */
1666

    
1667
function cdm_dataportal_named_area_view($uuid) {
1668
  $named_area = cdm_ws_get(CDM_WS_PORTAL_TERM, $uuid);
1669
  if (empty($named_area) || $named_area->class !== 'NamedArea') {
1670
    drupal_set_title(t('Named area does not exist'), PASS_THROUGH);
1671
    return FALSE;
1672
  }
1673
  $named_area_page = new stdClass();
1674

    
1675
  $named_area_page->title = $named_area->representation_L10n;
1676

    
1677
  // Render the specimen page.
1678
  $render_array = compose_cdm_named_area_page($uuid);
1679
  $named_area_page->content = drupal_render($render_array);
1680

    
1681
  return $named_area_page;
1682
}
1683

    
1684
function cdm_dataportal_named_area_page_view($uuid) {
1685

    
1686
  cdm_check_valid_portal_page();
1687

    
1688
  $named_area_page = cdm_dataportal_named_area_view($uuid);
1689
  if (!empty($named_area_page)) {
1690
    return cdm_node_show(NODETYPE_NAME, $uuid, $named_area_page->title, $named_area_page->content);
1691
  }
1692
  else {
1693
    return '';
1694
  }
1695

    
1696

    
1697
}
1698

    
1699
/**
1700
 * Returns a name page as a Drupal node ready to be renderized by Drupal.
1701
 *
1702
 * The node page shows the taxon name title and the list of taxon related
1703
 * with such taxon. Name on the tree already in use.
1704
 *
1705
 * @param UUID $taxon_name_uuid
1706
 *   The uuid of the CDM TaxonName to show a name page for
1707
 * @param UUID $taxon_to_hide_uuid
1708
 *   A taxon which should not be displayed in the taxon list
1709
 * @param UUID $highlite_synonym_uuid
1710
 *   Optinal parameter wich takes another taxon uuid, if given the
1711
 *   target taxon pages will show the syonymy tab where the taxon
1712
 *   refenrenced by the $highlite_synonym_uuid will be highlighted
1713
 *   in case it is found on this page.
1714
 *
1715
 * @return mixed
1716
 *   The formatted name page as node.
1717
 */
1718
function cdm_dataportal_name_page_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid = NULL) {
1719

    
1720
  cdm_check_valid_portal_page();
1721

    
1722
  $taxonname_page = cdm_dataportal_name_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid);
1723
  if (!empty($taxonname_page)) {
1724
    return cdm_node_show(NODETYPE_NAME, $taxon_name_uuid, $taxonname_page->title, $taxonname_page->content);
1725
  }
1726
  else {
1727
    return '';
1728
  }
1729
}
1730

    
1731
/**
1732
 * View function for a TaxonName page.
1733
 *
1734
 * The name page lists all taxa for which the name specified by the
1735
 * $taxon_name_uuid is being used. I case there is only one name the
1736
 * page automatically redirects ti the according taxon page. Otherwise
1737
 * the list of names is displayed.
1738
 *
1739
 * The parameter $taxon_to_hide_uuid allows to exclude a taxon from the
1740
 * list of taxa. This is useful for example when referencing from a taxon
1741
 * to the name page and the referring taxon should not be repeaded in the
1742
 * name page.
1743
 *
1744
 *
1745
 * @param UUID $taxon_name_uuid
1746
 *   The uuid of the CDM TaxonName to show a name page for
1747
 * @param UUID $taxon_to_hide_uuid
1748
 *   A taxon which should not be displayed in the taxon list
1749
 * @param UUID $highlite_synonym_uuid
1750
 *   Optinal parameter wich takes another taxon uuid, if given the
1751
 *   target taxon pages will show the syonymy tab where the taxon
1752
 *   refenrenced by the $highlite_synonym_uuid will be highlighted
1753
 *   in case it is found on this page.
1754
 *
1755
 * @return object
1756
 *   An object with two fields:
1757
 *     - title: the page title
1758
 *     - content: the page content
1759
 */
1760
function cdm_dataportal_name_view($taxon_name_uuid, $taxon_to_hide_uuid, $highlite_synonym_uuid = NULL) {
1761
  // Getting the full taxonname object from the server.
1762
  $taxon_name = cdm_ws_get(CDM_WS_PORTAL_NAME, array($taxon_name_uuid));
1763
  if (!$taxon_name) {
1764
    drupal_set_title(t('Taxon name does not exist'), PASS_THROUGH);
1765
    return FALSE;
1766
  }
1767
  // Searching for all the taxa connected with the taxon name on the tree
1768
  // in use.
1769
  $name_cache = cdm_ws_get(CDM_WS_NAME_NAMECAHE, array($taxon_name_uuid));
1770
  $request_params = array();
1771
  $request_params['query'] = $name_cache;
1772
  $request_params['tree'] = get_current_classification_uuid();
1773
  $request_params['doTaxa'] = 1;
1774
  $request_params['doSynonyms'] = 1;
1775
  $request_params['doTaxaByCommonNames'] = 0;
1776
  $request_params['matchMode'] = "EXACT";
1777
  $taxon_pager = cdm_ws_get(CDM_WS_PORTAL_TAXON_FIND, NULL, queryString($request_params));
1778

    
1779
  // Removing the name where we came from.
1780
  foreach ($taxon_pager->records as $k => &$taxon) {
1781
    if ($taxon->uuid == $taxon_to_hide_uuid) {
1782
      unset($taxon_pager->records[$k]);
1783
    }
1784
  }
1785
  // Show the taxa list or go to the singular taxon.
1786
  if (sizeof($taxon_pager->records) == 1) {// Single taxon case.
1787
    $singleTaxon = array_pop($taxon_pager->records);
1788
    if ($singleTaxon->class != "Taxon") {
1789
      // It is a Synonym -> look for the accepted.
1790
      $accepted_taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON_ACCEPTED, array($singleTaxon->uuid), 'classificationFilter=' . get_current_classification_uuid());
1791
      if (!empty($highlite_synonym_uuid)) {
1792
        drupal_goto('cdm_dataportal/taxon/' . $accepted_taxon->uuid . '/synonymy', array('query' => array('highlite' => $highlite_synonym_uuid)));
1793
      }
1794
      else {
1795
        drupal_goto('cdm_dataportal/taxon/' . $accepted_taxon->uuid . '/synonymy', array('query' => array('highlite' => $singleTaxon->uuid)));
1796
      }
1797
    }
1798
    else {
1799
      // It is an accepted taxon.
1800
      if (!empty($highlite_synonym_uuid)) {
1801
        drupal_goto('cdm_dataportal/taxon/' . $singleTaxon->uuid . '/synonymy', array('query' => array('highlite' => $highlite_synonym_uuid)));
1802
      }
1803
      else {
1804
        drupal_goto('cdm_dataportal/taxon/' . $singleTaxon->uuid);
1805
      }
1806
    }
1807
  }
1808
  else {// More than one taxa case.
1809
    $taxon_name_page = new stdClass();
1810
    $taxon_name_page->title = theme('cdm_name_page_title', array('taxon_name' => $taxon_name));
1811
    if ($taxon_pager->records) {
1812
      $taxon_name_page->content = compose_list_of_taxa($taxon_pager->records);
1813
    }
1814
    else {
1815
      $taxon_name_page->content = 'This name is not assigned to a taxon.';
1816
    }
1817
    return $taxon_name_page;
1818
  }
1819
}
1820

    
1821
/**
1822
 * Returns a registration page as a Drupal node to be rendered by Drupal.
1823
 *
1824
 * @param string  $registration_identifier_encoded
1825
 *   The persistent identifier of the registration urlencoded.
1826
 * @return mixed
1827
 *   The formatted registration page as node.
1828
 */
1829
function cdm_dataportal_registration_page_view($registration_identifier_encoded) {
1830

    
1831
  cdm_check_valid_portal_page("/\/cdm_dataportal\/registration\/.*$/");
1832
  $registration_page = cdm_dataportal_registration_view($registration_identifier_encoded);
1833
  return cdm_node_show_simulate($registration_page);
1834
}
1835

    
1836
function cdm_dataportal_registration_view($registration_identifier_encoded) {
1837

    
1838
  $registration_identifier = urldecode($registration_identifier_encoded);
1839

    
1840

    
1841
  $render_array = array();
1842

    
1843
  $registration_dto = cdm_ws_get("registrationDTO/identifier/" . $registration_identifier_encoded);
1844
  if($registration_dto){
1845
    drupal_set_title(t('Registration') . ' ' . $registration_identifier, PASS_THROUGH);
1846

    
1847
    $render_array['citation'] = markup_to_render_array("<div class=\"" . html_class_attribute_ref(new TypedEntityReference("Reference", $registration_dto->citationUuid)) . "\">"
1848
      . l($registration_dto->bibliographicCitationString, path_to_registration_workingset($registration_dto->citationUuid))
1849
      . "</br>&nbsp;</div>");
1850
    $render_array['summary'] = markup_to_render_array("<div>" . cdm_tagged_text_to_markup($registration_dto->summaryTaggedText) . "</div>");
1851

    
1852
    if(is_object($registration_dto->orderdTypeDesignationWorkingSets)){
1853

    
1854
      $field_unit_uuids = array();
1855
      foreach((array)$registration_dto->orderdTypeDesignationWorkingSets as $field_unit_ref => $obj){
1856
        $tokens = explode("#", $field_unit_ref);
1857
        $field_unit_uuids[] = $tokens[1];
1858
      }
1859
      $render_array['specimen_table'] = compose_derivate_hierarchy_table($field_unit_uuids);
1860
    }
1861

    
1862
  } else {
1863
    drupal_set_title(t('Registration not found'), PASS_THROUGH);
1864
    $render_array['error'] = markup_to_render_array("A registration with the identifier  " . $registration_identifier . " does not exist.");
1865
  }
1866

    
1867
  return $render_array ;
1868
}
1869

    
1870

    
1871

    
1872
/**
1873
 * Creates a page with the advance search form.
1874
 *
1875
 * NOTE: The advance search form allows searching for taxa.
1876
 */
1877
function cdm_dataportal_view_search_advanced() {
1878
  drupal_set_title(t('Advanced search'), PASS_THROUGH);
1879
  return drupal_get_form('cdm_dataportal_search_taxon_form_advanced');
1880
}
1881

    
1882
/**
1883
 * Creates a page with the search form for searching by taxon descriptions.
1884
 */
1885
function cdm_dataportal_view_search_taxon_by_description() {
1886
  drupal_set_title(t('Search by factual data'), PASS_THROUGH);
1887
  return drupal_get_form('cdm_dataportal_search_taxon_by_description_form');
1888
}
1889

    
1890
/**
1891
 * Executes the search and generates the result list of taxa.
1892
 */
1893
function cdm_dataportal_view_search_results_taxon() {
1894

    
1895
  $taxonPager = cdm_dataportal_search_taxon_execute();
1896

    
1897
  $showThumbnails = do_showThumbnails();
1898

    
1899
  $setSessionUri = url('cdm_api/setvalue/session', array(
1900
      'query' => array('var' => '[pageoption][searchtaxa][showThumbnails]', 'val' => ''),
1901
  ));
1902

    
1903
  drupal_add_js('jQuery(document).ready(function() {
1904

    
1905
      // init
1906
      if(' . $showThumbnails . ' == 1){
1907
          jQuery(\'.media_gallery\').show(20);
1908
      } else {
1909
          jQuery(\'.media_gallery\').hide(20);
1910
      }
1911

    
1912
      // add change handler
1913
      jQuery(\'#showThumbnails input.showThumbnails\').change(
1914
      function(event){
1915
        var state = 0;
1916
        if(jQuery(this).is(\':checked\')){
1917
          jQuery(\'.media_gallery\').show(20);
1918
          state = 1;
1919
        } else {
1920
          jQuery(\'.media_gallery\').hide(20);
1921
        }
1922
        // store state in session variable
1923
        var uri = \'' . $setSessionUri . '\' + state;
1924
        jQuery.get(uri);
1925
      });
1926
  });',
1927
  array('type' => "inline", 'scope' => JS_DEFAULT));
1928

    
1929
  drupal_set_title(t('Search results'), PASS_THROUGH);
1930

    
1931
  return theme('cdm_search_taxa_results', array(
1932
    'pager' => $taxonPager,
1933
    'path' => 'cdm_dataportal/search/results/taxon',
1934
    ));
1935
}
1936

    
1937
/**
1938
 * Executes the search for registrations and generates the result list..
1939
 */
1940
function cdm_dataportal_view_search_registrations_results() {
1941

    
1942
  $block = block_load('cdm_dataportal', 'registrations_search_filter');
1943
  $render_array = _block_get_renderable_array(_block_render_blocks(array($block)));
1944

    
1945
  $registration_pager = cdm_dataportal_search_registrations_execute();
1946

    
1947
  drupal_set_title(t('Search registrations'), PASS_THROUGH);
1948

    
1949
  $registrations_pager_array = compose_registrations_search_results($registration_pager);
1950

    
1951
  $render_array = array_merge($render_array, $registrations_pager_array);
1952

    
1953
  return $render_array;
1954
}
1955

    
1956

    
1957
/**
1958
 * Provides the standart image wich indicated a loading process
1959
 *
1960
 * @return string
1961
 *  The img html tag
1962
 */
1963
function loading_image_html() {
1964
  return '<img class="loading" src="' . base_path() . drupal_get_path('module', 'cdm_dataportal')
1965
    . '/images/loading_circle_grey_16.gif" style="display:none;">';
1966
}
1967

    
1968
/**
1969
 * Returns the state of the the showThumbnails flag set in the
1970
 * users session ($_SESSION['pageoption']['searchtaxa']['showThumbnails']).
1971
 *
1972
 * @return boolean
1973
 *    returns 1 if the flag is set
1974
 */
1975
function do_showThumbnails() {
1976
  static $showThumbnails = null;
1977

    
1978
  if($showThumbnails == null) {
1979
    $showThumbnails = 0;
1980
    if (!isset($_SESSION['pageoption']['searchtaxa']['showThumbnails'])) {
1981
      $showThumbnails = 0;
1982
      $search_gallery_settings = variable_get(CDM_DATAPORTAL_SEARCH_GALLERY_NAME, null);
1983
      $showThumbnails = is_array($search_gallery_settings)
1984
        && isset($search_gallery_settings['cdm_dataportal_show_taxon_thumbnails'])
1985
        && (
1986
            $search_gallery_settings['cdm_dataportal_show_taxon_thumbnails'] +
1987
            $search_gallery_settings['cdm_dataportal_show_synonym_thumbnails'] +
1988
            $search_gallery_settings['cdm_dataportal_show_thumbnail_captions'] > 0
1989
            )
1990
         ? 1 : 0;
1991

    
1992
       drupal_array_set_nested_value($_SESSION, array('pageoption', 'searchtaxa', 'showThumbnails'), $showThumbnails);
1993
    }
1994
    $showThumbnails = $_SESSION['pageoption']['searchtaxa']['showThumbnails'];
1995
    if (!is_numeric($showThumbnails)) {
1996
      $showThumbnails = 1;
1997
    }
1998
  }
1999

    
2000
  return $showThumbnails;
2001
}
2002

    
2003

    
2004

    
2005
/* ====================== other functions ====================== */
2006
/**
2007
 * Creates a URL to the taxon page specified by the $uuid parameter.
2008
 *
2009
 * The URL will be prepended with a path element to a specific taxon page tab.
2010
 *
2011
 * This tab is either taken from the CDM_DATAPORTAL_DEFAULT_TAXON_TAB which can
2012
 * be set globally in the administrative settings or individually in the user
2013
 * profile. If the CDM_DATAPORTAL_DEFAULT_TAXON_TAB value is set to LAST_VISITED_TAB
2014
 * the last portal will stay on this last tab.
2015
 *
2016
 * A third option is offerered by the $page_tab parameter which allows overwriting this
2017
 * internal mechanism by a specific value.
2018
 *
2019
 * @param string $uuid
2020
 *   The UUID of the taxon.
2021
 * @param string $page_tab
2022
 *   Overwriting the preset mechanism by defining specific value for the
2023
 *   taxon page tab.
2024
 *
2025
 * @return string
2026
 *   The created URL.
2027
 */
2028
function path_to_taxon($uuid, $page_tab = FALSE) {
2029

    
2030
  $tab = get_default_taxon_tab();
2031
  $values = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
2032

    
2033
  if (!$uuid) {
2034
    return FALSE;
2035
  }
2036

    
2037
  if ($page_tab) {
2038
    return 'cdm_dataportal/taxon/' . $uuid . '/' . $page_tab;
2039
  }
2040
  elseif (!$tab || strtolower($tab) == 'general') {
2041
    return 'cdm_dataportal/taxon/' . $uuid;
2042
  }
2043
  elseif (get_last_taxon_page_tab() &&   $tab == $values[CDM_DATAPORTAL_LAST_VISITED_TAB_ARRAY_INDEX]) {
2044
    return 'cdm_dataportal/taxon/' . $uuid . '/' . get_last_taxon_page_tab();
2045
  }
2046
  else {
2047
    return 'cdm_dataportal/taxon/' . $uuid . '/' . strtolower($tab);
2048
  }
2049
}
2050

    
2051
function path_to_specimen($uuid) {
2052

    
2053
    if (!$uuid) {
2054
        return FALSE;
2055
    }
2056
    else {
2057
        return 'cdm_dataportal/specimen/' . $uuid;
2058
    }
2059
}
2060

    
2061
function path_to_named_area($uuid) {
2062

    
2063
  if (!$uuid) {
2064
    return FALSE;
2065
  }
2066
  else {
2067
    return 'cdm_dataportal/named_area/' . $uuid;
2068
  }
2069
}
2070

    
2071
/**
2072
 * Creates a URL to show a synonmy in the according taxon page.
2073
 *
2074
 * The URL will point to the synonymy tab of the taxon page of the accepted taxon given as parameter $acceptedUuid.
2075
 * The resulting URI will include query parameters to highlight the synonym, and to optionally display
2076
 * the accepted taxons name in aform like "Foo bar is accepted taxon for Ree doo". The URI will also
2077
 * include the sysnonym uuid as fragment in order to let the browser scroll to the according location
2078
 * in the page
2079
 *
2080
 * @param string $synonymUuid
2081
 *    The uuid of the synonym
2082
 * @param string $acceptedUuid
2083
 *    The uuid of the according accepted taxon
2084
 * @return string
2085
 *    The URL to show a synonmy in the according taxon page
2086
 */
2087
function uri_to_synonym($synonymUuid, $acceptedUuid) {
2088
  $acceptedPath = path_to_taxon($acceptedUuid, "synonymy");
2089
  return url($acceptedPath, array(
2090
      'query' => array(
2091
        // highlite the synony in the synonymy
2092
        'highlite' => $synonymUuid,
2093
        // the taxon page is refered from a synonym and the synonym can optionally be named in the page title
2094
        // see theme_taxon_page_title()
2095
        'acceptedFor' => $synonymUuid
2096
      ),
2097
      'fragment' => $synonymUuid
2098
  ));
2099

    
2100
}
2101

    
2102
/**
2103
 * Composes the drupal path to the key identified by the uuid.
2104
 *
2105
 * @param string $keyType
2106
 *    the key typer corresponds to the specific class of the CDM
2107
 *    IdentificationKey. Possible values are
2108
 *      -PolytomousKey
2109
 *      -MultimediaKey
2110
 *      - ...
2111
 * @param string $keyUuid
2112
 *   The UUID of the key
2113
 */
2114
function path_to_key($keyType, $keyUuid) {
2115
  if (!$keyUuid || !$keyType) {
2116
    return FALSE;
2117
  }
2118
  $keyType{0} = strtolower($keyType{0});
2119
  return "cdm_dataportal/" . $keyType . "/$keyUuid";
2120
}
2121

    
2122
/**
2123
 * Composes the drupal path to the reference identified by the uuid.
2124
 *
2125
 * @param $uuid string String representation of the registration entity uuid.
2126
 *
2127
 * @return string
2128
 *  The drupal path
2129
 *
2130
 */
2131
function path_to_reference($uuid) {
2132
  if (!$uuid) {
2133
    return FALSE;
2134
  }
2135
  return 'cdm_dataportal/reference/' . $uuid;
2136
}
2137

    
2138
/**
2139
 * Composes the drupal path to the reference identified by the uuid.
2140
 *
2141
 * @param string $identifier
2142
 *  The persistent identifier of the registration entity (Registration.identifier).
2143
 * @return string
2144
 *  The drupal path
2145
 */
2146
function path_to_registration($identifier) {
2147

    
2148
  return 'cdm_dataportal/registration/' . urlencode($identifier);
2149
}
2150

    
2151

    
2152
/**
2153
 * Composes the drupal path to the reference identified by the uuid.
2154
 *
2155
 * @param $uuid string
2156
 *    The uuid of the reference which is the base entity for registration workingset..
2157
 *
2158
 * @return string
2159
 *  The drupal path
2160
 */
2161
function path_to_registration_workingset($identifier) {
2162

    
2163
  return 'cdm_dataportal/reference/' . urlencode($identifier);
2164
}
2165

    
2166
/**
2167
 * Creates the path to a cdm_dataportal taxon name page.
2168
 *
2169
 * @param string $taxon_name_uuid
2170
 *   The uuid as string of the CDM TaxonName to show a name page for
2171
 * @param string $taxon_to_hide_uuid
2172
 *   The uuid as string of a taxon which should not be displayed in the taxon list
2173
 * @param string $highlite_synonym_uuid
2174
 *   Optional parameter which takes another taxon uuid, if given the
2175
 *   target taxon pages will show the synonymy tab where the taxon
2176
 *   referenced by the $highlite_synonym_uuid will be highlighted
2177
 *   in case it is found on this page.
2178
 *
2179
 * @return string
2180
 *  URI path element as string
2181
 */
2182
function path_to_name($name_uuid, $taxon_to_hide_uuid = NULL, $synonym_uuid  = NULL) {
2183
  $res = FALSE;
2184
  if ($name_uuid) {
2185
    $res = 'cdm_dataportal/name/' . $name_uuid;
2186
  }
2187
  if($taxon_to_hide_uuid){
2188
    $res .= '/' . $taxon_to_hide_uuid;
2189
    if($synonym_uuid){
2190
      $res .= '/' . $synonym_uuid;
2191
    }
2192
  }
2193
  return $res;
2194
}
2195

    
2196
/**
2197
 * Composes the drupal path to the media entity identified by the uuid.
2198
 *
2199
 * @param string $uuid
2200
 *  The persistent identifier of the entity entity
2201
 * @return string
2202
 *  The drupal path
2203
 */
2204
function path_to_media($uuid, $representaion_uuid = FALSE, $partId = FALSE) {
2205
  if (!$uuid) {
2206
    return FALSE;
2207
  }
2208
  $out = 'cdm_dataportal/media/' . $uuid;
2209
  if ($representaion_uuid) {
2210
    $out .= '/' . $representaion_uuid;
2211
    if (is_numeric($partId)) {
2212
      $out .= '/' . $partId;
2213
    }
2214
  }
2215
  return $out;
2216
}
2217

    
2218
/**
2219
 * Compares thisRank with thatRank.
2220
 *
2221
 * Returns a negative integer, zero, or a positive integer
2222
 * as the of thisRank is higher than, equal to, or lower than thatRank.
2223
 * e.g:
2224
 * <ul>
2225
 * <li>rank_compare({species_uuid}, {genus_uuid}) = -1</li>
2226
 * <li>rank_compare({genus_uuid}, {genus_uuid}) = 0</li>
2227
 * <li>rank_compare({genus_uuid}, {tribus_uuid}) = 1</li>
2228
 * </ul>
2229
 * <p>
2230
 * This compare logic of the underlying webservice is the
2231
 * <b>inverse logic</b> of the the one implemented in
2232
 * java.lang.Comparable#compareTo(java.lang.Object)
2233
 *
2234
 * @param $thisRankUuid
2235
 * @param $thatRankUuid
2236
 *
2237
 * @return int
2238
 *   A negative integer, zero, or a positive integer
2239
 *   as the thisRank is lower than, equal to, or higher than thatRank.
2240
 */
2241
function rank_compare($thisRankUuid, $thatRankUuid) {
2242
  $result = cdm_ws_get(CDM_WS_TERM_COMPARE, array($thisRankUuid, $thatRankUuid));
2243
  return $result->Integer;
2244
}
2245

    
2246
/**
2247
 * Composes an HTML element class attribute value composed of
2248
 * the short-name of the cdm class and the uuid of the entity.
2249
 * This class attribute should be used wherever an cdm-entity is rendered.
2250
 *
2251
 * In case of Taxon entities or TaxonNodeDTOs the secReference is also added
2252
 * to the class attributes as 'sec_uuid:<uuid>'. In case of TaxonNodeDTOs the
2253
 * Taxon uuid is added also as taxon_uuid:<uuid>
2254
 *
2255
 * These according class selectors in css must be escaped, eg:
2256
 *    .cdm\:TextData
2257
 *
2258
 * @param $cdm_entity
2259
 *    A CDM entity, TaxonNodeDTO or TypedEntityReference
2260
 */
2261
function html_class_attribute_ref($cdm_entity) {
2262

    
2263
  $attributes = '';
2264
  if (is_cdm_entity($cdm_entity)) {
2265
    $attributes =  "cdm:" . $cdm_entity->class . " uuid:" . $cdm_entity->uuid;
2266
  } else if($cdm_entity->class == 'TypedEntityReference') {
2267
    $attributes =  "cdm:" . $cdm_entity->type . " uuid:" . $cdm_entity->uuid;
2268
  }
2269
  if($cdm_entity->class == 'TaxonNodeDto'){
2270
    $attributes .= " taxon_uuid:"  . $cdm_entity->taxonUuid . " sec_uuid:"  . $cdm_entity->secUuid;;
2271
  }
2272
  if($cdm_entity->class == 'Taxon' && isset($cdm_entity->sec->uuid)){
2273
    $attributes .= " sec_uuid:"  . $cdm_entity->sec->uuid;
2274
  }
2275
  return $attributes;
2276
}
2277

    
2278

    
2279
/**
2280
 * Creates a short version of a taxonname.
2281
 *
2282
 * The short name is created by using the taggedTitle field of
2283
 * TaxonNodeDTO instances.
2284
 * If the taggedTitle if empty the fullname will be returned.
2285
 *
2286
 * @param object $taxonNodeDTO
2287
 *   A TaxonNodeDTO object
2288
 *
2289
 * @return string
2290
 */
2291
function cdm_dataportal_shortname_of($taxonNodeDTO) {
2292

    
2293
  $nameStr = '';
2294

    
2295
  normalize_tagged_text($taxonNodeDTO->taggedTitle);
2296

    
2297
  // Get all tagged text tokens of the scientific name.
2298
  foreach ($taxonNodeDTO->taggedTitle as $tagtxt) {
2299
    if ($tagtxt->type == 'name' || $tagtxt->type == 'rank') {
2300
      $nameStr .= ($nameStr ? ' ' : '') . $tagtxt->text;
2301
    }
2302
  }
2303
  $nameStr = trim($nameStr);
2304

    
2305
  if ($nameStr) {
2306

    
2307
    // Do not return short names for these.
2308
    if ($taxonNodeDTO->unplaced || $taxonNodeDTO->excluded) {
2309
      return $nameStr;
2310
    }
2311

    
2312
    /*
2313
    1st capture group (^[a-zA-Z]): First letter of uninomial.
2314
    Second capture group ([\p{L}]+): remaining letters of uninomial ([\p{L} = an UTF-8 letter).
2315
    Third capture group (\s+[^(\x2E]+\s+.+$|\s+[a-zA-Z]+$): letters of name,
2316
    but only matching if no '(' or '.' in second word of name,        ( \x2E = '.')
2317
    OR only one specific epithet \s+[\p{L}\x22\x2D\xD7]+$             (\x22= '"', \x2D='-', \xD7='×' )
2318
    */
2319
    $pattern = '/(^[a-zA-Z])([\p{L}]+)(\s+[^(\x2E]+\s+.+$|\s+[\p{L}\x22\x2D\xD7]+$)/u';
2320
    if (preg_match($pattern, $nameStr, $matches, PREG_OFFSET_CAPTURE)) {
2321
      return $matches[1][0] . "." . $matches[3][0];
2322
    }
2323
    else {
2324
      return $nameStr;
2325
    }
2326
  }
2327
  else {
2328
    return $taxonNodeDTO->titleCache;
2329
  }
2330
}
2331

    
2332
/**
2333
 * Check if a taxon is accepted by the current taxonomic tree.
2334
 *
2335
 * @param mixed $taxon
2336
 *   The Taxon obkect to check.
2337
 *
2338
 * @return bool
2339
 *   Returns TRUE if $taxon is accepted, FALSE otherwise.
2340
 */
2341
function _cdm_dataportal_acceptedByCurrentView($taxon) {
2342

    
2343
  $defaultTreeUuid = get_current_classification_uuid();
2344

    
2345
  if (isset($taxon->taxonNodes)) {
2346
    $taxonNodes = $taxon->taxonNodes;
2347
  }
2348
  else {
2349
    $taxonNodes = cdm_ws_get(CDM_WS_PORTAL_TAXON_TAXONNODES, $taxon->uuid);
2350
  }
2351

    
2352
  if ($taxon->class == "Taxon" && isset($taxonNodes)) {
2353
    foreach ($taxonNodes as $node) {
2354
      if (isset($node->classification)){
2355
        if(is_object($node->classification)) {
2356
          if ($node->classification->uuid == $defaultTreeUuid) {
2357
            return TRUE;
2358
          }
2359
        }
2360
        else {
2361
          if ($node->classification == $defaultTreeUuid) {
2362
            return TRUE;
2363
          }
2364
        }
2365
      }
2366
    }
2367
  }
2368

    
2369
  return FALSE;
2370
}
2371

    
2372
/**
2373
 * Checks is the source has one of the given types.
2374
 *
2375
 * @param object $source
2376
 *   The original source entity
2377
 * @param array $types
2378
 *   An array of elementd of the OriginalSourceType enumeration
2379
 *   If not set the default will be used which is:
2380
 *    - Lineage
2381
 *    - PrimaryMediaSource
2382
 *    - PrimaryTaxonomicSource
2383
 *    - Unknown
2384
 *    - Other
2385
 * @return boolean
2386
 */
2387
  function _is_original_source_type($source, $types = null) {
2388
    // this is the default
2389
    // maybe this should also be put into the settings
2390
    static $default = array(
2391
      OriginalSourceType::Lineage,
2392
      OriginalSourceType::PrimaryMediaSource,
2393
      OriginalSourceType::PrimaryTaxonomicSource,
2394
      OriginalSourceType::Unknown,
2395
      OriginalSourceType::Other,
2396
    );
2397

    
2398
    if(!$types){
2399
      $types = $default;
2400
    }
2401
    return isset($source->type) && in_array($source->type, $types);
2402
  }
2403

    
2404
/**
2405
 * @todo Please document this function.
2406
 * @see http://drupal.org/node/1354
2407
 */
2408
function _is_invers_taxonRelationship($taxonRelationship, $focusedTaxon) {
2409
  return $taxonRelationship->toTaxon->uuid == $focusedTaxon->uuid;
2410
}
2411

    
2412

    
2413
/**
2414
 * Collects all the media from a list of description elements.
2415
 *
2416
 * @param array $descriptionElements
2417
 *   The description elements from which to collect the media.
2418
 *
2419
 * @return array
2420
 *   The output with all the collected media.
2421
 */
2422
function cdm_dataportal_media_from_descriptionElements($descriptionElements) {
2423

    
2424
  $outArrayOfMedia = array();
2425

    
2426
  // Avoiding a warning box in Drupal for Flora Malesiana.
2427
  if (isset($descriptionElements) && is_array($descriptionElements)) {
2428
    foreach ($descriptionElements as $descriptionElement) {
2429
      if (isset($descriptionElement->media) && is_array($descriptionElement->media)) {
2430
        foreach ($descriptionElement->media as $media) {
2431
          if (is_object($media)) {
2432
            $outArrayOfMedia[] = $media;
2433
          }
2434
        }
2435
      }
2436
    }
2437
  }
2438
  return $outArrayOfMedia;
2439
}
2440

    
2441
/**
2442
 * @todo Please document this function.
2443
 * @see http://drupal.org/node/1354
2444
 *
2445
 * @param array $cdm_entities
2446
 *   An array of CdmBase instances or a single instance.
2447
 * @param string $footnote_list_key_suggestion
2448
 *
2449
 * @return unknown
2450
 */
2451
function cdm_annotations_as_footnotekeys($cdm_entities, $footnote_list_key_suggestion = NULL) {
2452

    
2453
   static $annotations_types_filter = null;
2454
   if(!$annotations_types_filter) {
2455
     $annotations_types_filter = unserialize(ANNOTATIONS_TYPES_AS_FOOTNOTES_DEFAULT);
2456
   }
2457

    
2458
  $footNoteKeys = array();
2459

    
2460
  // Is argument cdmBase an array?
2461
  if (!is_array($cdm_entities)) {
2462
    $cdmBase_array = array();
2463
    $cdmBase_array[] = $cdm_entities;
2464
  }
2465
  else {
2466
    $cdmBase_array = $cdm_entities;
2467
  }
2468

    
2469
  // Getting the key for the footnotemanager.
2470
  if (isset($footnote_list_key_suggestion)) {
2471
    $footnote_list_key = $footnote_list_key_suggestion;
2472
  }
2473
  else {
2474
    $footnote_list_key = RenderHints::getFootnoteListKey() . '-annotations';
2475
  }
2476

    
2477
  // Adding the footnotes keys.
2478
  foreach ($cdmBase_array as $cdmBase_element) {
2479
    $annotations = cdm_ws_getAnnotationsFor($cdmBase_element, variable_get('annotations_types_as_footnotes', $annotations_types_filter));
2480
    if (is_array($annotations)) {
2481
      foreach ($annotations as $annotation) {
2482
        $footNoteKeys[] = FootnoteManager::addNewFootnote($footnote_list_key, $annotation->text);
2483
      }
2484
    }
2485
  }
2486

    
2487
  return $footNoteKeys;
2488
}
2489

    
2490

    
2491
/**
2492
 * Creates a CDM Dynabox.
2493
 *
2494
 * @param string $dynabox_id
2495
 *   a uninque name for tha dynabox, using a cdm entity uuid as id is good practice.
2496
 * @param string $label
2497
 *   The clickable text to show.
2498
 * @param string $content_url
2499
 *   The cdm REST service request url wich will deliver the content to be shown
2500
 *   once the dynabox toggles open.
2501
 * @param string $theme
2502
 *   The theme to be used for rendering the cdm REST service response with is
2503
 *   returned from the $content_url.
2504
 * @param string $link_alt_text
2505
 *   The value for the alt attribute of the dynabox link.
2506
 * @param array $enclosingtags
2507
 *   An array with two elements: $enclosingtags[0] will be used for the dynabox
2508
 *   element itself, $enclosingtags[1] is the tag to be used for the
2509
 *   dynabox_content (optional)
2510
 * @param array $attributes
2511
 * @param $content_element_selector
2512
 *   Optional jQuery selector which can be used to reference a dom element which should
2513
 *   be used as container for the content to be shown. The dynabox-<dynabox id>-content
2514
 *  element will be placed in this container.
2515
 *
2516
 * @param string $open_callback
2517
 *   optional javascript call back function to be triggered after toggling the box to
2518
 *   the open state.
2519
 * @param string $close_callback
2520
 *   optional javascript call back function to be triggered after toggling the box to
2521
 *   the closed state.
2522
 * @return string Returns HTML for a dynabox.
2523
 * Returns HTML for a dynabox.
2524
 */
2525
function cdm_dynabox($dynabox_id, $label, $content_url, $theme, $link_alt_text,
2526
                     $enclosingtags = array('li', 'ul'), $attributes = array(),
2527
                     $content_element_selector = null,
2528
                     $open_callback = 'function(){}', $close_callback = 'function(){}' ) {
2529
  $out = '';
2530

    
2531
  // check for plain class attribute string
2532
  $dynabox_id = preg_replace('/[^a-zA-Z0-9\-]/', '', $dynabox_id);
2533

    
2534
  if(!array_key_exists('class', $attributes)) {
2535
    $attributes['class'] = array();
2536
  }
2537
  $attributes['id'][] = 'dynabox-' . $dynabox_id;
2538
  $dynabox_attributes = drupal_attributes($attributes);
2539

    
2540

    
2541
  _add_js_domEvent(); // requires domEvent.js
2542
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/cdm_dynabox.js');
2543
  drupal_add_js("
2544
  jQuery(document).ready(
2545
      function() {
2546
        dynabox('". $dynabox_id ."',
2547
          {
2548
            open_callback: " . $open_callback .",
2549
            close_callback: " . $close_callback .
2550
            ($content_element_selector ? ",\n content_container_selector: '" . $content_element_selector . "'" : "") . "
2551
          }
2552
        );
2553
      }
2554
   );",
2555
   array(
2556
    'type'=>'inline',
2557
    'scope'=>'footer'
2558
    )
2559
  );
2560

    
2561

    
2562
  $cdm_proxy_url = url('cdm_api/proxy/' . urlencode($content_url) . "/$theme");
2563
  $out .= '<!-- dynabox for ' . $content_url . ' -->';
2564
  $out .= '<' . $enclosingtags[0] . ' ' .  $dynabox_attributes. '><a href="' . $cdm_proxy_url . '" class="label" alt="' . t('@link-alt-text', array('@link-alt-text' => $link_alt_text)) . '">' . $label . '</a>';
2565
  $out .= '  <' . $enclosingtags[1] . ' id="dynabox-' . $dynabox_id . '-content">';
2566
  $out .= '    <' . $enclosingtags[0] . ' class="dynabox-content-inner">' . loading_image_html() . '</' . $enclosingtags[0] . '>';
2567
  $out .= '    </' . $enclosingtags[1] . '>';
2568
  $out .= '  </' . $enclosingtags[0] . '>';
2569
  $out .= '<!-- dynabox end -->';
2570
  return $out;
2571
}
2572

    
2573
/**
2574
 * Checks whether a feature has any description elements.
2575
 *
2576
 * @param mixed $featureNode
2577
 *   A feature node as produced by the function _mergeFeatureTreeDescriptions().
2578
 *
2579
 * @see _mergeFeatureTreeDescriptions()
2580
 *
2581
 * @return bool
2582
 *   Returns TRUE if the given $featureNode or any of its subordinate nodes
2583
 *   contains at least one non empty TextData or at least one DescriptionElement
2584
 *   of an other type. A TextData element holding a multilanguageText or a
2585
 *   source reference is considered to be not empty.
2586
 *
2587
 * @TODO this function may have become obsolete by the new method of detecting empty blocks,
2588
 *       see $block_content_is_not_empty in make_feature_block_list() and
2589
 *       $feature_block_has_content in compose_feature_block_items_generic
2590
 */
2591
function has_feature_node_description_elements($featureNode) {
2592

    
2593
  if (isset($featureNode->descriptionElements) && is_array($featureNode->descriptionElements) && count($featureNode->descriptionElements) > 0) {
2594
    if(!isset($featureNode->descriptionElements['#type'])){ // #type is used to identify e.g. DTO elements: '#type' => 'DTO'
2595
      foreach ($featureNode->descriptionElements as $descriptionElement) {
2596
        if ($descriptionElement->class != "TextData" || isset($descriptionElement->multilanguageText_L10n->text)
2597
          && $descriptionElement->multilanguageText_L10n->text != ''
2598
          || isset($descriptionElement->sources[0])
2599
          || isset($descriptionElement->media[0]) ) {
2600
          return TRUE;
2601
        }
2602
      }
2603
    }
2604
  }
2605
  else if (isset($featureNode->childNodes) && is_array($featureNode->childNodes)) {
2606
    foreach ($featureNode->childNodes as $child) {
2607
      if (has_feature_node_description_elements($child)) {
2608
        return TRUE;
2609
      }
2610
    }
2611
  }
2612
  return FALSE;
2613
}
2614

    
2615
/**
2616
 * Checks if the current page is a valid taxon portal page and responds with HTTP status 404 (not found) otherwise
2617
 *
2618
 * @param $chapter
2619
 *   The taxon page chapter or part
2620
 */
2621
function cdm_check_valid_taxon_page($chapter){
2622
  static $taxon_tabs = null;
2623

    
2624
  cdm_check_valid_portal_page();
2625

    
2626
  if($taxon_tabs == null){
2627
    $taxon_tabs = array('all', 'description');
2628
    foreach(get_taxon_tabs_list() as $tab){
2629
      $taxon_tabs[] = strtolower($tab);
2630
    }
2631
  }
2632

    
2633
  if(!in_array($chapter, $taxon_tabs)){
2634
    // oops this is not a valid chapter name
2635
    http_response_code(404); // 404 = Not Found
2636
  }
2637

    
2638
}
2639

    
2640
/**
2641
 * Checks if the current page is a valid portal page and responds with HTTP status 404 (not found) otherwise.
2642
 * The test applied by default it a check for the query parameter 'q' ending with a file suffix like '*.*'
2643
 *
2644
 * @param $preg_pattern
2645
 *   Optional regular expression pattern to be used in preg_match().
2646
 */
2647
function cdm_check_valid_portal_page($preg_pattern = null){
2648
  $ends_with_file_suffix_pattern = '/\/[^\.\/]*[\.][^\.\/]*$/';
2649
  if($preg_pattern === null){
2650
    $preg_pattern = $ends_with_file_suffix_pattern;
2651
  }
2652
  if(preg_match($preg_pattern, $_GET['q'])){
2653
    // oops this urls ends with a file_suffix and thus does not refer to a portal page
2654
    http_response_code(404); // 404 = Not Found
2655
    exit('HTTP 404');
2656
  }
2657
}
2658

    
2659
/**
2660
 * Generates the diff of the texts and presents it in a HTML diff viewer.
2661
 *
2662
 * @param $text_a
2663
 * @param $text_b
2664
 * @return string
2665
 */
2666
function diff_viewer($text_a, $text_b) {
2667

    
2668
  static $diff_viewer_count = 0;
2669

    
2670
  $element_id = 'part_definitions_diff_' . $diff_viewer_count++;
2671

    
2672
  // http://code.stephenmorley.org/php/diff-implementation/
2673
  module_load_include('php', 'cdm_dataportal', 'lib/class.Diff');
2674
  drupal_add_css(drupal_get_path('module',
2675
      'cdm_dataportal') . '/css/diff.css');
2676
  _add_jquery_ui();
2677
  drupal_add_js(
2678
    'jQuery(document).ready( function(){
2679
        jQuery(\'#' . $element_id . '\').accordion({
2680
        collapsible: true,
2681
        active: false,
2682
        fillSpace: true,
2683
        }).children(\'div\').css({ \'height\': \'auto\' });
2684
        jQuery(\'#' . $element_id . ' table.diff\').prepend(\'<thead><tr><th>Default</th><th>User defined<th></th><tr></thead>\');
2685
     });'
2686
    , array(
2687
    'type' => 'inline',
2688
    'scope' => 'footer'
2689
  ));
2690

    
2691
  $diff = Diff::compare($text_a,
2692
    $text_b);
2693
  $diff_viewer_markup = '<div id="' . $element_id . '"><h3>View Diff</h3><div>'
2694
    . Diff::toTable($diff, '', '')
2695
    . '</div></div>';
2696
  return $diff_viewer_markup;
2697
}
2698

    
2699

    
(10-10/18)