Project

General

Profile

Statistics
| Branch: | Tag: | Revision:

cdm-dataportal / modules / cdm_dataportal / includes / common.inc @ 92e522db

History | View | Annotate | Download (19.9 KB)

1
<?php
2
/**
3
 * @file
4
 * Functions for dealing with CDM entities from the package model.common
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
 */
18

    
19
/**
20
 * @defgroup compose Compose functions
21
 * @{
22
 * Functions which are composing Drupal render arays
23
 *
24
 * The cdm_dataportal module needs to compose rather complex render arrays from
25
 * the data returned by the CDM REST service. The compose functions are
26
 * responsible for creating the render arrays.
27
 *
28
 * All these functions are also implementations of the compose_hook()
29
 * which is used in the proxy_content() function.
30
 * @}
31
 */
32

    
33
/**
34
 * Compose an render array from a CDM Marker object.
35
 *
36
 * compose_hook() implementation
37
 *
38
 * @param object $marker
39
 *   CDM instance of type Marker
40
 * @return array
41
 *   A drupal render array
42
 *
43
 * @ingroup compose
44
 */
45
function compose_cdm_marker($marker) {
46

    
47
  $render_array = array(
48
      // ---- generic
49
      //  these entries should be common to all cdm enitiy render arrays
50
      '#theme' => 'cdm_marker', // TODO   add alternative theme funcitons: 'cdm_marker_' . marker.type.label
51
      '#attributes' => array('class' => html_class_attribute_ref($marker)),
52

    
53
      // ---- individual
54
      '#label' => $marker->markerType->representation_L10n . ': ' . (($marker->flag !== TRUE ? t('yes') : t('no'))),
55
  );
56

    
57
  return $render_array;
58
}
59

    
60
/**
61
 * Checks if the given $cdm_entitiy has a marker the type references by the
62
 * $marker_type_uuid and returns TRUE if a matching marker has been found.
63
 *
64
 * @param object $cdm_entitiy A CDM Entity
65
 * @param string $marker_type_uuid
66
 */
67
function cdm_entity_has_marker($cdm_entitiy, $marker_type_uuid) {
68
  if(isset($cdm_entitiy->markers[0]) && !is_uuid($marker_type_uuid)){
69
    foreach ($cdm_entitiy->markers as $marker) {
70
      if(isset($marker->markerType) && $marker->markerType->uuid == $marker_type_uuid){
71
        return TRUE;
72
      }
73
    }
74
  }
75
  return FALSE;
76
}
77

    
78
/**
79
 * Sorts an array of CDM IdentifiableSource instances by 1. by the
80
 * author teams family names and 2. by the publication date.
81
 *
82
 * @param array $sources
83
 *    The array of CDM IdentifiableSource instances
84
 * @return array
85
 *  An array of drupal render arrays
86
 */
87
function oder_and_render_original_sources($sources){
88
    $sort_array = array();
89
    foreach ($sources as $source) {
90

    
91
      $order_key = '';
92

    
93
      // find the familynames
94
      if(isset($source->citation->uuid) && !isset($source->citation->authorship)){
95
        $authorteam = cdm_ws_get(CDM_WS_REFERENCE_AUTHORTEAM, $source->citation->uuid);
96

    
97
        $persons = array();
98
        if($authorteam->class == 'Team'){
99
          if(isset($authorteam->teamMembers)){
100
            $persons = $authorteam->teamMembers;
101
          }
102
        } else {
103
          $persons[] = $authorteam;
104
        }
105

    
106
        foreach($persons as $person){
107
          if(!empty($person->lastname)){
108
            $order_key .= $person->lastname;
109
          } else {
110
            $order_key .= $person->titleCache;
111
          }
112
        }
113
        if(empty($order_key)){
114
          $order_key = $authorteam->titleCache;
115
        }
116

    
117
      }
118
      $order_key = str_pad($order_key, 50);
119

    
120
      // add publication date to the key
121
      if(isset($source->citation->datePublished)){
122
        $order_key .= '_' . timePeriodAsOrderKey($source->citation->datePublished);
123
      } else {
124
        $order_key .= '_' . "0000";
125
      }
126

    
127
      // padd key until unique
128
      while(array_key_exists($order_key, $sort_array)){
129
        $order_key .= "_";
130
      }
131

    
132
      $sort_array[$order_key] = render_original_source($source);
133
    }
134
    ksort($sort_array);
135
    return array_values ($sort_array);
136
}
137

    
138
/**
139
 * Compare callback to be used in usort to sort image sources of CDM OriginalSource instances.
140
 *
141
 * TODO the compare strategy implemented in oder_and_render_original_sources() is probably better but is not taking the
142
 * originalName into account.
143
 *
144
 * @param $a
145
 * @param $b
146
 */
147
function compare_original_sources($a, $b){
148

    
149
  $a_string = '';
150
  if(isset($a->citation->titleCache)) {
151
    $a_string = $a->citation->titleCache;
152
  }
153
  if((isset($a->nameUsedInSource))){
154
    $a_string .= $a->nameUsedInSource->titleCache;
155
  } elseif (isset($a->originalNameString)){
156
    $a_string .= $a->originalNameString;
157
  }
158

    
159
  $b_string = '';
160
  if(isset($b->citation->titleCache)) {
161
    $b_string = $b->citation->titleCache;
162
  };
163
  if((isset($b->nameUsedInSource))){
164
    $b_string .= $b->nameUsedInSource->titleCache;
165
  } elseif (isset($b->originalNameString)){
166
    $b_string .= $b->originalNameString;
167
  }
168

    
169
  if ($a_string == $b_string) {
170
    return 0;
171
  }
172
  return ($a_string < $b_string) ? -1 : 1;
173
}
174

    
175
/**
176
 * Compare callback to be used in usort to sort image sources of CDM Media instances.
177
 *
178
 * @param $a
179
 * @param $b
180
 */
181
function compare_text_data($a, $b) {
182

    
183
  if ($a->multilanguageText_L10n->text == $b->multilanguageText_L10n->text) {
184
    return 0;
185
  }
186
  return ($a->multilanguageText_L10n->text < $b->multilanguageText_L10n->text) ? -1 : 1;
187
}
188

    
189
  /**
190
   * Compare two different footnotes objects.
191
   *
192
   * The comparison is based on the footnote key. The one which is
193
   * displayed as footnote number.
194
   *
195
   * @param mixed $a
196
   *   Footnote object $a.
197
   * @param mixed $b
198
   *   Footnote object $b.
199
   */
200
  function footnotes_key_compare($a, $b) {
201
    $res = 0;
202
    if (empty($a) || empty($b)) {
203
      return $res;
204
    }
205
    if ($a->keyStr < $b->keyStr) {
206
      $res = -1;
207
    }
208
    elseif ($a->keyStr > $b->keyStr) {
209
      $res = 1;
210
    }
211
    return $res;
212
  }
213

    
214

    
215
/**
216
 * Creates an array suitable to be used in min_max_markup()
217
 * The min max structure is suitable for being used in the context
218
 * of GatheringEvents and StatisticalMeasures (see render_quantitative_statistics())
219
 *
220
 * @return array
221
 */
222
function min_max_array() {
223

    
224
  $min_max = [
225
    'Min' => NULL,
226
    'TypicalLowerBoundary' => NULL,
227
    'Average' => NULL,
228
    'TypicalUpperBoundary' => NULL,
229
    'Max' => NULL,
230
    'Variance' => NULL,
231
    'StandardDeviation' => NULL,
232
  ];
233
  return $min_max;
234
}
235

    
236
/**
237
 * Creates markup from a min max array.
238
 *
239
 * NOTE: use  min_max_array() to create an appropriate array
240
 *
241
 * Internally Min will be translated to TypicalLowerBoundary if no such value is present.
242
 * The same also accounts for Max and TypicalUpperBoundary.
243
 *
244
 * For further details see #3742, #8766
245
 *
246
 * @param $min_max
247
 *  the min-max array
248
 * @param $unit
249
 *  Defaults to no unit
250
 * @return string
251
 */
252
function min_max_markup($min_max, $unit = '') {
253

    
254
  $min_max_markup = '';
255

    
256
  // --- sanitize values
257
  if(min_max_equals($min_max, 'Min', 'TypicalLowerBoundary')){
258
    $min_max['Min'] = NULL;
259
  }
260

    
261
  if(min_max_equals($min_max, 'Max', 'TypicalUpperBoundary')){
262
    $min_max['Max'] = NULL;
263
  }
264

    
265
  if($min_max['TypicalLowerBoundary'] === null && $min_max['Min'] !== null){
266
    $min_max['TypicalLowerBoundary'] = $min_max['Min'];
267
    $min_max['Min'] = NULL;
268
  }
269

    
270
  if($min_max['TypicalUpperBoundary'] === null && $min_max['Max']  !== null){
271
    $min_max['TypicalUpperBoundary'] = $min_max['Max'];
272
    $min_max['Max'] = NULL;
273
  }
274

    
275
  if (min_max_equals($min_max, 'Min', 'Max')) {
276
    $min_max['Average'] = $min_max['Min'];
277
    $min_max['Min'] = NULL;
278
    $min_max['Max'] = NULL;
279
  }
280

    
281
  // --- check for inconsistent cases, eg. only Max and average given
282
  if ($min_max['TypicalLowerBoundary'] === NULL && $min_max['TypicalUpperBoundary']  !== null) {
283
    // min missing
284
    $min_max['TypicalLowerBoundary'] = '?';
285
  }
286
  if ($min_max['TypicalLowerBoundary'] !== null && $min_max['TypicalUpperBoundary'] === NULL) {
287
    // max missing
288
    $min_max['TypicalUpperBoundary'] = '?';
289
  }
290

    
291
  foreach ($min_max as $key => $statistical_val) {
292
    if ($statistical_val !== NULL) {
293
      if ($statistical_val == '?') {
294
        $val_markup = $statistical_val;
295
      } else {
296
        $val_markup = '<span class="'
297
            . html_class_attribute_ref($statistical_val) . ' '
298
            . (isset($statistical_val->type) ? $statistical_val->type->termType : '') . ' ' . $key .'" title="'. $key. '">'
299
            . $statistical_val->_value . '</span>';
300
      }
301

    
302
      if (strlen($min_max_markup)) {
303
        $min_max_markup .= '–';
304
      }
305
      switch ($key) {
306
        case 'Min':
307
        case 'Max':
308
          $val_markup = "($val_markup)";
309
          break;
310
        case 'Variance':
311
          $val_markup = 'σ²=' . $val_markup;
312
          break;
313
        case 'StandardDeviation':
314
          $val_markup = 'σ=' . $val_markup;
315
          break;
316
      }
317
      $min_max_markup .= $val_markup;
318
    }
319
  }
320

    
321

    
322

    
323
  return $min_max_markup . ($unit ? ' ' . $unit : '');
324
}
325

    
326
/**
327
 * Used internally in min_max_markup() do determine equality of min_max values
328
 *
329
 * @param $min_max
330
 * @param $key1
331
 * @param $key2
332
 *
333
 * @return bool
334
 */
335
function min_max_equals($min_max,  $key1, $key2){
336

    
337
  return $min_max[$key1] !== NULL && $min_max[$key2] !== NULL && $min_max[$key1]->_value ==  $min_max[$key2]->_value;
338
}
339

    
340
/**
341
 * Creates min max markup to represent a min-average-max measure optionally with an error value.
342
 *
343
 * The fields that are taken into account are:
344
 * - field_base_name = min
345
 * - field_base_nameMax = max
346
 * - field_base_nameText = free text
347
 * - field_base_nameError = error value
348
 *
349
 * @param $object
350
 *    The object having min max measurement fields e.g.: GatheringEvent
351
 * @param string $field_base_name
352
 *    The base name for all measurement fields. This name is at the same time the full name of the
353
 *    min value.
354
 * @return string
355
 *   The markup for the min max
356
 */
357
function min_max_measure($object, $field_base_name)
358
{
359
  static $default_unit = 'm';
360

    
361
  $field_name = $field_base_name . 'Text';
362
  if (@is_string($object->$field_name)) {
363
    // Freetext overrides all other data
364
    $min_max_markup = ' ' . $object->$field_name;
365
  } else {
366
    // create markup for the atomized min max data
367
    $min_max_array = min_max_array();
368
    if (@is_numeric($object->$field_base_name)) {
369
      $min_max_array['Min'] = new stdClass();
370
      $min_max_array['Min']->_value = $object->$field_base_name;
371
    }
372
    $field_name = $field_base_name . 'Max';
373
    if (@is_numeric($object->$field_name)) {
374
      $min_max_array['Max'] = new stdClass();
375
      $min_max_array['Max']->_value = $object->$field_name;
376
    }
377
    $min_max_markup = min_max_markup($min_max_array, $default_unit);
378
  }
379

    
380
  return $min_max_markup;
381
}
382

    
383
// TODO  move below code into new file: agent.inc
384

    
385
/*
386
 * Compose an render array from a CDM TaxonNodeAgentRelation object as Taxon Expert.
387
 *
388
 * compose_hook() implementation
389
 *
390
 * @param object $taxon_node_agent_relation
391
 *   CDM instance of type TaxonNodeAgentRelation
392
 * @return array
393
 *   A drupal render array
394
 *
395
 * @ingroup compose
396
 */
397
function compose_cdm_taxon_expert($taxon_node_agent_relation) {
398

    
399
  $label_suffix = ':';
400

    
401
  if($taxon_node_agent_relation->class == 'DefaultPagerImpl'){
402
    // oops this is a pager
403
    // this situation will occur when this compose is executed
404
    // through the proxy_content() method
405
    $taxon_node_agent_relation = $taxon_node_agent_relation->records[0];
406

    
407
  }
408

    
409
  if(is_object($taxon_node_agent_relation->agent)) {
410
    $agent_details = compose_cdm_team_or_person_base($taxon_node_agent_relation->agent);
411
    // all data will be added to the groups of the agent_details render array
412
    $groups = &$agent_details[0]['#groups'];
413

    
414
    @_description_list_group_add($groups, t('Role'). $label_suffix, $taxon_node_agent_relation->type->representation_L10n);
415

    
416
    $family_tnars = cdm_ws_fetch_all(CDM_WS_PORTAL_AGENT . '/' . $taxon_node_agent_relation->agent->uuid . '/taxonNodeAgentRelations', array("rank"=>"Familia"));
417

    
418
    $taxa_markup = array(
419
      '#theme_wrappers' => array('container'),
420
      '#attributes' => array('class' => array('managed_taxa')),
421
      '#wrapper_attributes' => array('class' => 'sublist-container')
422
      );
423
    foreach($family_tnars as $tnar){
424
      if(is_object($tnar->taxonNode->taxon)){
425
        $taxa_markup[$tnar->taxonNode->taxon->titleCache] = markup_to_render_array(render_taxon_or_name($tnar->taxonNode->taxon, url(path_to_taxon($tnar->taxonNode->taxon->uuid))));
426
      }
427
    }
428
    ksort($taxa_markup);
429

    
430
    @_description_list_group_add($groups, t('Families'). $label_suffix, array($taxa_markup));
431

    
432
  }
433

    
434
  return $agent_details;
435
}
436

    
437

    
438
/*
439
 * Compose an render array from a CDM TeamOrPersonBase object.
440
 *
441
 * compose_hook() implementation
442
 *
443
 * TODO: currently mainly implemented for Agent, add Team details
444
 *
445
 * @param object $team_or_person
446
 *   CDM instance of type TeamOrPersonBase
447
 * @return array
448
 *   A drupal render array
449
 *
450
 * @ingroup compose
451
 */
452
function compose_cdm_team_or_person_base($team_or_person, $data = array()) {
453

    
454
  $groups = array();
455

    
456
  $label_suffix = ':';
457

    
458
  // $weight = 0;
459
  if($team_or_person){
460

    
461
    if(is_object($team_or_person->lifespan)){
462
      // ToDo render as date* - date† ?
463
      @_description_list_group_add($groups, t('Lifespan'). $label_suffix, timePeriodToString($team_or_person->lifespan) /*, '' , $weight++ */);
464
    }
465

    
466
    // nomenclaturalTitle
467
    @_description_list_group_add($groups, "Nomenclatural Title". $label_suffix, $team_or_person->nomenclaturalTitle);
468
    // collectorTitle
469
    @_description_list_group_add($groups, "Collector Title". $label_suffix, $team_or_person->collectorTitle);
470

    
471
    // institutionalMemberships
472
    if(is_array($team_or_person->institutionalMemberships)){
473

    
474
      $institutes_ra =  array();
475
      foreach($team_or_person->institutionalMemberships as $membership) {
476
        $membership_groups = array();
477
        @_description_list_group_add($membership_groups, t('Department'). $label_suffix, $membership->department);
478
        @_description_list_group_add($membership_groups, t('Role'). $label_suffix, $membership->role);
479
        if(is_object($membership->period)){
480
          @_description_list_group_add($membership_groups, t('Period'). $label_suffix, timePeriodToString($membership->period));
481
        }
482
        if(is_object($membership->institute->contact)){
483
          $institute_contact_details = compose_cdm_contact($membership->institute->contact, $membership->institute->titleCache);
484
          if(is_array($institute_contact_details[0]['#groups'])){
485
            $membership_groups = array_merge($membership_groups, $institute_contact_details[0]['#groups']);
486
          }
487
        }
488
        if(count($membership_groups) > 0){
489
          $institutes_ra[]  = array(
490
            '#title' => $membership->institute->titleCache,
491
            '#theme' => 'description_list',
492
            '#groups' => $membership_groups,
493
            '#attributes' => array('class' => html_class_attribute_ref($membership)),
494
            '#wrapper_attributes' => array('class' => 'sublist-container')
495
          );
496
        } else {
497
          // no further details for the membership, display the title
498
          $institutes_ra[] = markup_to_render_array('<h3>' . $membership->institute->titleCache . '</h3>');
499
        }
500

    
501
      }
502

    
503
      $label = count($institutes_ra) > 1 ? t('Institutes'):  t('Institute');
504
      @_description_list_group_add($groups, $label. $label_suffix, $institutes_ra /*, '' , $weight++ */);
505
    }
506

    
507

    
508
    // Contact
509
    $agent_contact_details = compose_cdm_contact($team_or_person->contact, $team_or_person->titleCache);
510
    if(is_array($agent_contact_details[0]['#groups'])){
511
      $groups = array_merge($groups, $agent_contact_details[0]['#groups']);
512
    }
513

    
514
    // additional data
515
    foreach($data as $key=>$value){
516
      @_description_list_group_add($sub_dl_groups, t('@key', array('@key' => $key)), $value /*, '' , $weight++ */);
517
    }
518

    
519
  }
520

    
521
  $team_or_person_details = array(
522
    '#title' => $team_or_person->titleCache,
523
    '#theme' => 'description_list',
524
    '#groups' => $groups,
525
    '#attributes' => array('class' => html_class_attribute_ref($team_or_person)),
526
  );
527
  return array($team_or_person_details);
528
}
529

    
530

    
531
/*
532
 * Compose an render array from a CDM Contact object.
533
 *
534
 * compose_hook() implementation
535
 *
536
 * TODO: currently mainly implemented for Agent, add Team details
537
 *
538
 * @param object $contact
539
 *   CDM instance of type Contact
540
 * @param $title
541
 *   The title for the description list header
542
 * @param $weight
543
 *   Optional weight for the description list entries
544
 * @return array
545
 *   A drupal render array
546
 *
547
 * @ingroup compose
548
 */
549
function compose_cdm_contact($contact, $title, $weight = 0)
550
{
551

    
552
  $groups = array();
553

    
554
  $contact_details = null;
555

    
556
  $label_suffix = ':';
557

    
558
  $contact_field_names_map = array(
559
    'emailAddresses' => t('Email'),
560
    'urls' => t('Urls'),
561
    'phoneNumbers' => t('Phone'),
562
    'faxNumbers' => t('Fax'),
563
  );
564

    
565
  // Contact
566
  if(is_object($contact)){
567
    if(isset($contact->addresses)){
568
      // TODO ....
569
      // $sub_groups = array();
570
      // foreach($contact->addresses as $address){
571
      //   @_description_list_group_add($sub_groups, $label, $contact->$fieldName, '', $weight++);
572
      // }
573
    }
574
    foreach($contact_field_names_map as $fieldName => $label){
575
      if(is_array($contact->$fieldName)){
576
        @_description_list_group_add($groups, $label . $label_suffix, $contact->$fieldName, '', $weight++);
577
      }
578
    }
579
    $contact_details = array(
580
      '#title' => $title,
581
      '#theme' => 'description_list',
582
      '#groups' => $groups
583
    );
584

    
585

    
586
  } else if(is_string($title)) {
587
    // if the contact entity is empty but the title is given anyway
588
    // we are only adding the title, using the description_list
589
    // structure is not possible since it would be empty due to
590
    // missing group data
591
    $contact_details = array('#markup' => '<h3>' . $title . '</h3>');
592
  }
593

    
594
  return array($contact_details);
595

    
596
}
597

    
598
/**
599
 * Compose an render array from a CDM Extension objects.
600
 *
601
 * @param $extensions
602
 *    An array of CDM Extension objects
603
 * @return array
604
 *   A render array containing the fields of the supplied $sequence
605
 *
606
 * @ingroup compose
607
 */
608
function compose_extensions($extensions)
609
{
610
  $extensions_render_array= null;
611
  $extensions_by_type = array();
612
  foreach ($extensions as $extension) {
613
    if (@is_string($extension->value)) {
614
      if (!isset($extensions_by_type[$extension->type->representation_L10n])) {
615
        $extensions_by_type[$extension->type->representation_L10n] = array();
616
      }
617
      $extensions_by_type[$extension->type->representation_L10n][] = markup_to_render_array($extension->value);
618
    }
619
  }
620

    
621
  if (count($extensions_by_type)) {
622
    $sub_dl_groups = array();
623
    foreach ($extensions_by_type as $type_label => $text_list) {
624
      @_description_list_group_add($sub_dl_groups, $type_label . ':', $text_list);
625
    }
626
    $extensions_render_array = array(
627
      array('#theme' => 'description_list', '#groups' => $sub_dl_groups)
628
    );
629
    return $extensions_render_array;
630
  }
631
  return $extensions_render_array;
632
}
633

    
634
function formatParams($params) {
635
    if (is_array($params)){
636
        $keys =array_keys($params);
637
        $paramString = '';
638
        foreach ($keys as $k ){
639
            if ($k != 'pageNumber' && $k != 'pageSize'){
640
                $paramString .= ' -'.$k.'='.urlencode($params[$k]);
641
            }
642
        }
643
    }
644
    return $paramString;
645
}
646

    
647
function formatWSParams($params) {
648
    if (is_array($params)){
649
        $keys =array_keys($params);
650
        $paramString = '';
651
        foreach ($keys as $k ){
652
            if ($k != 'pageNumber' && $k != 'pageSize'){
653
                $paramString .= '&'.$k.'='.urlencode($params[$k]);
654
            }
655
        }
656
    }
657
    return $paramString;
658
}
659

    
660
/**
661
 *
662
 * @param $cdm_entity
663
 *
664
 * @return string the markup
665
 */
666
function render_cdm_entity_link($cdm_entity) {
667

    
668
  switch ($cdm_entity->class) {
669
    case 'TaxonDescription':
670
      $link =  '<span class="' . html_class_attribute_ref($cdm_entity) . '">' . $cdm_entity->titleCache . '</span> ' . icon_link(path_to_description($cdm_entity->uuid));
671
      break;
672
    default:
673
      $link = '<span class="error">UNSUPPORTED CDM ENTITY TYPE</span>';
674
  }
675
  return $link;
676
}
677

    
678
/**
679
 * Creates an icon which links to the given path
680
 * @param $path
681
 *
682
 * @return string
683
 */
684
function icon_link($path, $fragment = '') {
685
  $iconlink = l(custom_icon_font_markup('icon-interal-link-alt-solid', ['class' => ['superscript']]), $path, ['html' => TRUE, 'fragment' => $fragment] );
686
  return $iconlink;
687
}
Add picture from clipboard (Maximum size: 40 MB)