Project

General

Profile

Download (77 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_openlayers() {
127

    
128
    $openlayers = '/js/map/OpenLayers-2.13.1/OpenLayers.js';
129
    $proj4js = '/js/map/proj4js-1.1.0/proj4js-compressed.js';
130

    
131
    if(variable_get('cdm_js_devel_mode', FALSE)){
132
      // develooper mode libs
133
  //     $openlayers = '/js/map/OpenLayers-2.13.1/lib/OpenLayers.js';
134
      $openlayers = '/js/map/OpenLayers-2.13.1/OpenLayers.debug.js';
135
      $proj4js = '/js/map/proj4js-1.1.0/proj4js-combined.js';
136
    }
137

    
138
    drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $openlayers,
139
      array(
140
        'type' => 'file',
141
        'weight' => JS_LIBRARY,
142
        'cache' => TRUE,
143
        'preprocess' => FALSE
144
      )
145
    );
146

    
147
    // see https://github.com/proj4js/proj4js
148
    // http://openlayers.org/dev/examples/using-proj4js.html
149
    drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $proj4js,
150
      array(
151
        'type' => 'file',
152
        'weight' => JS_LIBRARY,
153
        'cache' => TRUE,
154
      )
155
    );
156

    
157
    // configure the theme
158
    $openlayers_theme_path = drupal_get_path('module', 'cdm_dataportal') . '/js/map/OpenLayers-2.13.1/theme/default/';
159
    $openlayers_imp_path = drupal_get_path('module', 'cdm_dataportal') . '/js/map/img/dark/';
160
    drupal_add_js('OpenLayers.ImgPath="' . base_path() . $openlayers_imp_path . '";', array(
161
        'type' => 'inline',
162
        'weight' => JS_LIBRARY,
163
        'cache' => TRUE,
164
        'preprocess' => FALSE
165
      ));
166

    
167
    drupal_add_css($openlayers_theme_path . 'style.tidy.css',
168
      array(
169
        'type' => 'file',
170
        'cache' => TRUE,
171
        'preprocess' => FALSE
172
      )
173
    );
174

    
175
  }
176

    
177
  /**
178
   * @todo Please document this function.
179
   * @see http://drupal.org/node/1354
180
   */
181
  function _add_js_thickbox() {
182
    // ---- jQuery thickbox:
183
    /*
184
    * bug: compat-1.0.js && thickbox.js line 237 .trigger("unload") -> event is
185
    * not triggered because of problems with compat-1.0.js' see INSTALL.txt
186
    */
187
    // drupal_add_js(drupal_get_path('module',
188
    // 'cdm_dataportal').'/js/jquery.imagetool.min.js');
189
    //
190
    // Add a setting for the path to cdm_dataportal module, used to find the path
191
    // for the loading animation image in thickbox.
192
    drupal_add_js(array(
193
    'cdm_dataportal' => array(
194
    'cdm_dataportal_path' => base_path() . drupal_get_path('module', 'cdm_dataportal'),
195
    )
196
    ),
197
    'setting'
198
        );
199
        drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/thickbox/thickbox.js');
200
        drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/thickbox/cdm_thickbox.css');
201
  }
202

    
203
  /**
204
   * @todo Please document this function.
205
   * @see http://drupal.org/node/1354
206
   */
207
  function _add_js_lightbox($galleryID) {
208
    /*
209
     * Important Notice: The jquery.lightbox-0.5.js has been modified in order to
210
    * allow using the "alt" attribute for captions instead of the "title"
211
    * attribute
212
    */
213
    $lightbox_base_path =  drupal_get_path('module', 'cdm_dataportal') . '/js/jquery-lightbox-0.5';
214
    $lightbox_image_path = base_path() . $lightbox_base_path . '/images/';
215
    drupal_add_js($lightbox_base_path . '/js/jquery.lightbox-0.5.js');
216
    drupal_add_css($lightbox_base_path . '/css/jquery.lightbox-0.5.css');
217
    drupal_add_js('jQuery(document).ready(function() {
218
        jQuery(\'#' . $galleryID . ' a.lightbox\').lightBox({
219
          fixedNavigation:  true,
220
          imageLoading:     \'' . $lightbox_image_path . 'lightbox-ico-loading.gif\',
221
          imageBtnPrev:     \'' . $lightbox_image_path . 'lightbox-btn-prev.gif\',
222
          imageBtnNext:     \'' . $lightbox_image_path . 'lightbox-btn-next.gif\',
223
          imageBtnClose:    \'' . $lightbox_image_path . 'lightbox-btn-close.gif\',
224
          imageBlank:       \'' . $lightbox_image_path . 'lightbox-blank.gif\',
225
          adjustToWindow: true
226
        });
227
      });
228
      ', array('type' => 'inline'));
229
  }
230

    
231
  /**
232
   * @todo Please document this function.
233
   * @see http://drupal.org/node/1354
234
   */
235
  function _add_js_footnotes() {
236
    _add_js_domEvent();
237
    drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/footnotes.js');
238
  }
239

    
240
  /**
241
   * @todo Please document this function.
242
   * @see http://drupal.org/node/1354
243
   */
244
  function _add_js_cluetip() {
245

    
246
    // TODO replace by
247
    // @see http://www.socialembedded.com/labs/jQuery-Tooltip-Plugin/jQuery-Tooltip-Plugin.html
248
    drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/cluetip/jquery.cluetip.min.js');
249
    drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/jquery.dimensions.js');
250
    drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/cluetip/jquery.hoverIntent.js');
251
    if(variable_get('cdm_js_devel_mode', FALSE)){
252
      drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/cluetip/jquery.cluetip.js');
253
    }
254
    drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/cluetip/jquery.cluetip.css');
255
    drupal_add_js("jQuery(document).ready(function(){
256
        jQuery('.cluetip').css({color: '#0062C2'}).cluetip({
257
          splitTitle: '|',
258
          showTitle: true,
259
          activation: 'hover',
260
          sicky: true,
261
          arrows: true,
262
          dropShadow: false,
263
          cluetipClass: 'rounded'
264
        });
265
      });",
266
      array(
267
        'type' => 'inline',
268
        'scope' => 'footer'
269
      )
270
    );
271
  }
272

    
273
  /**
274
   * @todo Please document this function.
275
   * @see http://drupal.org/node/1354
276
   */
277
  function _add_js_ahah() {
278

    
279
    _add_js_domEvent(); // requires domEvent.js
280
    drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/ahah-content.js');
281
  }
282

    
283
/**
284
 * @todo Please document this function.
285
 * @see http://drupal.org/node/1354
286
 */
287
function _add_js_taxonomic_children($jquery_selector) {
288

    
289
  global $base_url;
290

    
291

    
292
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/jquery.cdm.taxonomic_children.js');
293
  
294
  drupal_add_js('jQuery(document).ready(function() {
295
        jQuery(\'' . $jquery_selector . '\').taxonomic_children({
296
          hoverClass: "fa-rotate-90",
297
          activeClass: "fa-rotate-90",
298
          classificationUuid: "' . get_current_classification_uuid() . '",
299
          cdmWebappBaseUri: "' . variable_get('cdm_webservice_url', '') . '",
300
          proxyBaseUri: "' . $base_url . '",
301
          
302
        });
303
      });
304
      ', array('type' => 'inline'));
305
}
306

    
307
  /**
308
   * Adds the external javascript file for domEvent.js.
309
   *
310
   * @see drupal_add_js()
311
   */
312
  function _add_js_domEvent() {
313
    drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/domEvent.js');
314
  }
315

    
316
  function _add_jquery_ui()
317
  {
318
    drupal_add_css(drupal_get_path('module',
319
        'cdm_dataportal') . '/js/jquery-ui-1.8.24/themes/base/jquery.ui.all.css');
320
    drupal_add_js(drupal_get_path('module',
321
        'cdm_dataportal') . '/js/jquery-ui-1.8.24/ui/jquery-ui.js',
322
      array(
323
        'type' => 'file',
324
        'weight' => JS_LIBRARY,
325
        'cache' => TRUE,
326
        'preprocess' => FALSE
327
      )
328
    );
329
  }
330

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

    
350

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

    
353
    $font_awesome_css_uri=drupal_get_path('module', 'cdm_dataportal').'/font-awesome/4.5.0/css/font-awesome.min.css';
354
    $font_awesome_css_uri="//maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css";
355

    
356
    drupal_add_html_head_link(
357
      array(
358
        'href' => $font_awesome_css_uri,
359
        'rel' => 'stylesheet'
360
      )
361
    );
362

    
363
    if($icon_name){
364
      if(!isset($attributes['class'])){
365
        $attributes['class'] = array();
366
      }
367
      $attributes['class'][] = 'fa';
368
      $attributes['class'][] = $icon_name;
369

    
370
      return '<i ' . drupal_attributes($attributes) . '></i>';
371
    }
372

    
373
    return '';
374
  }
375

    
376

    
377
  /* ====================== hook implementations ====================== */
378
  /**
379
   * Implements hook_permission().
380
   *
381
   * Valid permissions for this module.
382
   *
383
   * @return array
384
   *   An array of valid permissions for the portfolio module.
385
   */
386
  function cdm_dataportal_permission() {
387
    return array(
388
      'administer cdm_dataportal' => array(
389
        'title' => t('administer cdm_dataportal'),
390
        'description' => t("TODO Add a description for 'administer cdm_dataportal'"),
391
      ),
392
      'cdm_dataportal view notes' => array(
393
        'title' => t('cdm_dataportal view notes'),
394
        'description' => t("TODO Add a description for 'cdm_dataportal view notes'"),
395
      ),
396
      // TODO Which other permissions are required?
397
      // -> check the WP6 requirements document.
398
    );
399
  }
400

    
401
/**
402
 * Implements hook_menu().
403
 */
404
function cdm_dataportal_menu() {
405
  $items = array();
406

    
407
  // @see settings.php.
408
  cdm_dataportal_menu_admin($items);
409
  cdm_dataportal_menu_help($items);
410

    
411
  $items['cdm_dataportal/names'] = array(
412
    'page callback' => 'cdm_dataportal_view_names',
413
    'access arguments' => array('access content'),
414
    'type' => MENU_CALLBACK,
415
  );
416

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

    
425
   // Optional callback arguments: page.
426
    //FIXME point to view/page method in this module
427
    $items['cdm_dataportal/specimen'] = array(
428
        'page callback' => 'cdm_dataportal_specimen_page_view',
429
        'access arguments' => array('access content'),
430
        'type' => MENU_CALLBACK,
431
        // Expected callback arguments: uuid.
432
    );
433

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

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

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

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

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

    
477
  $items['cdm_dataportal/search'] = array(
478
    'page callback' => 'cdm_dataportal_view_search_advanced',
479
    'access arguments' => array('access content'),
480
    'type' => MENU_CALLBACK,
481
  );
482

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

    
490
  $items['cdm_dataportal/search/taxon_by_description'] = array(
491
    'title' => 'By factual data', // will be passed through t()
492
    'page callback' => 'cdm_dataportal_view_search_taxon_by_description',
493
    'access arguments' => array('access content'),
494
    'type' => MENU_LOCAL_TASK,
495
  );
496

    
497
  $items['cdm_dataportal/search/results/taxon'] = array(
498
    'page callback' => 'cdm_dataportal_view_search_results_taxon',
499
    'access arguments' => array('access content'),
500
    'type' => MENU_CALLBACK,
501
  );
502
  /*
503
   $items['cdm/xml2json'] = array(
504
   'page callback' => 'cdm_view_xml2json',
505
   'access arguments' => array('access content'),
506
   'type' => MENU_CALLBACK,
507
   );
508
   */
509

    
510
  // if (arg(0)=='user' && ($uid=arg(1)) && is_numeric($uid)) {
511
  // User configuration of cdm_dataportal.
512
  $items['user/%/cdm_dataportal'] = array(
513
    'title' => 'cdm_dataportal',
514
    'access arguments' => array('access content'),
515
    'page callback' => 'drupal_get_form',
516
    'page arguments' => array('cdm_dataportal_user_form'),
517
    'type' => MENU_LOCAL_TASK,
518
    'weight' => 10,
519
  );
520
  // }
521

    
522
  // 'May not cache' in D5.
523
  $items['cdm_dataportal/name/%'] = array(
524
    // 'page callback' => 'cdm_dataportal_view_name',
525
    'page callback' => 'cdm_dataportal_name_page_view',
526
    'page arguments' => array(2, 3, 4),
527
    'access arguments' => array('access content'),
528
    'type' => MENU_CALLBACK,
529
  );
530

    
531
  // --- Local tasks for Taxon.
532
  // --- tabbed taxon page
533
  if (variable_get('cdm_dataportal_taxonpage_tabs', 1)) {
534
    $items['cdm_dataportal/taxon/%'] = array(
535
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'General')),
536
      'page callback' => 'cdm_dataportal_taxon_page_view',
537
      'access arguments' => array('access content'),
538
      'type' => MENU_CALLBACK,
539
      'weight' => 1,
540
      'page arguments' => array(2, "description")
541
      , // Expected callback arguments: taxon_uuid.
542
    );
543

    
544
    $items['cdm_dataportal/taxon/%/all'] = array(
545
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'General')),
546
      'page callback' => 'cdm_dataportal_taxon_page_view',
547
      'access arguments' => array('access content'),
548
      'type' => MENU_CALLBACK,
549
      'weight' => 2,
550
      'page arguments' => array(2, "all")
551
      , // Expected callback arguments: taxon_uuid.
552
    );
553

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

    
564
    $items['cdm_dataportal/taxon/%/synonymy'] = array(
565
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'Synonymy')),
566
      'page callback' => 'cdm_dataportal_taxon_page_view',
567
      'access arguments' => array('access content'),
568
      'type' => MENU_LOCAL_TASK,
569
      'weight' => 4,
570
      'page arguments' => array(2, "synonymy", 4)
571
      , // Expected callback arguments: taxon_uuid and ...
572
    );
573
    $items['cdm_dataportal/taxon/%/images'] = array(
574
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'Images')),
575
      'page callback' => 'cdm_dataportal_taxon_page_view',
576
      'access arguments' => array('access content'),
577
      'type' => MENU_LOCAL_TASK,
578
      'weight' => 5,
579
      'page arguments' => array(2, "images")
580
      , // Expected callback arguments: taxon_uuid.
581
    );
582

    
583
    $items['cdm_dataportal/taxon/%/specimens'] = array(
584
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'Specimens')),
585
      'page callback' => 'cdm_dataportal_taxon_page_view',
586
      'access arguments' => array('access content'),
587
      'type' => MENU_LOCAL_TASK,
588
      'weight' => 6,
589
      'page arguments' => array(2, "specimens")
590
      , // Expected callback arguments: taxon_uuid.
591
    );
592

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

    
603
    $items['cdm_dataportal/taxon/%/experts'] = array(
604
        'title' => theme('cdm_taxonpage_tab', array('tabname' => 'Experts')),
605
        'page callback' => 'cdm_dataportal_taxon_page_view',
606
        'access arguments' => array('access content'),
607
        'type' => MENU_LOCAL_TASK,
608
        'weight' => 6,
609
        'page arguments' => array(2, "experts")
610
    , // Expected callback arguments: taxon_uuid.
611
    );
612
  }
613

    
614
  // --- refresh link for all cdmnode types
615
  foreach (cdm_get_nodetypes() as $type=>$name) {
616
    $items['cdm_dataportal/' . $name . '/%/refresh'] = array(
617
        'title' => t('Refresh'),
618
        'page callback' => 'cdm_dataportal_refresh_node',
619
        'access arguments' => array('administer cdm_dataportal'),
620
        'type' => MENU_LOCAL_TASK,
621
        'weight' => 100,
622
        'page arguments' => array($name, 2)
623
    );
624
  }
625

    
626
  return $items;
627
}
628

    
629
/**
630
 * Implements hook_init().
631
 *
632
 */
633
function cdm_dataportal_init() {
634
  //FIXME To add CSS or JS that should be present on all pages, modules
635
  //      should not implement this hook, but declare these files in their .info file.
636
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/cdm_dataportal.css');
637
  // drupal_add_css(drupal_get_path('module', 'cdm_dataportal').'/cdm_dataportal_print.css', 'print');
638
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/cdm_dataportal_screen.css', array('type' => 'screen'));
639

    
640
  if(variable_get('cdm_debug_mode', FALSE)){
641
    $file = 'temporary://drupal_debug.txt';
642
    file_put_contents($file, 'CDM DEBUG LOG for ' . $_GET['q']. "\n"); // will overwrite the file
643
  }
644

    
645
  $bibliography_settings = get_bibliography_settings();
646
  $enclosing_tag = $bibliography_settings['enabled'] == 1 ? 'div' : 'span';
647
  FootnoteManager::registerFootnoteSet('BIBLIOGRAPHY', $enclosing_tag, $bibliography_settings['key_format']);
648
}
649

    
650
function cdm_dataportal_refresh_node($cdm_node_name, $uuid, $parameters = array()){
651

    
652
  $base_path = 'cdm_dataportal/' . $cdm_node_name . '/' . $uuid;
653

    
654
  if($cdm_node_name == 'taxon' && variable_get('cdm_dataportal_taxonpage_tabs', 1)){
655
    // force reloading of all and notify user about this special loading
656
    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: ')
657
        . l('Back to tabbed taxon page', $base_path));
658
    $base_path .= '/all';
659
  } else {
660
    drupal_set_message(t('The level 2 cache has been cleared for this page'));
661
  }
662

    
663
  $parameters['cacheL2_refresh'] ='1';
664

    
665

    
666
  drupal_goto($base_path, array('query' => $parameters));
667
}
668

    
669
/**
670
 * The function generate form for own user cdm dataportal configurations.
671
 */
672
function cdm_dataportal_user_form($form, &$form_state) {
673

    
674
  global $user;
675
  $checkbox_value = 'cdm_dataportal_' . $user->uid . '_default_tab_active';
676

    
677
  $form['taxon_page_tabs'] = array(
678
      '#type' => 'fieldset',
679
      '#tree' => true,
680
      '#title' => t('Taxon page tabs'),
681
  );
682

    
683
  $form['taxon_page_tabs']['user_defined'] = array(
684
    '#type' => 'checkbox',
685
    '#title' => t('Activate user default configuration'),
686
    '#default_value' => variable_get($checkbox_value, 0),
687
    '#description' => t('Check this if you want configure your own default tab from the below menu.'),
688
  );
689

    
690
  $form['taxon_page_tabs']['default_tab'] = array(
691
    '#type' => 'select',
692
    '#title' => t('Default tab to display'),
693
    '#default_value' => get_default_taxon_tab(TRUE),
694
    '#options' => unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB),
695
    '#description' => t('<p>Select the default tab to display when visiting a taxon page. Only available if Tabbed Taxon Page is enable.</p>
696
              <strong>Note:</strong> After performing a search and clicking in any synonym, the taxon tab
697
              to be rendered will be the synonymy of the accepted taxon and not the above selected tab.'),
698
  );
699

    
700

    
701
  if(false){
702
    $form['developer_options'] = array(
703
        '#type' => 'fieldset',
704
        '#tree' => true,
705
        '#title' => t('Developer options'),
706
    );
707

    
708
    $form['developer_options']['show_render_path'] = array(
709
      '#type' => 'checkbox',
710
      '#title' => t('Display the render path for each taxon name.'),
711
      '#default_value' => variable_get($checkbox_value, 0),
712
      '#description' => t('This option is very helpful if you are editing the !link for taxon names.',
713
        array(
714
            '!link' => l(
715
              'render template', 'admin/config/cdm_dataportal/settings/layout', array('fragment' => 'edit-cdm-name-render-templates'))
716
            )
717
        ),
718
    );
719
  }
720

    
721
  $form['submit'] = array(
722
    '#type' => 'submit',
723
    '#value' => t('Submit'),
724
  );
725

    
726
  return $form;
727
}
728

    
729
/**
730
 * Form submission handler for user_form().
731
 *
732
 * Submits the user cdm dataportal configurations.
733
 */
734
function cdm_dataportal_user_form_submit($form, &$form_state) {
735
  global $user;
736
  $msg_type = 'status';
737
  $username = $user->name;
738
  $variable_to_use = 'cdm_dataportal_' . $user->uid . '_default_tab';
739

    
740
  // FIXME: this is completely wrong, see user_profile_form_submit()
741

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

    
745
    // DEFAULT_TAXON_TAB
746
    $variable = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
747
    variable_set($variable_to_use . '_active', $form_state['values']['taxon_page_tabs']['user_defined']);
748
    variable_set($variable_to_use, $form_state['values']['taxon_page_tabs']['default_tab']);
749
    if ($form_state['values']['taxon_page_tabs']['user_defined']) {
750
      drupal_set_message(check_plain(t('The user default tab will be used for the next taxon site visit.')));
751
      drupal_set_message(check_plain(t('The user default tab has been changed to: !tab for the user !user', array(
752
        '!tab' => $variable[variable_get($variable_to_use, 0)],
753
        '!user' => $username,
754
      ))), $msg_type);
755
    }
756
    else {
757
      drupal_set_message(check_plain(t('The user default tab wont be used for
758
        the next taxon site, check the box if you want to use the user default configuration.')));
759
    }
760

    
761
  }
762
  else {
763
    // Problem with the user id => variables wont be saved.
764
    $msg_type = 'warning';
765
    drupal_set_message(check_plain(t('Default tab has not been saved due to user id problems')), $msg_type);
766
  }
767
}
768

    
769
/**
770
 * Implements hook_block_info().
771
 */
772
function cdm_dataportal_block_info() {
773

    
774
    // $block[0]["info"] = t("CDM DataPortal DevLinks");
775
    // $block[1]["info"] = t("CDM DataPortal Credits");
776
    $block["2"] = array(
777
        "info" => t("CDM Search Taxa"),
778
        "cache" => DRUPAL_NO_CACHE
779
      );
780
    // $block[3]["info"] = t("CDM Filters");
781
    $block["4"]["info"] = t("CDM Dataportal Print");
782
    $block["keys"]["info"] = t("CDM identification keys");
783
    $block["fundedByEDIT"]["info"] = t('Funded by EDIT');
784
    $block["classification_breadcrumbs"] =  array(
785
        'info' => t('Classification breadcrumbs'),
786
        'cache' => DRUPAL_CACHE_PER_PAGE
787
      );
788

    
789
    return $block;
790
}
791

    
792
/**
793
 * Implements hook_block_view().
794
 */
795
function cdm_dataportal_block_view($delta) {
796
  // TODO Rename block deltas (e.g. '2') to readable strings.
797
  switch ($delta) {
798
    // case 'delta-1':
799
    // $block['subject'] = t('Credits');
800
    // $block['content'] = theme('cdm_credits');
801
    // return $block;
802
    case '2':
803
      $block['subject'] = t('Search taxa');
804
      $form = drupal_get_form('cdm_dataportal_search_taxon_form');
805
      $block['content'] = drupal_render($form);
806

    
807
      if (variable_get('cdm_dataportal_show_advanced_search', 1)) {
808
        $block['content'] .= '<div>' . l(t('Advanced Search'), 'cdm_dataportal/search') . '</div>';
809
      }
810
      return $block;
811
    case '4':
812
      $block['subject'] = '';
813
      $block['content'] = theme('cdm_print_button');
814
      return $block;
815
    case "keys":
816
      $block['subject'] = t('Identification Keys');
817
      $block['content'] = theme('cdm_block_IdentificationKeys', array('taxonUuid' => NULL));
818
      return $block;
819
    case "fundedByEDIT":
820
      // t('Funded by EDIT');
821
      $text = '<none>';
822
      $block['subject'] = $text;
823
      $img_tag = '<img src="' . base_path() . drupal_get_path('module', 'cdm_dataportal') . '/images/powered_by_edit.png' . '" alt="' . $text . '"/>';
824
      $block['content'] = l($img_tag, "http://cybertaxonomy.org/", array(
825
        'attributes' => array("target" => "EDIT"),
826
        'absolute' => TRUE,
827
        'html' => TRUE,
828
      ));
829
      return $block;
830
    case 'classification_breadcrumbs':
831
      $taxon_uuid = null;
832
      if (arg(1) == 'taxon' && is_uuid(arg(2))) {
833
        $taxon_uuid = arg(2);
834
      }
835
      $block['subject'] = '<none>';
836
      $block['content'] = compose_classification_breadcrumbs($taxon_uuid);
837
      return $block;
838
    
839
  }
840
}
841

    
842
/*
843
 function cdm_dataportal_session_clear($cdm_ws_uri_update = FALSE){
844
 $_SESSION['cdm'] = NULL;
845
 if(is_string($cdm_ws_uri_update)){
846
 $_SESSION['cdm'] = array('ws_uri'=>$cdm_ws_uri_update);
847
 }
848
 }
849

    
850
 function cdm_dataportal_session_validate(){
851
 if(!isset($_SESSION['cdm']['ws_uri'])){
852
 $_SESSION['cdm'] = array('ws_uri'=>variable_get('cdm_webservice_url', FALSE));
853
 } else if($_SESSION['cdm']['ws_uri'] != variable_get('cdm_webservice_url', FALSE)){
854
 cdm_dataportal_session_clear(variable_get('cdm_webservice_url', FALSE));
855
 }
856
 }
857
 */
858

    
859
/**
860
 * creates a  selector form for taxonomic trees.
861
 *
862
 * @return a drupal form array
863
 */
864
function cdm_taxonomictree_selector() {
865
  _add_js_treeselector();
866

    
867
  $form = drupal_get_form('cdm_taxonomictree_selector_form');
868
  return $form;
869
}
870

    
871
/**
872
 * @todo Please document this function.
873
 * @see http://drupal.org/node/1354
874
 */
875
function cdm_taxonomictree_selector_form($form, &$form_state) {
876

    
877
  $url = url('cdm_api/setvalue/session', array('query' => NULL));
878
  $form['#action'] = $url;
879

    
880
  $form['var'] = array(
881
    '#weight' => -3,
882
    '#type' => 'hidden',
883
    '#value' => '[cdm][taxonomictree_uuid]',
884
  );
885

    
886
  $destination_array = drupal_get_destination();
887
  $destination = $destination_array['destination'];
888

    
889
  $form['destination'] = array(
890
    '#weight' => -3,
891
    '#type' => 'hidden',
892
    '#value' =>  $destination,
893
  );
894

    
895
  $options = cdm_get_taxontrees_as_options();
896
  $taxontree_includes = variable_get(CDM_TAXONTREE_INCLUDES, null);
897
  if($taxontree_includes){
898
    $filtered_options = array();
899
    foreach($options as $uuid=>$label){
900
      if(!empty($taxontree_includes[$uuid])){
901
        $filtered_options[$uuid] = $label;
902
      }
903
    }
904
    $options = $filtered_options;
905
  }
906

    
907
  $form['val'] = array(
908
    '#type' => 'select',
909
    '#title' => t('Available classifications'),
910
    '#default_value' => get_current_classification_uuid(),
911
    '#options' => $options,
912
    '#attributes' => array('class' => array('highlite-first-child'))
913
  );
914

    
915
  return $form;
916

    
917
}
918

    
919
/* UNREACHABLE since action of form directly links to view.
920
 function cdm_dataportal_search_taxon_form_submit($form_id, $form_values) {
921

    
922
 $_SESSION['cdm']['search'] = $form_values;
923
 //return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['vernacular']?'1':'0').'/'.$form_values['language'];
924
 return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['onlyAccepted']?'1':'0');
925
 //$paramstr = compose_url_prameterstr($form_values);
926
 //return url('/cdm_dataportal/search/taxon/', array('query' => $paramstr));
927
 }
928
 */
929
/* ====================== menu callback functions ====================== */
930
/**
931
 * @todo Please document this function.
932
 * @see http://drupal.org/node/1354
933
 */
934
/*
935
function cdm_dataportal_form_alter(&$form, &$form_state, $form_id) {
936
  static $comment_node_disabled =  0;
937
  static $comment_node_read_only =  1;
938
  static $comment_node_read_write =  2;
939

    
940
  if ($form_id == 'node_type_form'
941
   && isset($form['identity']['type'])
942
   && array_key_exists($form['#node_type']->type, cdm_get_nodetypes())
943
  ) {
944
    $form['workflow']['comment'] = array(
945
      '#type' => 'radios',
946
      '#title' => t('Default comment setting'),
947
      '#default_value' => variable_get('comment__' . $node->type . $form['#node_type']->type, $comment_node_disabled),
948
      '#options' => array(t('Disabled'), t('Read only'), t('Read/Write')),
949
      '#description' => t('Users with the <em>administer comments</em> permission will be able to override this setting.'),
950
    );
951
  }
952
}
953
*/
954

    
955
/**
956
 * Displays a list of the known taxonomic names.
957
 *
958
 * When the list of taxonomic names is displayed, long lists are split up into
959
 * multiple pages.
960
 *
961
 * TODO: Parameters are still preliminary.
962
 *
963
 * @param string $beginsWith
964
 * @param string $page
965
 *   Page number to diplay defaults to page 1.
966
 * @param bool $onlyAccepted
967
 */
968
function cdm_dataportal_view_names($beginsWith = 'A', $page = 1, $onlyAccepted = FALSE) {
969

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

    
972
  /*
973
  // FIXME the filter for accepted names will be a form element, thus this
974
  // widget should be generated via form api preferably as block.
975
  $out  = theme('cdm_dataportal_widget_filter_accepted', $onlyAccepted);
976
  $out .= theme('cdm_dataportal_widget_names_list', $names, $page);
977
  $out .= theme('cdm_listof_taxa', $taxonPager);
978
  return $out;
979
  */
980
}
981

    
982
/**
983
 * @todo Please document this function.
984
 * @see http://drupal.org/node/1354
985
 */
986
function cdm_dataportal_view_reference($uuid, $arg2 = NULL) {
987

    
988
  cdm_check_valid_portal_page();
989

    
990
  $reference = cdm_ws_get(CDM_WS_REFERENCE, $uuid);
991
  return theme('cdm_reference_page', array('reference' => $reference));
992
}
993

    
994
/**
995
 * Creates a view on a all references contained in the portal.
996
 *
997
 * This function is used at the path cdm_dataportal/reference/list
998
 */
999
function cdm_dataportal_view_reference_list($pageNumber) {
1000
  $referencePager = cdm_ws_page(CDM_WS_REFERENCE, variable_get('cdm_dataportal_search_items_on_page', CDM_DATAPORTAL_SEARCH_ITEMS_ON_PAGE), $pageNumber);
1001
  cdm_reference_pager($referencePager, 'cdm_dataportal/reference/list/');
1002
}
1003

    
1004
/**
1005
 * @todo Please document this function.
1006
 * @see http://drupal.org/node/1354
1007
 */
1008
function cdm_dataportal_view_media($mediaUuid, $mediarepresentation_uuid = FALSE, $part = 0) {
1009

    
1010
  cdm_check_valid_portal_page();
1011

    
1012
  $media = cdm_ws_get(CDM_WS_PORTAL_MEDIA, $mediaUuid);
1013
  return theme('cdm_media_page', array(
1014
    'media' => $media,
1015
    'mediarepresentation_uuid' => $mediarepresentation_uuid,
1016
    'partId' => $part,
1017
    ));
1018
}
1019

    
1020
/**
1021
 * @todo Please document this function.
1022
 * @see http://drupal.org/node/1354
1023
 */
1024
function _load_taxonBase(&$taxonBase) {
1025
  if (isset($taxonBase->uuid)) {
1026
    $taxonBase->name = cdm_ws_get(CDM_WS_TAXON, array($taxonBase->uuid, "name"));
1027
    $taxonBase->name->taggedName = cdm_ws_get(CDM_WS_NAME, array($taxonBase->name->uuid, "taggedName"));
1028
    $taxonBase->name->nomenclaturalReference = cdm_ws_get(CDM_WS_NAME, array($taxonBase->name->uuid, "nomenclaturalReference"));
1029
  }
1030
}
1031

    
1032
/**
1033
 * Loads the media associated to the given taxon from the cdm server.
1034
 * The aggregation settings regarding taxon relathionships and
1035
 * taxonnomic childen are taken into account.
1036
 *
1037
 * The media lists are cached in a static variable.
1038
 *
1039
 * @param Taxon $taxon
1040
 *   A CDM Taxon entitiy
1041
 *
1042
 * @return array
1043
 *   An array of CDM Media entities
1044
 *
1045
 */
1046
function _load_media_for_taxon($taxon) {
1047

    
1048
  static $media = NULL;
1049

    
1050
  if(!isset($media)) {
1051
    $media = array();
1052
  }
1053
  if (!isset($media[$taxon->uuid])) {
1054

    
1055
    // --- GET Images --- //
1056
    $mediaQueryParameters = array(
1057
        "type" => "ImageFile",
1058
    );
1059

    
1060
    $relationship_choice = variable_get(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS, unserialize(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS_DEFAULT));
1061
    $mediaQueryParameters['relationships'] = implode(',', get_selection($relationship_choice['direct']));
1062
    $mediaQueryParameters['relationshipsInvers'] = implode(',', get_selection($relationship_choice['invers']));
1063

    
1064
    $taxon_media_filter_choice = variable_get(CDM_TAXON_MEDIA_FILTER, unserialize(CDM_TAXON_MEDIA_FILTER_DEFAULT));
1065
    $mediaQueryParameters['includeTaxonDescriptions'] = (boolean) $taxon_media_filter_choice['includeTaxonDescriptions'] != 0;
1066
    $mediaQueryParameters['includeOccurrences'] = (boolean) $taxon_media_filter_choice['includeOccurrences'] != 0;
1067
    $mediaQueryParameters['includeTaxonNameDescriptions'] = (boolean) $taxon_media_filter_choice['includeTaxonNameDescriptions'] != 0;
1068

    
1069
    $ws_endpoint = NULL;
1070
    if ( variable_get('cdm_images_include_children', 0) == 0) {
1071
      $ws_endpoint = CDM_WS_PORTAL_TAXON_MEDIA;
1072
    } else {
1073
      $ws_endpoint = CDM_WS_PORTAL_TAXON_SUBTREE_MEDIA;
1074
    }
1075

    
1076
    $media[$taxon->uuid] = cdm_ws_get($ws_endpoint,
1077
        array(
1078
            $taxon->uuid,
1079
        ),
1080
        queryString($mediaQueryParameters)
1081
       );
1082
  }
1083

    
1084
  return $media[$taxon->uuid];
1085
}
1086

    
1087
/**
1088
 *
1089
 * @param Taxon $taxon
1090
 *   A CDM Taxon entitiy
1091
 *
1092
 * @return array
1093
 *   An array of CDM SpecimenOrObservation entities
1094
 *
1095
function _load_occurences_for_taxon($taxon){
1096

    
1097
  static $occurences = NULL;
1098

    
1099
  if(!isset($occurences)) {
1100
    $occurences = array();
1101
  }
1102

    
1103
  if (!isset($occurences[$taxon->uuid])){
1104

    
1105
    $relationship_choice = variable_get(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS, unserialize(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS_DEFAULT));
1106
    $relationship_choice['direct'] = get_selection($relationship_choice['direct']);
1107
    $relationship_choice['invers'] = get_selection($relationship_choice['invers']);
1108

    
1109
    $by_associatedtaxon_query = http_build_query(array(
1110
        'relationshipsInvers' => implode(',', $relationship_choice['invers']),
1111
        'relationships' => implode(',', $relationship_choice['direct']),
1112
        'pageSize' => null // all hits in one page
1113
    )
1114
    );
1115

    
1116
    $pager = cdm_ws_get(CDM_WS_OCCURRENCE_BY_ASSOCIATEDTAXON,
1117
        null,
1118
        $by_associatedtaxon_query . '&taxonUuid=' . $taxon->uuid
1119
    );
1120

    
1121

    
1122
    if(isset($pager->records[0])){
1123
      $occurences[$taxon->uuid] =  $pager->records;
1124
    }
1125
  }
1126
  return $occurences[$taxon->uuid];
1127
}
1128
 */
1129

    
1130
/**
1131
 * Gets a Drupal variable, string or array and returns it.
1132
 *
1133
 * Similar to the variable_get() function of Drupal, except that this function
1134
 * is able to handle arrays correctly. This function is especially useful
1135
 * when dealing with collections of settings form elements (#tree = TRUE).
1136
 *
1137
 * @param string $variableKey
1138
 *   The Unique key of the Drupal variable in the Drupal variables table.
1139
 * @param string $defaultValueString
1140
 *   A string as for example derived from a CONSTANT.
1141
 *
1142
 * @return mixed
1143
 *   usually an array, depending on the nature of the variable.
1144
 *
1145
 * TODO compare with get_array_variable_merged() duplicate functions?
1146
 * @deprecated rather use get_array_variable_merged() since this function
1147
 * used an array as second parameter
1148
 */
1149
function mixed_variable_get($variableKey, $defaultValueString) {
1150
  $systemDefaults = unserialize($defaultValueString);
1151
  $storedSettings = variable_get($variableKey, array());
1152
  if (is_array($storedSettings)) {
1153
    // TODO better use drupal_array_merge_deep() ?
1154
    $settings = array_merge($systemDefaults, $storedSettings);
1155
  }
1156
  else {
1157
    $settings = $systemDefaults;
1158
  }
1159
  return $settings;
1160
}
1161

    
1162
/**
1163
 * Recursive function to convert an object into an array.
1164
 * also subordinate objects will be converted.
1165
 *
1166
 * @param object $object
1167
 * @return the array
1168
 */
1169
function convert_to_array($object) {
1170
  if(is_object($object) || is_array($object)) {
1171
    $array = (array)$object;
1172
    foreach ($array as $key=>$value){
1173
      $array[$key] = convert_to_array($value);
1174
    }
1175
    return $array;
1176
  } else {
1177
    return $object;
1178
  }
1179
}
1180

    
1181
/**
1182
 * Searches the $collection for the cdm entitiy given as $element.
1183
 *
1184
 * The elements are compared by their UUID.
1185
 *
1186
 * @param $element
1187
 *  the CDM entitiy to search for
1188
 * @param $collection
1189
 *  the list of CDM entities to search in
1190
 *
1191
 * @return boolean TRUE if the $collection contains the $element, otheriwse FALSE
1192
 *
1193
 */
1194
function contains_cdm_entitiy($element, $collection) {
1195
  $result = FALSE;
1196
  foreach ($collection as $a) {
1197
    if ($a->uuid == $element->uuid) {
1198
      $result = TRUE;
1199
    }
1200
  }
1201
  return $result;
1202
}
1203

    
1204
/**
1205
 * Fiters the array $entity_list of CDM entities by the list
1206
 * of $excludes. Any element contained in the $excludes will be removed
1207
 * from included int the retuned list.
1208
 *
1209
 * If the $entity_list is not an array the $excludes will be returned.
1210
 */
1211
function filter_cdm_entity_list($entity_list, $excludes) {
1212
  if (is_array($entity_list)) {
1213
    $result = $entity_list;
1214
    if ($excludes) {
1215
      foreach ($excludes as $exclude) {
1216
        if (!contains_cdm_entitiy($exclude, $entity_list)) {
1217
          $result[] = $exclude;
1218
        }
1219
      }
1220
    }
1221
  }
1222
  else {
1223
    $result = $excludes;
1224
  }
1225
  return $result;
1226
}
1227

    
1228
/**
1229
 * Wraps the given $html string into a render array suitable for drupal_render()
1230
 *
1231
 * @param $html
1232
 *   the html string, see
1233
 *   http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#markup
1234
 * @param $weight
1235
 *   A positive or negative number (integer or decimal).
1236
 *   see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#weightval
1237
 * @param $prefix
1238
 *   Optional markup for the '#prefix' element of the render array
1239
 * @param $suffix
1240
 *   Optional markup for the '#suffix' element of the render array
1241
 *
1242
 * @return array
1243
 *   A render array
1244
 *
1245
 */
1246
function markup_to_render_array($html, $weight = FALSE, $prefix = NULL, $suffix = NULL) {
1247
  $render_array = array(
1248
    '#markup' => $html
1249
      );
1250
  if (is_numeric($weight)) {
1251
    $render_array['#weight'] = $weight;
1252
  }
1253
  if($prefix){
1254
    $render_array['#prefix'] = $prefix;
1255
  }
1256
  if($suffix) {
1257
    $render_array['#suffix'] = $suffix;
1258
  }
1259
  return $render_array;
1260
}
1261

    
1262
/**
1263
 * Loads the subgraph of a given PolytomousKeyNode.
1264
 *
1265
 * Loads the subgraph of the given PolytomousKeyNode recursively from
1266
 * the CDM REST service.
1267
 *
1268
 * @param mixed $polytomousKeyNode
1269
 *   PolytomousKeyNode passed by reference.
1270
 *
1271
 * @return void
1272
 */
1273
function _load_polytomousKeySubGraph(&$polytomousKeyNode) {
1274

    
1275
  if (!$polytomousKeyNode) {
1276
    return;
1277
  }
1278
  if ($polytomousKeyNode->class != "PolytomousKeyNode") {
1279
    drupal_set_message('_load_polytomousKeySubGraph(): ' . t('invalid type given.'), 'error');
1280
    return;
1281
  }
1282
  if (!is_uuid($polytomousKeyNode->uuid)) {
1283
    drupal_set_message('_load_polytomousKeySubGraph(): ' . t('invalid type given.'), 'error');
1284
    return;
1285
  }
1286

    
1287
  $polytomousKeyNode = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, $polytomousKeyNode->uuid);
1288

    
1289
  if (!$polytomousKeyNode) {
1290
    // drupal_set_message("_load_polytomousKeyChildNodes() : could not load polytomousKeyNode", "error");
1291
    return;
1292
  }
1293

    
1294
  // Load children.
1295
  foreach ($polytomousKeyNode->children as &$childNode) {
1296
    _load_polytomousKeySubGraph($childNode);
1297
  }
1298

    
1299
  // Load subkey.
1300
  $polytomousKeyNode->subkey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "subkey"));
1301

    
1302
  // Load taxon.
1303
  $polytomousKeyNode->taxon = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "taxon"));
1304
  _load_taxonBase($polytomousKeyNode->taxon);
1305
  return;
1306
}
1307

    
1308
/**
1309
 * @todo Please document this function.
1310
 * @see http://drupal.org/node/1354
1311
 */
1312
function cdm_dataportal_view_polytomousKey($polytomousKeyUuid) {
1313

    
1314
  cdm_check_valid_portal_page();
1315

    
1316
  $polytomousKey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, $polytomousKeyUuid);
1317

    
1318
  $sourcePager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'sources'));
1319
  if (is_array($sourcePager->records)) {
1320
    $polytomousKey->sources = $sourcePager->records;
1321
    // $polytomousKey->sources->citation = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'sources'));
1322
  }
1323

    
1324
  $annotationPager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'annotations'));
1325
  if (is_array($annotationPager->records)) {
1326
    $polytomousKey->annotations = $annotationPager->records;
1327
  }
1328

    
1329
  _load_polytomousKeySubGraph($polytomousKey->root);
1330
  return theme('cdm_polytomousKey_page', array('polytomousKey' => $polytomousKey));
1331
}
1332

    
1333
/**
1334
 * Creates a taxon page view or a chapter of it.
1335
 *
1336
 * The taxon page gives detailed information on a taxon, it shows:
1337
 *  - Taxon name.
1338
 *  - Full list of synonyms homotypic synonyms on top, followed by the
1339
 *    heterotypic and finally followed by misapplied names.
1340
 *    The list is ordered historically.
1341
 *  - All description associated with the taxon.
1342
 *
1343
 * @param string $uuid
1344
 * @param string $chapter
1345
 *   Name of the part to display, valid values are:
1346
 *   'description', 'images', 'synonymy', 'specimens', 'all'.
1347
 *
1348
 * @return unknown_type
1349
 */
1350
function cdm_dataportal_taxon_page_view($uuid, $chapter = 'all', $synonym_uuid = NULL) {
1351

    
1352
  cdm_check_valid_taxon_page($chapter);
1353
  cdm_dd("START OF TAXON PAGE [" . $chapter . "] " . $uuid . ' for ' . $_GET['q']);
1354
  // show a warning in case the javascript development mode is anabled
1355
  if(variable_get('cdm_js_devel_mode', FALSE)) {
1356
    drupal_set_message(t('The !url1 is enabled.
1357
        WARNING: this is a performance penalty and must be turned off on production websites.', array(
1358
          '!url1' => l('java-script development mode', 'admin/config/cdm_dataportal/settings', array('fragment' => 'edit-cdm-js-devel-mode'))
1359
    )),
1360
    'warning'
1361
        );
1362
  }
1363

    
1364
  // Display the page for the taxon defined by $uuid.
1365
  // set_last_taxon_page_tab(arg(3));
1366
  $taxonpage = cdm_dataportal_taxon_view($uuid, $chapter, $synonym_uuid);
1367
  if (!empty($taxonpage)) {
1368
    cdm_dd("END OF TAXON PAGE [" . $chapter . "] " . $uuid);
1369
    return cdm_node_show(NODETYPE_TAXON, $uuid, $taxonpage->title, $taxonpage->content);
1370
  }
1371
  else {
1372
    cdm_dd("END OF TAXON PAGE [" . $chapter . "] " . $uuid . ' !!! PAGE IS EMPTY !!!');
1373
    return '';
1374
  }
1375
}
1376

    
1377
/**
1378
 * This function will genreate the taxon page part ($chapter) and returns a taxonpage object
1379
 * which has two fields, one for the page title and one for the content. Later on in the
1380
 * process chain the value contained in these fields will be passed to the cdm_node_show()
1381
 * function as the function parameters $title and $content.
1382
 *
1383
 * @param string $uuid
1384
 *   the uuid of the taxon to show
1385
 * @param string $chapter
1386
 *   Name of the part to display, valid values are:
1387
 *   'description', 'images', 'synonymy', 'all'.
1388
 *
1389
 * @return taxonpage object with the following fields:
1390
 *   - title : the title of the page
1391
 *   - content: the content of the page
1392
 *
1393
 */
1394
function cdm_dataportal_taxon_view($uuid, $chapter = 'all') {
1395
  // Taxon object.
1396
  $taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON, $uuid);
1397
  if (empty($taxon)) {
1398
    drupal_set_title(t('Taxon does not exist'), PASS_THROUGH);
1399
    return FALSE;
1400
  }
1401
  $taxonpage = new stdClass();
1402

    
1403
  $taxonpage->title = theme('cdm_taxon_page_title', array(
1404
    'taxon' => $taxon
1405
  ));
1406

    
1407
  // Check if the taxon id contained in the currently selected tree.
1408
  $taxon_in_current_classification = taxon_in_current_classification($uuid);
1409

    
1410
  if (!$taxon_in_current_classification) {
1411
    $classifications = get_classifications_for_taxon($taxon);
1412
    RenderHints::pushToRenderStack('not_in_current_classification');
1413
    $taxon_name_markup = render_taxon_or_name($taxon);
1414

    
1415
    if (count($classifications) == 0) {
1416
      drupal_set_message(t('This concept of the taxon !taxonname is not contained as an accepted taxon in the currently chosen classification.',
1417
        array(
1418
        '!taxonname' => $taxon_name_markup,
1419
        )
1420
      ), 'warning');
1421
    }
1422
    else {
1423
      $trees = '';
1424
      foreach ($classifications as $classification) {
1425
        if (isset($classification->titleCache)) {
1426
          $trees .= ($trees ? ', ' : '') . '<strong>' . $classification->titleCache . '</strong>';
1427
        }
1428
      }
1429

    
1430
      drupal_set_message(format_plural(count($trees),
1431
          'This concept of the taxon !taxonname is not contained as an accepted taxon in the currently chosen classification, but in this one: !trees',
1432
          'This concept of the taxon !taxonname is not contained as an accepted taxon in the currently chosen classification, but in one of these: !trees',
1433
          array('!taxonname' => $taxon_name_markup, '!trees' => $trees)
1434
        ) ,
1435
        'warning');
1436
    }
1437
    RenderHints::popFromRenderStack();
1438
  }
1439

    
1440
  // Render the taxon page.
1441
  $render_array = compose_cdm_taxon_page($taxon, $chapter);
1442
  $taxonpage->content = drupal_render($render_array);
1443

    
1444
  return $taxonpage;
1445
}
1446

    
1447
/**
1448
 * Creates a specimen page view.
1449
 * @param string $uuid the UUID of the specimen
1450
 * @return array|string
1451
 */
1452
function cdm_dataportal_specimen_page_view($uuid) {
1453

    
1454
    //cdm_check_valid_taxon_page($chapter);
1455
    //cdm_dd("START OF TAXON PAGE [" . $chapter . "] " . $uuid . ' for ' . $_GET['q']);
1456
    // show a warning in case the javascript development mode is anabled
1457
    if(variable_get('cdm_js_devel_mode', FALSE)) {
1458
        drupal_set_message(t('The !url1 is enabled.
1459
        WARNING: this is a performance penalty and must be turned off on production websites.', array(
1460
            '!url1' => l('java-script development mode', 'admin/config/cdm_dataportal/settings', array('fragment' => 'edit-cdm-js-devel-mode'))
1461
        )),
1462
            'warning'
1463
        );
1464
    }
1465

    
1466
    // Display the page for the specimen defined by $uuid.
1467
    $specimenpage = cdm_dataportal_specimen_view($uuid);
1468
    if (!empty($specimenpage)) {
1469
        return cdm_node_show(NODETYPE_TAXON, $uuid, $specimenpage->title, $specimenpage->content);
1470
    }
1471
    else {
1472
        return '';
1473
    }
1474
}
1475

    
1476
/**
1477
 *
1478
 * Creates a specimen view.
1479
 * @param string $uuid the UUID of the specimen
1480
 * @return array|string
1481
 */
1482
function cdm_dataportal_specimen_view($uuid) {
1483
    $specimen = cdm_ws_get(CDM_WS_OCCURRENCE, $uuid);
1484
    if (empty($specimen)) {
1485
        drupal_set_title(t('Specimen does not exist'), PASS_THROUGH);
1486
        return FALSE;
1487
    }
1488
    $specimenpage = new stdClass();
1489

    
1490
    $specimenpage->title = theme('cdm_specimen_page_title', array(
1491
        'specimen' => $specimen
1492
    ));
1493

    
1494
    // Render the specimen page.
1495
    $render_array = compose_cdm_specimen_page($uuid);
1496
    $specimenpage->content = drupal_render($render_array);
1497

    
1498
    return $specimenpage;
1499
}
1500

    
1501
/**
1502
 * Returns a name page as a Drupal node ready to be renderized by Drupal.
1503
 *
1504
 * The node page shows the taxon name title and the list of taxon related
1505
 * with such taxon. Name on the tree already in use.
1506
 *
1507
 * @param UUID $taxon_name_uuid
1508
 *   The uuid of the CDM TaxonNameBase to show a name page for
1509
 * @param UUID $taxon_to_hide_uuid
1510
 *   A taxon which should not be displayed in the taxon list
1511
 * @param UUID $highlite_synonym_uuid
1512
 *   Optinal parameter wich takes another taxon uuid, if given the
1513
 *   target taxon pages will show the syonymy tab where the taxon
1514
 *   refenrenced by the $highlite_synonym_uuid will be highlighted
1515
 *   in case it is found on this page.
1516
 *
1517
 * @return mixed
1518
 *   The formatted name page as node.
1519
 */
1520
function cdm_dataportal_name_page_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid = NULL) {
1521

    
1522
  cdm_check_valid_portal_page();
1523

    
1524
  $taxonname_page = cdm_dataportal_name_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid);
1525
  if (!empty($taxonname_page)) {
1526
    return cdm_node_show(NODETYPE_NAME, $taxon_name_uuid, $taxonname_page->title, $taxonname_page->content);
1527
  }
1528
  else {
1529
    return '';
1530
  }
1531
}
1532

    
1533
/**
1534
 * View function for a TaxonNameBase page.
1535
 *
1536
 * The name page lists all taxa for which the name specified by the
1537
 * $taxon_name_uuid is being used. I case there is only one name the
1538
 * page automatically redirects ti the according taxon page. Otherwise
1539
 * the list of names is displayed.
1540
 *
1541
 * The parameter $taxon_to_hide_uuid allows to exclude a taxon from the
1542
 * list of taxa. This is useful for example when referencing from a taxon
1543
 * to the name page and the referring taxon should not be repeaded in the
1544
 * name page.
1545
 *
1546
 *
1547
 * @param UUID $taxon_name_uuid
1548
 *   The uuid of the CDM TaxonNameBase to show a name page for
1549
 * @param UUID $taxon_to_hide_uuid
1550
 *   A taxon which should not be displayed in the taxon list
1551
 * @param UUID $highlite_synonym_uuid
1552
 *   Optinal parameter wich takes another taxon uuid, if given the
1553
 *   target taxon pages will show the syonymy tab where the taxon
1554
 *   refenrenced by the $highlite_synonym_uuid will be highlighted
1555
 *   in case it is found on this page.
1556
 *
1557
 * @return object
1558
 *   An object with two fields:
1559
 *     - title: the page title
1560
 *     - content: the page content
1561
 */
1562
function cdm_dataportal_name_view($taxon_name_uuid, $taxon_to_hide_uuid, $highlite_synonym_uuid = NULL) {
1563
  // Getting the full taxonname object from the server.
1564
  $taxon_name = cdm_ws_get(CDM_WS_PORTAL_NAME, array($taxon_name_uuid));
1565
  if (!$taxon_name) {
1566
    drupal_set_title(t('Taxon name does not exist'), PASS_THROUGH);
1567
    return FALSE;
1568
  }
1569
  // Searching for all the taxa connected with the taxon name on the tree
1570
  // in use.
1571
  $name_cache = cdm_ws_get(CDM_WS_NAME_NAMECAHE, array($taxon_name_uuid));
1572
  $request_params = array();
1573
  $request_params['query'] = $name_cache;
1574
  $request_params['tree'] = get_current_classification_uuid();
1575
  $request_params['doTaxa'] = 1;
1576
  $request_params['doSynonyms'] = 1;
1577
  $request_params['doTaxaByCommonNames'] = 0;
1578
  $request_params['matchMode'] = "EXACT";
1579
  $taxon_pager = cdm_ws_get(CDM_WS_PORTAL_TAXON_FIND, NULL, queryString($request_params));
1580

    
1581
  // Removing the name where we came from.
1582
  foreach ($taxon_pager->records as $k => &$taxon) {
1583
    if ($taxon->uuid == $taxon_to_hide_uuid) {
1584
      unset($taxon_pager->records[$k]);
1585
    }
1586
  }
1587
  // Show the taxa list or go to the singular taxon.
1588
  if (sizeof($taxon_pager->records) == 1) {// Single taxon case.
1589
    $singleTaxon = array_pop($taxon_pager->records);
1590
    if ($singleTaxon->class != "Taxon") {
1591
      // It is a Synonym -> look for the accepted.
1592
      $accepted_taxa = cdm_ws_get(CDM_WS_PORTAL_TAXON_ACCEPTED, array($singleTaxon->uuid, get_current_classification_uuid()));
1593
      if (!empty($highlite_synonym_uuid)) {
1594
        drupal_goto('cdm_dataportal/taxon/' . $accepted_taxa[0]->uuid . '/synonymy', array('query' => array('highlite' => $highlite_synonym_uuid)));
1595
      }
1596
      else {
1597
        drupal_goto('cdm_dataportal/taxon/' . $accepted_taxa[0]->uuid . '/synonymy', array('query' => array('highlite' => $singleTaxon->uuid)));
1598
      }
1599
    }
1600
    else {
1601
      // It is an accepted taxon.
1602
      if (!empty($highlite_synonym_uuid)) {
1603
        drupal_goto('cdm_dataportal/taxon/' . $singleTaxon->uuid . '/synonymy', array('query' => array('highlite' => $highlite_synonym_uuid)));
1604
      }
1605
      else {
1606
        drupal_goto('cdm_dataportal/taxon/' . $singleTaxon->uuid);
1607
      }
1608
    }
1609
  }
1610
  else {// More than one taxa case.
1611
    $taxon_name_page = new stdClass();
1612
    $taxon_name_page->title = theme('cdm_name_page_title', array('taxon_name' => $taxon_name));
1613
    if ($taxon_pager->records) {
1614
      $taxon_name_page->content = compose_list_of_taxa($taxon_pager->records);
1615
    }
1616
    else {
1617
      $taxon_name_page->content = 'This name has no taxa';
1618
    }
1619
    return $taxon_name_page;
1620
  }
1621
}
1622

    
1623
/**
1624
 * Creates a page with the advance search form.
1625
 *
1626
 * NOTE: The advance search form allows searching for taxa.
1627
 */
1628
function cdm_dataportal_view_search_advanced() {
1629
  drupal_set_title(t('Advanced search'), PASS_THROUGH);
1630
  return drupal_get_form('cdm_dataportal_search_taxon_form_advanced');
1631
}
1632

    
1633
/**
1634
 * Creates a page with the search form for searching by taxon descriptions.
1635
 */
1636
function cdm_dataportal_view_search_taxon_by_description() {
1637
  drupal_set_title(t('Search by factual data'), PASS_THROUGH);
1638
  return drupal_get_form('cdm_dataportal_search_taxon_by_description_form');
1639
}
1640

    
1641
/**
1642
 * Executes the search and generates the result list of taxa.
1643
 */
1644
function cdm_dataportal_view_search_results_taxon() {
1645

    
1646
  $taxonPager = cdm_dataportal_search_execute();
1647

    
1648
  $showThumbnails = do_showThumbnails();
1649

    
1650
  $setSessionUri = url('cdm_api/setvalue/session', array(
1651
      'query' => array('var' => '[pageoption][searchtaxa][showThumbnails]', 'val' => ''),
1652
  ));
1653

    
1654
  drupal_add_js('jQuery(document).ready(function() {
1655

    
1656
      // init
1657
      if(' . $showThumbnails . ' == 1){
1658
          jQuery(\'.media_gallery\').show(20);
1659
      } else {
1660
          jQuery(\'.media_gallery\').hide(20);
1661
      }
1662

    
1663
      // add change handler
1664
      jQuery(\'#showThumbnails input.showThumbnails\').change(
1665
      function(event){
1666
        var state = 0;
1667
        if(jQuery(this).is(\':checked\')){
1668
          jQuery(\'.media_gallery\').show(20);
1669
          state = 1;
1670
        } else {
1671
          jQuery(\'.media_gallery\').hide(20);
1672
        }
1673
        // store state in session variable
1674
        var uri = \'' . $setSessionUri . '\' + state;
1675
        jQuery.get(uri);
1676
      });
1677
  });',
1678
  array('type' => "inline", 'scope' => JS_DEFAULT));
1679

    
1680
  drupal_set_title(t('Search results'), PASS_THROUGH);
1681

    
1682
  return theme('cdm_search_results', array(
1683
    'pager' => $taxonPager,
1684
    'path' => 'cdm_dataportal/search/results/taxon',
1685
    ));
1686
}
1687

    
1688
/**
1689
 * Provides the standart image wich indicated a loading process
1690
 *
1691
 * @return string
1692
 *  The img html tag
1693
 */
1694
function loading_image_html() {
1695
  return '<img class="loading" src="' . base_path() . drupal_get_path('module', 'cdm_dataportal')
1696
    . '/images/loading_circle_grey_16.gif" style="display:none;">';
1697
}
1698

    
1699
/**
1700
 * Returns the state of the the showThumbnails flag set in the
1701
 * users session ($_SESSION['pageoption']['searchtaxa']['showThumbnails']).
1702
 *
1703
 * @return boolean
1704
 *    returns 1 if the flag is set
1705
 */
1706
function do_showThumbnails() {
1707
  static $showThumbnails = null;
1708

    
1709
  if($showThumbnails == null) {
1710
    $showThumbnails = 0;
1711
    if (!isset($_SESSION['pageoption']['searchtaxa']['showThumbnails'])) {
1712
      $showThumbnails = 0;
1713
      $search_gallery_settings = variable_get(CDM_DATAPORTAL_SEARCH_GALLERY_NAME, null);
1714
      $showThumbnails = is_array($search_gallery_settings)
1715
        && isset($search_gallery_settings['cdm_dataportal_show_taxon_thumbnails'])
1716
        && (
1717
            $search_gallery_settings['cdm_dataportal_show_taxon_thumbnails'] +
1718
            $search_gallery_settings['cdm_dataportal_show_synonym_thumbnails'] +
1719
            $search_gallery_settings['cdm_dataportal_show_thumbnail_captions'] > 0
1720
            )
1721
         ? 1 : 0;
1722

    
1723
       drupal_array_set_nested_value($_SESSION, array('pageoption', 'searchtaxa', 'showThumbnails'), $showThumbnails);
1724
    }
1725
    $showThumbnails = $_SESSION['pageoption']['searchtaxa']['showThumbnails'];
1726
    if (!is_numeric($showThumbnails)) {
1727
      $showThumbnails = 1;
1728
    }
1729
  }
1730

    
1731
  return $showThumbnails;
1732
}
1733

    
1734
/**
1735
 * View which transforms XML output from a given webservice endpoint into JSON.
1736
 */
1737
/*
1738
 function cdm_view_xml2json(){
1739
 $file = arg(2);
1740
 $datastr = file_get_contents(variable_get('cdm_webservice_url', '').$file);
1741
 return  xml2json::transformXmlStringToJson($datastr);
1742
 }
1743
 */
1744

    
1745
/* ====================== other functions ====================== */
1746
/**
1747
 * Creates a URL to the taxon page specified by the $uuid parameter.
1748
 *
1749
 * The URL will be prepended with a path element to a specific taxon page tab.
1750
 *
1751
 * This tab is either taken from the CDM_DATAPORTAL_DEFAULT_TAXON_TAB which can
1752
 * be set globally in the administrative settings or individually in the user
1753
 * profile. If the CDM_DATAPORTAL_DEFAULT_TAXON_TAB value is set to LAST_VISITED_TAB
1754
 * the last portal will stay on this last tab.
1755
 *
1756
 * A third option is offerered by the $page_tab parameter which allows overwriting this
1757
 * internal mechanism by a specific value.
1758
 *
1759
 * @param string $uuid
1760
 *   The UUID of the taxon.
1761
 * @param string $page_tab
1762
 *   Overwriting the preset mechanism by defining specific value for the
1763
 *   taxon page tab.
1764
 *
1765
 * @return string
1766
 *   The created URL.
1767
 */
1768
function path_to_taxon($uuid, $page_tab = FALSE) {
1769

    
1770
  $tab = get_default_taxon_tab();
1771
  $values = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
1772

    
1773
  if (!$uuid) {
1774
    return FALSE;
1775
  }
1776

    
1777
  if ($page_tab) {
1778
    return 'cdm_dataportal/taxon/' . $uuid . '/' . $page_tab;
1779
  }
1780
  elseif (!$tab || strtolower($tab) == 'general') {
1781
    return 'cdm_dataportal/taxon/' . $uuid;
1782
  }
1783
  elseif (get_last_taxon_page_tab() &&   $tab == $values[CDM_DATAPORTAL_LAST_VISITED_TAB_ARRAY_INDEX]) {
1784
    return 'cdm_dataportal/taxon/' . $uuid . '/' . get_last_taxon_page_tab();
1785
  }
1786
  else {
1787
    return 'cdm_dataportal/taxon/' . $uuid . '/' . strtolower($tab);
1788
  }
1789
}
1790

    
1791
function path_to_specimen($uuid) {
1792

    
1793
    if (!$uuid) {
1794
        return FALSE;
1795
    }
1796
    else {
1797
        return 'cdm_dataportal/specimen/' . $uuid;
1798
    }
1799
}
1800

    
1801
/**
1802
 * Creates a URL to show a synonmy in the according taxon page.
1803
 *
1804
 * The URL will point to the synonymy tab of the taxon page of the accepted taxon given as parameter $acceptedUuid.
1805
 * The resulting URI will include query parameters to highlight the synonym, and to optionally display
1806
 * the accepted taxons name in aform like "Foo bar is accepted taxon for Ree doo". The URI will also
1807
 * include the sysnonym uuid as fragment in order to let the browser scroll to the according location
1808
 * in the page
1809
 *
1810
 * @param string $synonymUuid
1811
 *    The uuid of the synonym
1812
 * @param string $acceptedUuid
1813
 *    The uuid of the according accepted taxon
1814
 * @return string
1815
 *    The URL to show a synonmy in the according taxon page
1816
 */
1817
function uri_to_synonym($synonymUuid, $acceptedUuid) {
1818
  $acceptedPath = path_to_taxon($acceptedUuid, "synonymy");
1819
  return url($acceptedPath, array(
1820
      'query' => array(
1821
        // highlite the synony in the synonymy
1822
        'highlite' => $synonymUuid,
1823
        // the taxon page is refered from a synonym and the synonym can optionally be named in the page title
1824
        // see theme_taxon_page_title()
1825
        'acceptedFor' => $synonymUuid
1826
      ),
1827
      'fragment' => $synonymUuid
1828
  ));
1829

    
1830
}
1831

    
1832
/**
1833
 * Compses the drupal path to the key identified by the uuid.
1834
 *
1835
 * @param string $keyType
1836
 *    the key typer corresponds to the specific class of the CDM
1837
 *    IdentificationKey. Possible values are
1838
 *      -PolytomousKey
1839
 *      -MultimediaKey
1840
 *      - ...
1841
 * @param UUID $keyUuid
1842
 *   The UUID of the key
1843
 */
1844
function path_to_key($keyType, $keyUuid) {
1845
  if (!$keyUuid || !$keyType) {
1846
    return FALSE;
1847
  }
1848
  $keyType{0} = strtolower($keyType{0});
1849
  return "cdm_dataportal/" . $keyType . "/$keyUuid";
1850
}
1851

    
1852
/**
1853
 * @todo Please document this function.
1854
 * @see http://drupal.org/node/1354
1855
 */
1856
function path_to_reference($uuid) {
1857
  if (!$uuid) {
1858
    return FALSE;
1859
  }
1860
  return 'cdm_dataportal/reference/' . $uuid;
1861
}
1862

    
1863
/**
1864
 * Creates the path to a cdm_dataportal taxon name page.
1865
 *
1866
 * @param UUID $taxon_name_uuid
1867
 *   The uuid of the CDM TaxonNameBase to show a name page for
1868
 * @param UUID $taxon_to_hide_uuid
1869
 *   A taxon which should not be displayed in the taxon list
1870
 * @param UUID $highlite_synonym_uuid
1871
 *   Optinal parameter wich takes another taxon uuid, if given the
1872
 *   target taxon pages will show the syonymy tab where the taxon
1873
 *   refenrenced by the $highlite_synonym_uuid will be highlighted
1874
 *   in case it is found on this page.
1875
 *
1876
 * @return a URI path element as string
1877
 */
1878
function path_to_name($name_uuid, $taxon_to_hide_uuid = NULL, $synonym_uuid  = NULL) {
1879
  $res = FALSE;
1880
  if ($name_uuid) {
1881
    $res = 'cdm_dataportal/name/' . $name_uuid;
1882
  }
1883
  if($taxon_to_hide_uuid){
1884
    $res .= '/' . $taxon_to_hide_uuid;
1885
    if($synonym_uuid){
1886
      $res .= '/' . $synonym_uuid;
1887
    }
1888
  }
1889
  return $res;
1890
}
1891

    
1892
/**
1893
 * @todo Please document this function.
1894
 * @see http://drupal.org/node/1354
1895
 */
1896
function path_to_media($uuid, $representaion_uuid = FALSE, $partId = FALSE) {
1897
  if (!$uuid) {
1898
    return FALSE;
1899
  }
1900
  $out = 'cdm_dataportal/media/' . $uuid;
1901
  if ($representaion_uuid) {
1902
    $out .= '/' . $representaion_uuid;
1903
    if ($partId !== FALSE) {
1904
      $out .= '/' . $partId;
1905
    }
1906
  }
1907
  return $out;
1908
}
1909

    
1910
/**
1911
 * Compares thisRank with thatRank.
1912
 *
1913
 * Returns a negative integer, zero, or a positive integer
1914
 * as the of thisRank is higher than, equal to, or lower than thatRank.
1915
 * e.g:
1916
 * <ul>
1917
 * <li>rank_compare({species_uuid}, {genus_uuid}) = -1</li>
1918
 * <li>rank_compare({genus_uuid}, {genus_uuid}) = 0</li>
1919
 * <li>rank_compare({genus_uuid}, {tribus_uuid}) = 1</li>
1920
 * </ul>
1921
 * <p>
1922
 * This compare logic of the underlying webservice is the
1923
 * <b>inverse logic</b> of the the one implemented in
1924
 * java.lang.Comparable#compareTo(java.lang.Object)
1925
 *
1926
 * @param $thisRankUuid
1927
 * @param $thatRankUuid
1928
 *
1929
 * @return int
1930
 *   A negative integer, zero, or a positive integer
1931
 *   as the thisRank is lower than, equal to, or higher than thatRank.
1932
 */
1933
function rank_compare($thisRankUuid, $thatRankUuid) {
1934
  $result = cdm_ws_get(CDM_WS_TERM_COMPARE, array($thisRankUuid, $thatRankUuid));
1935
  return $result->Integer;
1936
}
1937

    
1938
/**
1939
 * Composes an HTML element class attribute value composed of
1940
 * the shortname of the cdm class and the uuid of the entity.
1941
 * This class attribute should be used whereever an cdm-entity is rendered.
1942
 *
1943
 * These according class selectors in css must be escaped, eg:
1944
 *    .cdm\:TextData
1945
 *
1946
 * @param $cdmEntity
1947
 */
1948
function html_class_attribute_ref($cdmEntity) {
1949

    
1950
  if (is_cdm_entity($cdmEntity)) {
1951
    return "cdm:" . $cdmEntity->class . " uuid:" . $cdmEntity->uuid;
1952
  }
1953
}
1954

    
1955

    
1956
/**
1957
 * Creates a short taxonname.
1958
 *
1959
 * The short name is created by using the taggedTitle field of
1960
 * NameSTO or NameTO instances.
1961
 * If the taggedTitle if empty the fullname will be returned.
1962
 *
1963
 * @param unknown_type $name
1964
 *   Name or TreeNode.
1965
 *
1966
 * @return string
1967
 */
1968
function cdm_dataportal_shortname_of($name) {
1969
  $nameStr = '';
1970

    
1971
  normalize_tagged_text($name->taggedTitle);
1972

    
1973
  // Get all tagged text tokens of the scientific name.
1974
  foreach ($name->taggedTitle as $tagtxt) {
1975
    if ($tagtxt->type == 'name' || $tagtxt->type == 'rank') {
1976
      $nameStr .= ($nameStr ? ' ' : '') . $tagtxt->text;
1977
    }
1978
  }
1979
  $nameStr = trim($nameStr);
1980

    
1981
  if ($nameStr) {
1982

    
1983
    // Do not return short names for these.
1984
    if ($name->unplaced || $name->excluded) {
1985
      return $nameStr;
1986
    }
1987

    
1988
    /*
1989
    1st capture group (^[a-zA-Z]): First letter of uninomial.
1990
    Second capture group ([\p{L}]+): remaining letters of uninomial ([\p{L} = an UTF-8 letter).
1991
    Third capture group (\s+[^(\x2E]+\s+.+$|\s+[a-zA-Z]+$): letters of name,
1992
    but only matching if no '(' or '.' in second word of name,        ( \x2E = '.')
1993
    OR only one specific epithet \s+[\p{L}\x22\x2D\xD7]+$             (\x22= '"', \x2D='-', \xD7='×' )
1994
    */
1995
    $pattern = '/(^[a-zA-Z])([\p{L}]+)(\s+[^(\x2E]+\s+.+$|\s+[\p{L}\x22\x2D\xD7]+$)/u';
1996
    if (preg_match($pattern, $nameStr, $matches, PREG_OFFSET_CAPTURE)) {
1997
      return $matches[1][0] . "." . $matches[3][0];
1998
    }
1999
    else {
2000
      return $nameStr;
2001
    }
2002
  }
2003
  else {
2004
    return $name->titleCache;
2005
  }
2006
}
2007

    
2008
/**
2009
 * Check if a taxon is accepted by the current taxonomic tree.
2010
 *
2011
 * @param mixed $taxon
2012
 *   The Taxon obkect to check.
2013
 *
2014
 * @return bool
2015
 *   Returns TRUE if $taxon is accepted, FALSE otherwise.
2016
 */
2017
function _cdm_dataportal_acceptedByCurrentView($taxon) {
2018

    
2019
  $defaultTreeUuid = get_current_classification_uuid();
2020

    
2021
  if (isset($taxon->taxonNodes)) {
2022
    $taxonNodes = $taxon->taxonNodes;
2023
  }
2024
  else {
2025
    $taxonNodes = cdm_ws_get(CDM_WS_PORTAL_TAXON_TAXONNODES, $taxon->uuid);
2026
  }
2027

    
2028
  if ($taxon->class == "Taxon" && isset($taxonNodes)) {
2029
    foreach ($taxonNodes as $node) {
2030
      if (isset($node->classification)){
2031
        if(is_object($node->classification)) {
2032
          if ($node->classification->uuid == $defaultTreeUuid) {
2033
            return TRUE;
2034
          }
2035
        }
2036
        else {
2037
          if ($node->classification == $defaultTreeUuid) {
2038
            return TRUE;
2039
          }
2040
        }
2041
      }
2042
    }
2043
  }
2044

    
2045
  return FALSE;
2046
}
2047

    
2048
/**
2049
 * Checks is the source has one of the given types.
2050
 *
2051
 * @param object $source
2052
 *   The original source entity
2053
 * @param array $types
2054
 *   An array of elementd of the OriginalSourceType enumeration
2055
 *   If not set the default will be used which is:
2056
 *    - Lineage
2057
 *    - PrimaryMediaSource
2058
 *    - PrimaryTaxonomicSource
2059
 *    - Unknown
2060
 *    - Other
2061
 * @return boolean
2062
 */
2063
  function _is_original_source_type($source, $types = null) {
2064
    // this is the default
2065
    // maybe this should also be put into the settings
2066
    static $default = array(
2067
      OriginalSourceType::Lineage,
2068
      OriginalSourceType::PrimaryMediaSource,
2069
      OriginalSourceType::PrimaryTaxonomicSource,
2070
      OriginalSourceType::Unknown,
2071
      OriginalSourceType::Other,
2072
    );
2073

    
2074
    if(!$types){
2075
      $types = $default;
2076
    }
2077
    return isset($source->type) && in_array($source->type, $types);
2078
  }
2079

    
2080
/**
2081
 * @todo Please document this function.
2082
 * @see http://drupal.org/node/1354
2083
 */
2084
function _is_invers_taxonRelationship($taxonRelationship, $focusedTaxon) {
2085
  return $taxonRelationship->toTaxon->uuid == $focusedTaxon->uuid;
2086
}
2087

    
2088

    
2089
/**
2090
 * Collects all the media from a list of description elements.
2091
 *
2092
 * @param array $descriptionElements
2093
 *   The description elements from which to collect the media.
2094
 *
2095
 * @return array
2096
 *   The output with all the collected media.
2097
 */
2098
function cdm_dataportal_media_from_descriptionElements($descriptionElements) {
2099

    
2100
  $outArrayOfMedia = array();
2101

    
2102
  // Avoiding a warning box in Drupal for Flora Malesiana.
2103
  if (isset($descriptionElements) && is_array($descriptionElements)) {
2104
    foreach ($descriptionElements as $descriptionElement) {
2105
      if (isset($descriptionElement->media) && is_array($descriptionElement->media)) {
2106
        foreach ($descriptionElement->media as $media) {
2107
          if (is_object($media)) {
2108
            $outArrayOfMedia[] = $media;
2109
          }
2110
        }
2111
      }
2112
    }
2113
  }
2114
  return $outArrayOfMedia;
2115
}
2116

    
2117
/**
2118
 * @todo Please document this function.
2119
 * @see http://drupal.org/node/1354
2120
 *
2121
 * @param array $cdm_entities
2122
 *   An array of CdmBase instances or a single instance.
2123
 * @param string $footnote_list_key_suggestion
2124
 *
2125
 * @return unknown
2126
 */
2127
function cdm_annotations_as_footnotekeys($cdm_entities, $footnote_list_key_suggestion = NULL) {
2128

    
2129
   static $annotations_types_filter = null;
2130
   if(!$annotations_types_filter) {
2131
     $annotations_types_filter = unserialize(ANNOTATIONS_TYPES_AS_FOOTNOTES_DEFAULT);
2132
   }
2133

    
2134
  $footNoteKeys = array();
2135

    
2136
  // Is argument cdmBase an array?
2137
  if (!is_array($cdm_entities)) {
2138
    $cdmBase_array = array();
2139
    $cdmBase_array[] = $cdm_entities;
2140
  }
2141
  else {
2142
    $cdmBase_array = $cdm_entities;
2143
  }
2144

    
2145
  // Getting the key for the footnotemanager.
2146
  if (isset($footnote_list_key_suggestion)) {
2147
    $footnote_list_key = $footnote_list_key_suggestion;
2148
  }
2149
  else {
2150
    $footnote_list_key = RenderHints::getFootnoteListKey() . '-annotations';
2151
  }
2152

    
2153
  // Adding the footnotes keys.
2154
  foreach ($cdmBase_array as $cdmBase_element) {
2155
    $annotations = cdm_ws_getAnnotationsFor($cdmBase_element, variable_get('annotations_types_as_footnotes', $annotations_types_filter));
2156
    if (is_array($annotations)) {
2157
      foreach ($annotations as $annotation) {
2158
        $footNoteKeys[] = FootnoteManager::addNewFootnote($footnote_list_key, $annotation->text);
2159
      }
2160
    }
2161
  }
2162

    
2163
  return $footNoteKeys;
2164
}
2165

    
2166

    
2167
/**
2168
 * Creates a CDM Dynabox.
2169
 *
2170
 * @param string $dynabox_id
2171
 *   a uninque name for tha dynabox, using a cdm entity uuid as id is good practice.
2172
 * @param string $label
2173
 *   The clickable text to show.
2174
 * @param string $content_url
2175
 *   The cdm REST service request url wich will deliver the content to be shown
2176
 *   once the dynabox toggles open.
2177
 * @param string $theme
2178
 *   The theme to be used for rendering the cdm REST service response with is
2179
 *   returned from the $content_url.
2180
 * @param string $link_alt_text
2181
 *   The value for the alt attribute of the dynabox link.
2182
 * @param array $enclosingtags
2183
 *   An array with two elements: $enclosingtags[0] will be used for the dynabox
2184
 *   element itself, $enclosingtags[1] is the tag to be used for the
2185
 *   dynabox_content (optional)
2186
 * @param array $attributes
2187
 * @param $content_element_selector
2188
 *   Optional jQuery selector which can be used to reference a dom element which should
2189
 *   be used as container for the content to be shown. The dynabox-<dynabox id>-content
2190
 *  element will be placed in this container.
2191
 *
2192
 * @param string $open_callback
2193
 *   optional javascript call back function to be triggered after toggling the box to
2194
 *   the open state.
2195
 * @param string $close_callback
2196
 *   optional javascript call back function to be triggered after toggling the box to
2197
 *   the closed state.
2198
 * @return string Returns HTML for a dynabox.
2199
 * Returns HTML for a dynabox.
2200
 */
2201
function cdm_dynabox($dynabox_id, $label, $content_url, $theme, $link_alt_text,
2202
                     $enclosingtags = array('li', 'ul'), $attributes = array(),
2203
                     $content_element_selector = null,
2204
                     $open_callback = 'function(){}', $close_callback = 'function(){}' ) {
2205
  $out = '';
2206

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

    
2210
  if(!array_key_exists('class', $attributes)) {
2211
    $attributes['class'] = array();
2212
  }
2213
  $attributes['id'][] = 'dynabox-' . $dynabox_id;
2214
  $dynabox_attributes = drupal_attributes($attributes);
2215

    
2216

    
2217
  _add_js_domEvent(); // requires domEvent.js
2218
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/cdm_dynabox.js');
2219
  drupal_add_js("
2220
  jQuery(document).ready(
2221
      function() {
2222
        dynabox('". $dynabox_id ."',
2223
          {
2224
            open_callback: " . $open_callback .",
2225
            close_callback: " . $close_callback .
2226
            ($content_element_selector ? ",\n content_container_selector: '" . $content_element_selector . "'" : "") . "
2227
          }
2228
        );
2229
      }
2230
   );",
2231
   array(
2232
    'type'=>'inline',
2233
    'scope'=>'footer'
2234
    )
2235
  );
2236

    
2237

    
2238
  $cdm_proxy_url = url('cdm_api/proxy/' . urlencode($content_url) . "/$theme");
2239
  $out .= '<!-- dynabox for ' . $content_url . ' -->';
2240
  $out .= '<' . $enclosingtags[0] . ' ' .  $dynabox_attributes. '><a href="' . $cdm_proxy_url . '" class="label" alt="' . t($link_alt_text) . '">' . $label . '</a>';
2241
  $out .= '  <' . $enclosingtags[1] . ' id="dynabox-' . $dynabox_id . '-content">';
2242
  $out .= '    <' . $enclosingtags[0] . ' class="dynabox-content-inner">' . loading_image_html() . '</' . $enclosingtags[0] . '>';
2243
  $out .= '    </' . $enclosingtags[1] . '>';
2244
  $out .= '  </' . $enclosingtags[0] . '>';
2245
  $out .= '<!-- dynabox end -->';
2246
  return $out;
2247
}
2248

    
2249
/**
2250
 * Checks whether a feature has any description elements.
2251
 *
2252
 * @param mixed $featureNode
2253
 *   A feature node as produced by the function _mergeFeatureTreeDescriptions().
2254
 *
2255
 * @see _mergeFeatureTreeDescriptions()
2256
 *
2257
 * @return bool
2258
 *   Returns TRUE if the given $featureNode or any of its subordinate nodes
2259
 *   contains at least one non empty TextData or at least one DescriptionElement
2260
 *   of an other type. A TextData element holding a multilanguageText or a
2261
 *   source reference is considered to be not empty.
2262
 *
2263
 * @TODO this function may have become obsolete by the new method of detecting empty blocks,
2264
 *       see $block_content_is_not_empty in compose_feature_blocks() and
2265
 *       $feature_block_has_content in compose_feature_block_items_generic
2266
 */
2267
function has_feature_node_description_elements($featureNode) {
2268

    
2269
  if (isset($featureNode->descriptionElements) && is_array($featureNode->descriptionElements) && count($featureNode->descriptionElements) > 0) {
2270
    if(!isset($featureNode->descriptionElements['#type'])){ // #type is used to identify e.g. DTO elements: '#type' => 'DTO'
2271
      foreach ($featureNode->descriptionElements as $descriptionElement) {
2272
        if ($descriptionElement->class != "TextData" || isset($descriptionElement->multilanguageText_L10n->text)
2273
          && $descriptionElement->multilanguageText_L10n->text != ''
2274
          || isset($descriptionElement->sources[0])
2275
          || isset($descriptionElement->media[0]) ) {
2276
          return TRUE;
2277
        }
2278
      }
2279
    }
2280
  }
2281
  else if (isset($featureNode->childNodes) && is_array($featureNode->childNodes)) {
2282
    foreach ($featureNode->childNodes as $child) {
2283
      if (has_feature_node_description_elements($child)) {
2284
        return TRUE;
2285
      }
2286
    }
2287
  }
2288
  return FALSE;
2289
}
2290

    
2291
/**
2292
 * Checks if the current page is a valid taxon portal page and responds with HTTP status 404 (not found) otherwise
2293
 *
2294
 * @param $chapter
2295
 *   The taxon page chapter or part
2296
 */
2297
function cdm_check_valid_taxon_page($chapter){
2298
  static $taxon_tabs = null;
2299

    
2300
  cdm_check_valid_portal_page();
2301

    
2302
  if($taxon_tabs == null){
2303
    $taxon_tabs = array('all', 'description');
2304
    foreach(get_taxon_tabs_list() as $tab){
2305
      $taxon_tabs[] = strtolower($tab);
2306
    }
2307
  }
2308

    
2309
  if(!in_array($chapter, $taxon_tabs)){
2310
    // oops this is not a valid chapter name
2311
    http_response_code(404); // 404 = Not Found
2312
  }
2313

    
2314
}
2315

    
2316
/**
2317
 * Checks if the current page is a valid portal page and responds with HTTP status 404 (not found) otherwise
2318
 *
2319
 * @param $chapter
2320
 *   The taxon page chapter or part
2321
 */
2322
function cdm_check_valid_portal_page(){
2323
  $ends_with_file_suffix_pattern = '/\/[^\.\/]*[\.][^\.\/]*$/';
2324
  if(preg_match($ends_with_file_suffix_pattern, $_GET['q'])){
2325
    // oops this urls ends with a file_suffix and thus does not refer to a portal page
2326
    http_response_code(404); // 404 = Not Found
2327
    exit('HTTP 404');
2328
  }
2329
}
2330

    
2331
/**
2332
 * Generates the diff of the texts and presents it in a HTML diff viewer.
2333
 *
2334
 * @param $text_a
2335
 * @param $text_b
2336
 * @return string
2337
 */
2338
function diff_viewer($text_a, $text_b) {
2339

    
2340
  static $diff_viewer_count = 0;
2341

    
2342
  $element_id = 'part_definitions_diff_' . $diff_viewer_count++;
2343

    
2344
  // http://code.stephenmorley.org/php/diff-implementation/
2345
  module_load_include('php', 'cdm_dataportal', 'lib/class.Diff');
2346
  drupal_add_css(drupal_get_path('module',
2347
      'cdm_dataportal') . '/css/diff.css');
2348
  _add_jquery_ui();
2349
  drupal_add_js(
2350
    'jQuery(document).ready( function(){
2351
        jQuery(\'#' . $element_id . '\').accordion({
2352
        collapsible: true,
2353
        active: false,
2354
        fillSpace: true,
2355
        }).children(\'div\').css({ \'height\': \'auto\' });
2356
        jQuery(\'#' . $element_id . ' table.diff\').prepend(\'<thead><tr><th>Default</th><th>User defined<th></th><tr></thead>\');
2357
     });'
2358
    , array(
2359
    'type' => 'inline',
2360
    'scope' => 'footer'
2361
  ));
2362

    
2363
  $diff = Diff::compare($text_a,
2364
    $text_b);
2365
  $diff_viewer_markup = '<div id="' . $element_id . '"><h3>View Diff</h3><div>'
2366
    . Diff::toTable($diff, '', '')
2367
    . '</div></div>';
2368
  return $diff_viewer_markup;
2369
}
2370

    
2371

    
(10-10/16)