Project

General

Profile

Download (36.9 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/**
3
 * @file
4
 * Displays a taxon tree in 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
/**
21
 * Implements hook_menu() 
22
 */
23
function cdm_taxontree_menu() {
24

    
25
  $items = array();
26

    
27
  $items['cdm_taxontree/set'] = array(
28
    'page callback' => 'cdm_taxontree_set',
29
    'access arguments' => array('access cdm content'),
30
    'type' => MENU_CALLBACK,
31
  );
32

    
33
  $items['cdm_taxontree/filter'] = array(
34
    'page callback' => 'cdm_taxontree_view_filter',
35
    'access arguments' => array('access cdm content'),
36
    'type' => MENU_CALLBACK,
37
  );
38

    
39
  $items['cdm_taxontree/taxonomy/children'] = array(
40
    'page callback' => 'cdm_taxontree_taxonomy_children',
41
    'access arguments' => array('access cdm content'),
42
    'type' => MENU_CALLBACK,
43
  );
44

    
45

    
46
  return $items;
47
}
48

    
49
/**
50
 * Implements hook_block_info().
51
 */
52
function cdm_taxontree_block_info() {
53
  $block['cdm_tree'] = array(
54
        "info" => t('CDM taxon tree'),
55
        "cache" => DRUPAL_NO_CACHE
56
      );
57

    
58
  $block['cdm_tree_filters']['info'] = t('Active filters');
59
  $block['cdm_tree_drupal_taxonomy']['info'] = t('Drupal taxonomy tree');
60
  return $block;
61
}
62

    
63
/**
64
 * Implements hook_block_view().
65
 */
66
function cdm_taxontree_block_view($delta) {
67

    
68
  switch ($delta) {
69
    case 'cdm_tree':
70
      $block['subject'] = t('Classification');
71
      $taxonUuid_inFocus = _cdm_get_taxonuuid();
72
      $tree = cdm_taxontree_build_tree($taxonUuid_inFocus);
73

    
74
      // cdm_taxontree_magicbox_enable is not yet made available via the settings, so $magicbox_enable is always 0
75
      $magicbox_enable = variable_get('cdm_taxontree_magicbox_enable', 0);
76

    
77
      $block['content'] = '';
78
      $taxonomictree_selector_form = cdm_taxonomictree_selector();
79
      if (count($taxonomictree_selector_form['val']['#options']) > 1) {
80
        $block['content'] = drupal_render($taxonomictree_selector_form);
81
      }
82
      $block['content'] .= theme('cdm_taxontree_block', array(
83
        'tree' => $tree,
84
        'delta' => $delta,
85
        'magicbox' => $magicbox_enable == 1,
86
        'show_filter_switch' => FALSE,
87
        // 'cdm_taxontree_node_concept_switch'
88
       ));
89
      cdm_taxontree_add_js('#block-cdm-taxontree-cdm-tree', $magicbox_enable);
90
      return $block;
91

    
92
    case 'cdm_tree_filters':
93
      $block['subject'] = t('Active filters');
94
      $block['content'] = cdm_taxontree_view_filter('list');
95
      return $block;
96

    
97
    case 'cdm_tree_drupal_taxonomy':
98
      // cdm tree for a drupal taxonomy
99
      $block['subject'] = t('Taxonomy tree');
100
      $term_inFocus = arg(0) == 'taxonomy' && arg(1) == 'term' ? arg(2) : 0;
101
      $tree = cdm_taxontree_build_tree($term_inFocus, TRUE, variable_get('cdm_taxontree_block_1_vid', 0));
102
      $block['content'] = theme('cdm_taxontree_block', array(
103
        'tree' => $tree,
104
        'delta' => $delta,
105
        'magicbox' => FALSE,
106
      ));
107
      cdm_taxontree_add_js('#block-cdm-taxontree-cdm-tree-drupal-taxonomy');
108
      return $block;
109

    
110
  }
111
}
112

    
113
/**
114
 * Implements hook_block_configure().
115
 */
116
function cdm_taxontree_block_configure($delta) {
117
  // TODO Rename block deltas (e.g. '1') to readable strings.
118
  if (TRUE) {
119
    switch ($delta) {
120
      case '1':
121
        $vocs = taxonomy_get_vocabularies();
122
        $options = array();
123
        foreach ($vocs as $voc) {
124
          $options[$voc->vid] = $voc->name;
125
        }
126
        $form['vid'] = array(
127
          '#type' => 'select',
128
          '#title' => t('Category'),
129
          '#default_value' => variable_get('cdm_taxontree_block_1_vid', 0),
130
          '#options' => $options,
131
        );
132
        return $form;
133
    }
134
  }
135
}
136

    
137
/**
138
 * Implements hook_block_save().
139
 */
140
function cdm_taxontree_block_save($delta, $edit) {
141
  // TODO Rename block deltas (e.g. '1') to readable strings.
142
  if (TRUE) {
143
    switch ($delta) {
144
      case '1':
145
        variable_set('cdm_taxontree_block_1_vid', $edit['vid']);
146
        return;
147
    }
148
  }
149
}
150

    
151
/**
152
 * Implements hook_help().
153
 */
154
function cdm_taxontree_help($path, $arg) {
155
  switch ($path) {
156
    case 'admin/modules#description':
157
      return t('Defines a selection widget for massive taxonomy structures.');
158
  }
159
}
160

    
161
/**
162
 * Implements hook_field_info().
163
 */
164
function cdm_taxontree_field_info() {
165
  return array(
166
    'cdm_taxontree' => array('label' => 'CDM Taxontree'),
167
  );
168
}
169

    
170
/**
171
 * @todo Please document this function.
172
 * @see http://drupal.org/node/1354
173
 */
174
function cdm_taxontree_field_formatter_info() {
175
  return array(
176
    'default' => array(
177
      'label' => t('Default'),
178
      'field types' => array('cdm_taxontree'),
179
    ),
180
    'link' => array(
181
      'label' => t('With link'),
182
      'field types' => array('cdm_taxontree'),
183
    ),
184
  );
185
}
186

    
187
/**
188
 * Formatters to prepare the correct links for taxa.
189
 */
190
function cdm_taxontree_field_formatter($field, $item, $formatter, $node) {
191
  switch ($formatter) {
192
    case 'link':
193
      $term = taxonomy_term_load($item['tid']);
194
      $taxa = db_query('SELECT name FROM {taxonomy_vocabulary} WHERE vid = :vid', array(':vid' => $term->vid))->fetchField();
195
      switch ($taxa) {
196
        case 'Taxonomy':
197
          $link = 'interest_by_taxonomy/';
198
          break;
199

    
200
        case 'Georegion':
201
          $link = 'interest_by_georegion/';
202
          break;
203

    
204
        default:
205
          $link = 'taxonomy/term/';
206
      }
207
      return l($term->name, $link . $term->tid);
208

    
209
    default:
210
      $name = db_query('SELECT name FROM {taxonomy_term_data} WHERE tid = :tid', array(':tid' => $item['tid']))->fetchField();
211
      return $name;
212
  }
213
}
214

    
215

    
216
/**
217
 * Transforms an unpredictably and irregularly nested set of tids (as returned
218
 * from a taxonomy form) into a linear array of tids.
219
 * borrow from taxonomy_browser.module
220
 */
221
function _cdm_taxontree_get_all_children($tids = NULL, $include_children = FALSE) {
222
  static $tid_list = array();
223

    
224
  if (isset($tids) && is_array($tids)) {
225

    
226
    foreach ($tids as $key => $tid) {
227
      if (!empty($tid)) {
228
        if (is_array($tid)) {
229
          foreach ($tid as $key2 => $tid2) {
230
            if (!empty($tid2)) {
231
              $tid_list[$tid2] = $tid2;
232
            }
233
          }
234
        }
235
        else {
236
          $tid_list[$tid] = $tid;
237
        }
238
      } /* end !empty */
239
    } /* end foreach */
240
  }
241

    
242
  if ($include_children) {
243
    foreach ($tid_list as $tid) {
244
      _cdm_taxontree_get_children($tid_list, $tid);
245
    }
246
  }
247

    
248
  return $tid_list;
249
}
250

    
251
/**
252
 * @todo Please document this function.
253
 * @see http://drupal.org/node/1354
254
 */
255
function _cdm_taxontree_get_children(&$tid_list, $tid) {
256
  $child_nodes = taxonomy_get_children($tid);
257
  if (!empty($child_nodes)) {
258
    foreach ($child_nodes as $child_tid => $child_term) {
259
      $tid_list[$tid] = $tid;
260
      _cdm_taxontree_get_children($tid_list, $child_tid);
261
    }
262
  }
263
  else {
264
    $tid_list[$tid] = $tid;
265
  }
266
}
267

    
268
/**
269
 * @todo Please document this function.
270
 * @see http://drupal.org/node/1354
271
 */
272
function cdm_taxontree_set($key, $value) {
273
  if (is_string($key)) {
274
    $_SESSION['cdm']['taxontree'][$key] = $value;
275
  }
276

    
277
  if ($_GET['destination']) {
278
    $destination = $_GET['destination'];
279
    unset($_GET['destination']);
280
    drupal_goto($destination);
281
  }
282
}
283

    
284
/**
285
 * Enter description here...
286
 *
287
 * @param string $secUuid
288
 *
289
 * @return unknown
290
 */
291
function cdm_taxontree_secRefTitle_for($secUuid) {
292

    
293
  $reference = cdm_api_secref_cache_get($secUuid);
294
  if ($reference) {
295
    $cit = $reference->titleCache;
296
  }
297
  else {
298
    $cit = '[no title for:' . $secUuid . ']';
299
  }
300
  return $cit;
301
}
302

    
303
/**
304
 * Queries the Drupal db for location of a certain block with the given $delta.
305
 *
306
 * @param mixed $delta
307
 *   String or number identifying the block.
308
 *
309
 * @return string
310
 *   The location: left, right or <empty>.
311
 */
312
function _get_block_region($delta) {
313
  global $user, $theme_key;
314
  // Comment @WA you need to repace this with db_select if other modules
315
  // should be able to overrride this.
316
  $result = db_query("
317
    SELECT DISTINCT b.region
318
    FROM {block} b
319
    LEFT JOIN {block_role} r
320
    ON b.module = r.module
321
    AND b.delta = r.delta
322
    WHERE b.theme = :b.theme
323
    AND b.status = :b.status
324
    AND (r.rid IN (:r.rid) OR r.rid IS NULL)
325
    AND b.module = :b.module
326
    AND b.delta = :b.delta
327
  ", array(
328
    ':b.theme' => $theme_key,
329
    ':b.status' => 1,
330
    ':r.rid' => implode(',', array_keys($user->roles)),
331
    ':b.module' => 'cdm_taxontree',
332
    ':b.delta' => $delta,
333
  ))->fetch();
334
  return $result['region'];
335
}
336

    
337
/**
338
 * Enter description here...
339
 *
340
 * @return unknown
341
 */
342
function _get_compact_mode() {
343
  if (!isset($_SESSION['cdm']['taxontree']['compact_mode'])) {
344
    $_SESSION['cdm']['taxontree']['compact_mode'] = 'expanded';
345
  }
346
  return $_SESSION['cdm']['taxontree']['compact_mode'];
347
}
348

    
349
/**
350
 * Converts Drupal taxonomy terms into preliminary cdm tree nodes.
351
 *
352
 * An array of drupal taxonomy terms are converted into an
353
 * array of partially instantiated cdm tree nodes by adding the fields
354
 * relevant for tree node processing in cdm_taxontree.
355
 *
356
 * term => cdm tree node
357
 * ------------------------------------
358
 * tid -> uuid
359
 * name -> titleCache
360
 * taggedName
361
 * secUuid
362
 * isAccepted
363
 * taxonomicChildrenCount
364
 * alternativeConceptRefs
365
 *
366
 * @param array $terms
367
 */
368
function cdm_taxontree_terms2treenodes(&$terms) {
369
  foreach ($terms as &$term) {
370
    $term->uuid = $term->tid;
371
    $term->titleCache = $term->name;
372
    $term->taxonomicChildrenCount = count(taxonomy_get_children($term->tid, $term->vid));
373
  }
374
  return $terms;
375
}
376

    
377
/**
378
 * Enter description here...
379
 *
380
 * @param unknown_type $tid
381
 * @param unknown_type $vid
382
 * @param unknown_type $theme
383
 */
384
function cdm_taxontree_taxonomy_children($tid, $vid, $theme) {
385
  $args = func_get_args();
386
  $tid = array_shift($args);
387
  $vid = array_shift($args);
388
  $theme = array_shift($args);
389

    
390
  $children = cdm_taxontree_get_children($tid, $vid);
391
  $children = cdm_taxontree_terms2treenodes($children);
392
  array_unshift($args, $theme, $children);
393
  print call_user_func_array('theme', $args);
394
}
395

    
396
/**
397
 * Get the root level of the tree
398
 */
399
function cdm_taxontree_get_root($vid = NULL) {
400
  if (is_numeric($vid)) {
401
    // vid, $parent = 0, $depth = -1, $max_depth = NULL) {
402
    $terms = taxonomy_get_tree($vid, 0, 1);
403
    return cdm_taxontree_terms2treenodes($terms);
404
  }
405
  else {
406
    return cdm_ws_taxonomy_root_level();
407
  }
408
}
409

    
410
/**
411
 * @todo Enter description here...
412
 *
413
 * @param unknown_type $uuid
414
 * @param unknown_type $vid
415
 *
416
 * @return unknown
417
 */
418
function cdm_taxontree_get_children($uuid, $vid = NULL) {
419

    
420
  if (is_numeric($vid)) {
421
    $terms = taxonomy_get_children($uuid, $vid);
422
    return cdm_taxontree_terms2treenodes($terms);
423
  }
424
  else {
425
    // FIXME Replace $uuid by path of parent $uuids.
426
    return cdm_ws_taxonomy_root_level($uuid);
427
  }
428
}
429

    
430
/**
431
 * @todo Enter description here...
432
 *
433
 * @param unknown_type $uuid
434
 *
435
 * @return unknown
436
 */
437
function cdm_taxontree_get_parents($uuid) {
438

    
439
  if (!is_uuid($uuid)) {
440
    // Using Drupal taxonomy.
441
    $terms = taxonomy_get_parents($uuid);
442
    array_push($terms, taxonomy_term_load($uuid));
443
    $terms = array_reverse($terms);
444
    return cdm_taxontree_terms2treenodes($terms);
445
  }
446
  else {
447
    // Using cdm.
448
    $terms = cdm_ws_taxonomy_pathFromRoot($uuid);
449
    if (!$terms) {
450
      return;
451
    }
452
    $terms = array_reverse($terms);
453
    return $terms;
454
  }
455
}
456

    
457
/**
458
 * Builds a tree of TaxonNode instances
459
 *
460
 * When building the tree, the instances are extended by some fields:
461
 *  - $node->filter: values ( 'on', 'excluded', 'included' )
462
 *  - $node->expanded: values ( 'expanded', 'collapsed' )
463
 *
464
 * @param string $taxonUuid
465
 *
466
 * @return unknown
467
 */
468
function cdm_taxontree_build_tree($taxonUuid = NULL, $hideOtherConcepts = TRUE, $vid = NULL) {
469
  // TODO Remove $hideOtherConcepts from method signature.
470
  if (is_null($vid)) {
471
    if ($taxonUuid) {
472
      $taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON, $taxonUuid);
473
    }
474

    
475
    $compact_tree = cdm_taxontree_filters_active() && _get_compact_mode() != 'expanded';
476
  }
477
  // Valid compact_modes: 'expanded', 'compact', 'flattened'.
478
  // Get the root level.
479
  $root_tree = cdm_taxontree_get_root($vid);
480
  /*
481
  if(!$root_tree || !is_array($root_tree)){
482
    return array();
483
  }
484
  */
485
  $root_tree = _cdm_resultset2nodelist($root_tree, cdm_taxontree_filters_active());
486

    
487
  if (cdm_taxontree_filters_active()) {
488
    // The paths up to active filters are inactive in the user interface and
489
    // thus cannot be browsed by expanding nodes.
490
    // Therefore we need to build up the branches for all nodes which are set
491
    // as filters. The branches are merged with the root.
492
    foreach (cdm_taxontree_filters_get() as $uuid => $filter) {
493
      $branch = cdm_taxontree_build_path($uuid, TRUE, ($compact_tree === FALSE ? TRUE : NULL));
494
      $root_tree = _cdm_taxontree_merge($root_tree, $branch);
495
    }
496
  }
497

    
498
  // Build the the branch for the focused node and merge it with the root.
499
  if ($taxonUuid) {
500
    $taxon_in_current_tree = taxon_in_current_classification($taxonUuid);
501
    if ($taxon_in_current_tree) {
502
      $branch = cdm_taxontree_build_path($taxonUuid, NULL, (cdm_taxontree_filters_active() ? NULL : TRUE));
503
      $root_tree = _cdm_taxontree_merge($root_tree, $branch);
504
    }
505
  }
506

    
507
   // Reorder siblings & populate expanded nodes with children and propagate
508
   // the filter attribute.
509
   $root_tree = cdm_taxontree_populate($root_tree, $compact_tree === FALSE);
510

    
511
  // Flatten tree.
512
  if ($compact_tree) {
513
    if (_get_compact_mode() == 'flattened') {
514
      $root_tree = cdm_taxontree_flatten($root_tree);
515
    }
516
    elseif (_get_compact_mode() == 'compact') {
517
      foreach ($root_tree as $uuid => $node) {
518
        if ($node->filter == 'excluded' && !$node->children) {
519
          unset($root_tree[$uuid]);
520
        }
521
      }
522
    }
523
  }
524

    
525
  return $root_tree;
526
}
527

    
528
/**
529
 * Builds the specific branch path for $taxonUuid.
530
 *
531
 * The branch path reaches from the parent root node of
532
 * $taxonUuid up to $taxonUuid.
533
 *
534
 * @param string $taxonUuid
535
 *   The UUID of the taxon.
536
 * @param bool $is_filter_path
537
 *   Whether the upmost node of this path is mapped by an active filter.
538
 * @param bool $is_expanded
539
 *   Whether all nodes along the tree are expanded.
540
 *
541
 * @return mixed
542
 *   A subtree.
543
 */
544
function cdm_taxontree_build_path($taxonUuid, $is_filter_path = NULL, $is_expanded = NULL) {
545

    
546
  $branch_path = array();
547

    
548
  $parents = cdm_taxontree_get_parents($taxonUuid);
549
  if (!$parents) {
550
    if ($is_filter_path) {
551
      // \remove invalid filter.
552
      cdm_taxontree_filters_remove($taxonUuid);
553
    }
554
    return FALSE;
555
  }
556

    
557
  $parents = _cdm_resultset2nodelist($parents, NULL);
558
  $lastParent = NULL;
559

    
560
  foreach ($parents as $pnode) {
561
    if ($lastParent) {
562
      $pnode->children = array($lastParent->taxonUuid => $lastParent);
563
      if (!is_null($is_filter_path)) {
564
        $pnode->filter = ($is_filter_path ? 'excludes' : 'included');
565
      }
566
      if (!is_null($is_expanded)) {
567
        $pnode->expanded = ($is_expanded ? 'expanded' : 'collapsed');
568
      }
569
    }
570
    else {
571
      // The uppermost node of branch.
572
      if (!is_null($is_filter_path)) {
573
        $pnode->filter = ($is_filter_path ? 'on' : 'includes');
574
      }
575
      $pnode->expanded = ($pnode->taxonomicChildrenCount ? 'expanded' : 'collapsed');
576
    }
577
    $lastParent = $pnode;
578
  }
579
  $branch_path[$pnode->taxonUuid] = $pnode;
580
  return $branch_path;
581
}
582

    
583
/**
584
 * Order a tree and populate expanded nodes.
585
 *
586
 * Performs two steps on each level of the tree:
587
 *  1. Reorder siblings except root (which is expected to be ordered already)
588
 *     alphabetically.
589
 *  2. Populate children of expanded nodes  & propagate the filter attribute
590
 *
591
 * @param array $tree
592
 * @param unknown $expand_excluded
593
 * @param unknown $filter_default
594
 *
595
 * @return unknown
596
 */
597
function cdm_taxontree_populate($tree, $expand_excluded, $filter_default = NULL) {
598

    
599
  if (!is_array($tree)) {
600
    return FALSE;
601
  }
602
  foreach (array_keys($tree) as $uuid) {
603

    
604
    if (!isset($tree[$uuid]->filter)) {
605
      $tree[$uuid]->filter = $filter_default;
606
    }
607

    
608
    if (isset($tree[$uuid]->expanded) && $tree[$uuid]->expanded == 'expanded' && ($expand_excluded || $tree[$uuid]->filter != 'excluded')) {
609

    
610
      if (isset($tree[$uuid]->vid)) {
611
        $children = cdm_taxontree_get_children($uuid, $tree[$uuid]->vid);
612
      }
613
      else {
614
        $children = cdm_taxontree_get_children($uuid);
615
      }
616
      $children = _cdm_resultset2nodelist($children, ($tree[$uuid]->filter == 'excludes'));
617

    
618
      // Store the children of the node for later processing.
619
      if (isset($tree[$uuid]->children) && is_array($tree[$uuid]->children)) {
620
        $pnode_children = $tree[$uuid]->children;
621
      }
622
      else {
623
        $pnode_children = FALSE;
624
      }
625
      // Replace the children by the newly retrieved child nodes.
626
      $tree[$uuid]->children = $children;
627

    
628
      if ($pnode_children) {
629
        // Recurse into the childtree which was stored before.
630
        $pnode_children = cdm_taxontree_populate($pnode_children, $expand_excluded, $tree[$uuid]->filter);
631
        // Recombine.
632
        foreach ($pnode_children as $childUuid => $cnode) {
633
          $tree[$uuid]->children[$childUuid] = $cnode;
634
        }
635
      }
636
    }
637
    else {
638
      // Reorder nodes which are not expanded, expanded nodes are reordered
639
      // implicitly above.
640
      if (isset($tree[$uuid]->children) && count($tree[$uuid]->children) > 1) {
641
        // Copy the children into an array which can be sorted by its keys.
642
        $ordered = array();
643
        foreach ($tree[$uuid]->children as $cnode) {
644
          // Concatenate full name and uid.
645
          $reordered[str_pad($cnode->titleCache, 255, '-') . $cnode->taxonUuid] = $cnode;
646
        }
647

    
648
        // Sort.
649
        ksort($reordered);
650

    
651
        // Move the children back into the parent node.
652
        $tree[$uuid]->children = array();
653
        foreach ($reordered as $cnode) {
654
          $tree[$uuid]->children[$cnode->taxonUuid] = $cnode;
655
        }
656
      }
657
      if (!isset($tree[$uuid]->children)) {
658
        $tree[$uuid]->children = FALSE;
659
      }
660
      $tree[$uuid]->children = cdm_taxontree_populate($tree[$uuid]->children, $expand_excluded, $tree[$uuid]->filter);
661
    }
662
  }
663
  return $tree;
664
}
665

    
666
/**
667
 * Enter description here...
668
 *
669
 * @param array $tree
670
 *   Tree to flatten.
671
 * @param array $new_root
672
 *
673
 * @return unknown
674
 */
675
function cdm_taxontree_flatten($tree, &$new_root = NULL) {
676
  if (empty($new_root)) {
677
    $new_root = array();
678
  }
679
  foreach ($tree as $node) {
680
    if ($node->filter == 'on') {
681
      $new_root[$node->taxonUuid] = $node;
682
    }
683
    elseif (is_array($node->children)) {
684
      cdm_taxontree_flatten($node->children, $new_root);
685
    }
686
  }
687
  return $new_root;
688
}
689

    
690
/**
691
 * Merge a branch into a tree.
692
 *
693
 * Merge a branch into a tree whereas the tree dominated the branch except
694
 * nodes having property filter set to "on". These always dominate
695
 * nevertheless if they are in tree or branch.
696
 *
697
 * @param array $tree
698
 *   The dominant tree.
699
 * @param array $branch
700
 *   The tree to be merged in.
701
 *
702
 * @return array
703
 *   The merged $tree.
704
 */
705
function _cdm_taxontree_merge($tree, $branch) {
706

    
707
  if (!$branch || !is_array($branch)) {
708
    return $tree;
709
  }
710

    
711
  if (!is_array($tree)) {
712
    return;
713
  }
714

    
715
  foreach (array_keys($tree) as $uuid) {
716
    // Check if node exists in $branch.
717
    if (!empty($branch[$uuid])) {
718
      // Preserve filter property.
719
      if (isset($tree[$uuid]->filter) && !(isset($branch[$uuid]->filter) && $branch[$uuid]->filter == 'on')) {
720
        $branch[$uuid]->filter = $tree[$uuid]->filter;
721
      }
722
      elseif (isset($branch[$uuid]->filter)) {
723
        $tree[$uuid]->filter = $branch[$uuid]->filter;
724
      }
725
      // Preserve expanded property.
726
      if (isset($tree[$uuid]->expanded)) {
727
        $branch[$uuid]->expanded = $tree[$uuid]->expanded;
728
      }
729
      elseif (isset($branch[$uuid]->expanded)) {
730
        $tree[$uuid]->expanded = $branch[$uuid]->expanded;
731
      }
732
      // $Uuid exists check if the node in tree1 or tree2 contains children.
733
      if (isset($branch[$uuid]->children) && is_array($branch[$uuid]->children) && isset($tree[$uuid]->children) && is_array($tree[$uuid]->children)) {
734
        // Merge recursive.
735
        $tree[$uuid]->children = _cdm_taxontree_merge($tree[$uuid]->children, $branch[$uuid]->children);
736
      }
737
      elseif (isset($branch[$uuid]->children) && is_array($branch[$uuid]->children)) {
738
        $tree[$uuid] = $branch[$uuid];
739
      }
740
      unset($branch[$uuid]);
741
    }
742
  }
743
  // Append remaining items from branch to tree.
744
  foreach (array_keys($branch) as $uuid) {
745
    $tree[$uuid] = $branch[$uuid];
746
  }
747
  return $tree;
748
}
749

    
750

    
751
/**
752
 * Alter a resultset into an array of TreeNode instances with taxonUuid as keys.
753
 *
754
 * Replaces the keys of an array of TreeNode instances
755
 * by the $treenode->taxonUuid of the single array elements and sets
756
 * additional fields.
757
 *
758
 * @param array $resultset
759
 *   Array of TreeNode instances as +returned by the cdm web service.
760
 * @param mixed $excluded
761
 *   Whether the $resultset is included by a active filter. Is ignored if NULL.
762
 * @param mixed $expanded
763
 *   Whether the children of the nodes in the $resultset are expanded or not.
764
 *   Is ignored if NULL.
765
 *
766
 * @return array
767
 *   A tree of TreeNode instances with altered keys.
768
 */
769
function _cdm_resultset2nodelist($resultset, $excluded = NULL, $expanded = NULL) {
770

    
771
  if (!is_array($resultset)) {
772
    return FALSE;
773
  }
774

    
775
  $tree = array();
776
  foreach ($resultset as $treeNode) {
777
    if (!is_null($excluded)) {
778
      $treeNode->filter = ($excluded ? 'excluded' : 'included');
779
    }
780
    if (!is_null($expanded)) {
781
      $treeNode->expanded = ($expanded ? 'expanded' : 'collapsed');
782
    }
783
    $tree[$treeNode->taxonUuid] = $treeNode;
784
  }
785
  return $tree;
786
}
787

    
788
/**
789
 * Adds all java script files and also initializes the cdm_taxontree java script behaviours
790
 *
791
 * @param string $parent_element_selector
792
 *    jQuery selector of a parent element of the cdm_taxontree, This is usually a drupal block id
793
 *    selector: #block-cdm-taxontree-cdm-tree or #block-cdm-taxontree-cdm-tree-drupal-taxonomy
794
 *
795
 * @param bool $magicbox_enable
796
 *    If set to TRUE the cdm_taxontree will get the magic box behavoir, which means that it
797
 *    will extend on mouse over events in order to
798
 *    show the entrys without truncation through cropping
799
 */
800
function cdm_taxontree_add_js($parent_element_selector, $magicbox_enable = FALSE) {
801

    
802
  $path_cdm_taxontree = drupal_get_path('module', 'cdm_taxontree');
803
  $path_preferred_module = drupal_get_path('module', 'cdm_dataportal') ? drupal_get_path('module', 'cdm_dataportal') : $path_cdm_taxontree;
804
  drupal_add_css($path_cdm_taxontree . '/cdm_taxontree.css');
805
  drupal_add_js($path_cdm_taxontree . '/js/cdm_taxontree.js');
806

    
807
  drupal_add_js('
808
      jQuery(document).ready(function()
809
      {
810
        jQuery(\'' . $parent_element_selector . '\').cdm_taxontree();
811
      });
812
      ', array('type' => 'inline'));
813
}
814

    
815
// ------------------------ THEME --------------------------- //
816

    
817
/**
818
 *  Returns HTML for a Taxontree block.
819
 *
820
 * @param array $variables
821
 *   An associative array containing:
822
 *   - tree: The tree of TreeNode to be displayed.
823
 *   - magicbox: Boolean. If TRUE, the tree will be embedded into a set of
824
 *       div tags which allow the tree to expand and overlap other content.
825
 *       This is useful if the node titles are quite long or if the tree is
826
 *       nested deeply. If $magicbox ist set to the delta of the containing
827
 *       block the direction into which the box expands is dependent on the
828
 *       region in which the block is located. See also $left_expand_region
829
 *       in this function!
830
 *   - show_filter_switch: The tree can offer buttons to add a node to a set of
831
 *       filters which can then be applied to the tree to limit the visible
832
 *       subtrees and thus to compact the tree. Three different compact modes
833
 *       are available.
834
 *   - tree_node_callback: Name of a callback method which will be called
835
 *       for each node in theme_cdm_taxontree_node(). The output of this
836
 *       callback, which takes the $node object as single arument, is appended
837
 *       to the end of the rendered node.
838
 *
839
 * @ingroup themeable
840
 */
841
function theme_cdm_taxontree_block($variables) {
842
  $tree = $variables['tree'];
843
  $delta = $variables['delta'];
844
  $magicbox = $variables['magicbox'];
845
  $show_filter_switch = $variables['show_filter_switch'];
846
  $tree_node_callback = $variables['tree_node_callback'];
847

    
848
  // THEMERS: change the line below according to the
849
  // specific regions of your theme.
850
  $left_expand_region = 'right';
851

    
852
  $out = '';
853
  if (cdm_taxontree_filters_active()) {
854
    $out .= theme('cdm_taxontree_controller', array('compact_mode' => _get_compact_mode()));
855
  }
856
  $region = null;
857
  if (!empty($magicbox)) {
858
    if (is_numeric($magicbox) || is_string($magicbox)) {
859
      $region = _get_block_region($magicbox);
860
    }
861
    // The magicbox expands to the right by default,
862
    // if the class 'expand-left' to  the cdm_taxontree_scroller_x the box will
863
    // expand to the left.
864
    $expand_direction = ($region == 'right' ? 'expand-left' : '');
865
    $out .= '<div class="cdm_taxontree_scroller_x ' . $expand_direction . '"><div class="cdm_taxontree_container"><div class="cdm_taxontree_scroller_y">';
866
  }
867
  else {
868
    $out .= '<div class="cdm_taxontree_scroller_xy">';
869
  }
870

    
871
  $out .= theme('cdm_taxontree', array(
872
    'tree' => $tree,
873
    'filterIncludes' => !cdm_taxontree_filters_active(),
874
    'show_filter_switch' => $show_filter_switch,
875
    'tree_node_callback' => $tree_node_callback,
876
    ));
877

    
878
  if ($magicbox) {
879
    $out .= '</div></div></div>';
880
  }
881
  else {
882
    $out .= '</div>';
883
  }
884
  return $out;
885
}
886

    
887
/**
888
 * @todo Please document this function.
889
 * @see http://drupal.org/node/1354
890
 */
891
function theme_cdm_taxontree_controller($variables) {
892
  $compact_mode = $variables['compact_mode'];
893

    
894
  static $modes = array('expanded', 'compact', 'flattened');
895

    
896
  $out = '<div class="settings">';
897
  foreach ($modes as $mode) {
898
    if ($compact_mode == $mode) {
899
      $out .= t('@mode', array('@mode' => $mode));
900
    }
901
    else {
902
      $out .= l(t('@mode', array('@mode' => $mode)), 'cdm_taxontree/set/compact_mode/' . $mode, array('query' => drupal_get_destination()));
903
    }
904
    $out .= ' ';
905
  }
906

    
907
  return $out . '</div>';
908
}
909

    
910
/**
911
 * @todo Please document this function.
912
 * @see http://drupal.org/node/1354
913
 */
914
function theme_cdm_taxontree($variables) {
915
  $tree = $variables['tree'];
916
  $filterIncludes = $variables['filterIncludes'];
917
  $show_filter_switch = $variables['show_filter_switch'];
918
  $tree_node_callback = $variables['tree_node_callback'];
919
  $element_name = $variables['element_name'];
920

    
921
  if(isset($tree->records)){
922
    // unwrap from pager object
923
    $tree = $tree->records;
924
  }
925

    
926
  if (!is_array($tree)) {
927
    return FALSE;
928
  }
929

    
930
  if (is_null($filterIncludes)) {
931
    // Set $filterIncludes TRUE if no filters are set.
932
    $filterIncludes = !cdm_taxontree_filters_active();
933
  }
934

    
935
  // Append element name to get multiple taxontrees on one page working.
936
  $out = '<ul class="taxon-nodes ' . (($element_name) ? ' ' . $element_name : '') . '">';
937
  foreach ($tree as $node) {
938
    if($node == null){
939
      continue;
940
    }
941
    $out .= theme('cdm_taxontree_node', array(
942
      'node' => $node,
943
      'filterIncludes' => $filterIncludes,
944
      'show_filter_switch' => $show_filter_switch,
945
      'tree_node_callback' => $tree_node_callback
946
      ));
947
  }
948
  $out .= '</ul>';
949
  return $out;
950
}
951

    
952
/**
953
 * @todo Please document this function.
954
 * @see http://drupal.org/node/1354
955
 */
956
function theme_cdm_taxontree_node($variables) {
957
  $node = $variables['node'];
958
  $filterIncludes = $variables['filterIncludes'];
959
  $show_filter_switch = $variables['show_filter_switch'];
960
  $tree_node_callback = $variables['tree_node_callback'];
961

    
962
  $is_leaf = !$node->taxonomicChildrenCount || $node->taxonomicChildrenCount == 0;
963
  $is_expanded = isset($node->expanded) && $node->expanded = 'expanded';
964

    
965
  $focused_taxon_uuid = get_current_taxon_uuid();
966

    
967
  if (isset($node->tid)) {
968
    $node_name = $node->name;
969
    $path = "taxonomy/term/" . $node->tid;
970
    // disable filterswitch
971

    
972
    $show_filter_switch = FALSE;
973

    
974
  }
975
  elseif (module_exists('cdm_dataportal')) {
976
    $node_name = cdm_dataportal_shortname_of($node);
977
    $path = path_to_taxon($node->taxonUuid);
978
  }
979
  else {
980
    $node_name = "module cdm_dataportal missing";
981
    $path = "";
982
  }
983

    
984
  if ($filterIncludes) {
985
    $name = l($node_name, $path);
986
    // No names for terms in filter widget; as discussed with A. Müller.
987
    // $name = '';
988
    $filter_class = 'filter_included';
989
  }
990
  else {
991
    if ($node->filter == 'on') {
992
      $name = l($node_name, $path);
993
      $filter_class = 'filter_on';
994
    }
995
    else {
996
      $name = $node_name;
997
      $filter_class = 'filter_excluded';
998
    }
999
  }
1000
  $nextLevelIncluded = isset($node->filter) && $node->filter == 'on' || $filterIncludes;
1001

    
1002
  $ahah_url = FALSE;
1003
  if (!$is_leaf && !$is_expanded && $filter_class != 'filter_excluded') {
1004
    if (isset($node->tid)) {
1005
      $ahah_url = url('cdm_taxontree/taxonomy/children/' . $node->tid . '/' . $node->vid . '/cdm_taxontree/' . ($nextLevelIncluded ? 1 : 0) . '/' . ($show_filter_switch ? 1 : 0) . '/' . $tree_node_callback);
1006
    }
1007
    elseif (module_exists('cdm_dataportal')) {
1008
      $ws_url = cdm_compose_taxonomy_root_level_path($node->taxonUuid);
1009
      $ahah_url = url('cdm_api/proxy/' . urlencode($ws_url) . '/cdm_taxontree/' . ($nextLevelIncluded ? 1 : 0) . '/' . ($show_filter_switch ? 1 : 0) . '/' . $tree_node_callback);
1010
    }
1011
  }
1012

    
1013
  // List item.
1014
  $out = '<li class="'
1015
    . ($node->taxonUuid == $focused_taxon_uuid ? 'focused ' : '')
1016
    . ($is_leaf ? 'leaf ' : ($is_expanded ? 'expanded ' : 'collapsed '))
1017
    . $filter_class . '"'
1018
    . ($ahah_url ? ' data-cdm-ahah-url="' . $ahah_url . '"' : '')
1019
    . '>';
1020

    
1021
  if ($show_filter_switch) {
1022
    // Filter icon.
1023
    $out .= theme('cdm_taxontree_node_filter_switch', array('node' => $node, 'filter_class' => $filter_class));
1024
  }
1025

    
1026
  // Taxon name.
1027
  $out .= $name;
1028

    
1029
  // Concept_switch or other theme callbacks.
1030
  if ($tree_node_callback) {
1031
     $out .= theme($tree_node_callback, array('node' => $node));
1032
  }
1033

    
1034
  if (isset($node->children) && is_array($node->children)) {
1035
    $out .= theme('cdm_taxontree', array(
1036
      'tree' => $node->children,
1037
      'filterIncludes' => $nextLevelIncluded,
1038
      'show_filter_switch' => $show_filter_switch,
1039
      'tree_node_callback' => $tree_node_callback,
1040
    ));
1041
  }
1042
  $out .= '</li>';
1043

    
1044
  return $out;
1045
}
1046

    
1047
/**
1048
 * @todo Please document this function.
1049
 * @see http://drupal.org/node/1354
1050
 */
1051
function theme_cdm_taxontree_node_filter_switch($variables) {
1052
  $node = $variables['node'];
1053
  $filter_class = $variables['filter_class'];
1054
  if (!module_exists('cdm_dataportal')) {
1055
    return '';
1056
  }
1057

    
1058
  $out = '';
1059
  switch ($filter_class) {
1060
    case 'filter_included':
1061
      $filter_icon = 'visible_implicit_small.gif';
1062
      break;
1063

    
1064
    case 'filter_excluded':
1065
      $filter_icon = 'invisible_small.gif';
1066
      break;
1067

    
1068
    case 'filter_on':
1069
      $filter_icon = 'visible_small.gif';
1070
      break;
1071

    
1072
  }
1073

    
1074
  $filter_op = $node->filter == 'on' ? 'remove' : 'add';
1075

    
1076
  $out .= '&nbsp;'
1077
    . l('<img src="' . base_path() . drupal_get_path('module', 'cdm_taxontree') . '/' . $filter_icon . '" alt="[f]" />',
1078
        'cdm_taxontree/filter/' . $filter_op . '/' . $node->taxonUuid, array(
1079
          'attributes' => array('class' => 'filter_' . $filter_op),
1080
          'query' => 'destination=' . path_to_taxon($node->taxonUuid),
1081
          'fragment' => NULL,
1082
          'absolute' => TRUE,
1083
          'html' => TRUE,
1084
        ));
1085

    
1086
  return $out;
1087
}
1088

    
1089
/**
1090
 * Returns HTML for a Taxontree-node concept switch.
1091
 *
1092
 * @param array $variables
1093
 *   An associative array containing:
1094
 *   - node: The node object.
1095
 *
1096
 * @ingroup themeable
1097
 */
1098
function theme_cdm_taxontree_node_concept_switch($variables) {
1099
  $node = $variables['node'];
1100
  $out = '';
1101

    
1102
  if (isset($node->alternativeConceptRefs[0])) {
1103
    $out = l(
1104
      '<img src="' . base_path() . drupal_get_path('module', 'cdm_taxontree') . '/concept_switch.gif" alt="[-&gt;]" />',
1105
      'cdm_dataportal/taxon/alternative/' . $node->taxonUuid, array(
1106
        'attributes' => array('rel' => 'cdm_dataportal/taxon/alternative/' . $node->taxonUuid, 'class' => 'concept_switch'),
1107
        'query' => NULL,
1108
        'fragment' => NULL,
1109
        'absolute' => TRUE,
1110
        'html' => TRUE,
1111
      ));
1112
  }
1113
  return $out;
1114
}
1115

    
1116
/**
1117
 * @todo Please document this function.
1118
 * @see http://drupal.org/node/1354
1119
 */
1120
function cdm_taxontree_theme() {
1121
  return array(
1122
    'cdm_taxontree' => array('variables' => array(
1123
      'tree' => NULL,
1124
      'filterIncludes' => NULL,
1125
      'show_filter_switch' => FALSE,
1126
      'tree_node_callback' => FALSE,
1127
      'element_name' => FALSE
1128
      )),
1129
    'cdm_taxontree_block' => array('variables' => array(
1130
      'tree' => NULL,
1131
      'delta' => NULL,
1132
      'magicbox' => FALSE,
1133
      'show_filter_switch' => FALSE,
1134
      'tree_node_callback' => FALSE,
1135
      )),
1136
    'cdm_taxontree_controller' => array('variables' => array('compact_mode' => NULL)),
1137
    'cdm_taxontree_node' => array('variables' => array(
1138
      'node' => NULL,
1139
      'filterIncludes' => NULL,
1140
      'show_filter_switch' => FALSE,
1141
      'tree_node_callback' => FALSE
1142
      )),
1143
    'cdm_taxontree_node_concept_switch' => array('variables' => array('node' => NULL)),
1144
    'cdm_taxontree_node_filter_switch' => array('variables' => array('node' => NULL, 'filter_class' => NULL)),
1145
  );
1146
}
1147

    
1148
// ----------------- FILTERS -------------------------- //
1149
/**
1150
 * Filters on children, overrides already set parent filters and vice versa.
1151
 *
1152
 * @param string $op
1153
 *   [add | remove] a taxon from the filtered taxa.
1154
 *   TODO at the moment there is also a 'list' operation that displays all
1155
 *   set filters and provides the ability to delete them.
1156
 *   This option depends on function is defined in cdm_dataportal.
1157
 *   Problem is, that the dependency is the other way round.
1158
 * @param string $taxonUuid
1159
 *
1160
 * @return unknown
1161
 */
1162
function cdm_taxontree_view_filter($op, $taxonUuid = NULL) {
1163

    
1164
  if (!isset($_SESSION['cdm']['filters'])) {
1165
    $_SESSION['cdm']['filters'] = array();
1166
  }
1167
  if ($taxonUuid || $op == 'list') {
1168
    switch ($op) {
1169
      case 'add':
1170
        cdm_taxontree_filters_add($taxonUuid);
1171
        break;
1172

    
1173
      case 'remove':
1174
        cdm_taxontree_filters_remove($taxonUuid);
1175
        break;
1176

    
1177
      case 'list':
1178
        // TODO put in cdm_dataportal_theme to decouple both modules by this!!!
1179
        $out = '<ul>';
1180
        foreach ($_SESSION['cdm']['filters'] as $uuid => $node) {
1181
          $out .= '<li>' . cdm_dataportal_shortname_of($node) . ' ' . l(t('[x]'), 'cdm_dataportal/filter/remove/' . $uuid, array('query' => drupal_get_destination())) . '</li>';
1182
        }
1183
        $out .= '</ul>';
1184
        return $out;
1185
    }
1186
  }
1187
  if ($_GET['destination']) {
1188
    $destination = $_GET['destination'];
1189
    unset($_GET['destination']);
1190
    drupal_goto($destination);
1191
  }
1192
}
1193

    
1194
/**
1195
 * Checks if there are active filters.
1196
 *
1197
 * Filters are set in cdm_dataportal_view_filter().
1198
 * functions using filters should remove invalid filters.
1199
 *
1200
 * @return bool
1201
 *   TRUE if any filter is active.
1202
 */
1203
function cdm_taxontree_filters_active() {
1204
  return isset($_SESSION['cdm']['filters']) && count($_SESSION['cdm']['filters']) > 0;
1205
}
1206

    
1207
/**
1208
 * Filters are set in cdm_dataportal_view_filter().
1209
 *
1210
 * @return mixed
1211
 *   A reference on the filters array stored in the SESSION.
1212
 */
1213
function &cdm_taxontree_filters_get() {
1214
  if (!isset($_SESSION['cdm']['filters'])) {
1215
    $_SESSION['cdm']['filters'] = array();
1216
  }
1217
  return $_SESSION['cdm']['filters'];
1218
}
1219

    
1220
/**
1221
 * Adds a taxon to the filtered taxa array
1222
 *
1223
 * @param UUID $taxonUuid
1224
 */
1225
function cdm_taxontree_filters_add($taxonUuid) {
1226

    
1227
  $parents = cdm_ws_taxonomy_pathFromRoot($taxonUuid);
1228

    
1229
  $parents = array_reverse($parents);
1230

    
1231
  // Pop off last element since this is the TreeNode object for $taxonUuid!
1232
  $this_node = array_pop($parents);
1233

    
1234
  // Will contain the uuid of the parent nodes excluding the
1235
  // $taxonUuid node itself.
1236
  $parent_uuids = array();
1237

    
1238
  // Children override parents rule: remove all parent filters.
1239
  foreach ($parents as $pnode) {
1240
    unset($_SESSION['cdm']['filters'][$pnode->taxonUuid]);
1241
    $parent_uuids[] = $pnode->taxonUuid;
1242
  }
1243

    
1244
  // Search for potential children of this $taxonUuid.
1245
  foreach ($_SESSION['cdm']['filters'] as $uuid => $node) {
1246
    if (in_array($taxonUuid, $node->parentUuids)) {
1247
      unset($_SESSION['cdm']['filters'][$node->taxonUuid]);
1248
    }
1249
  }
1250
  // Finally add this $taxonUuid as new filter.
1251
  $this_node->parentUuids = $parent_uuids;
1252
  $_SESSION['cdm']['filters'][$taxonUuid] = $this_node;
1253
}
1254

    
1255
/**
1256
 * Unsets a taxon from the filtered taxa array.
1257
 *
1258
 * @param string $taxonUuid
1259
 */
1260
function cdm_taxontree_filters_remove($taxonUuid) {
1261
  unset($_SESSION['cdm']['filters'][$taxonUuid]);
1262
}
1263

    
1264
// ------------------------ PRIVATE --------------------------- //
1265
/**
1266
 * Analyses the current Drupal path to get the taxon UUID.
1267
 *
1268
 * If a certain taxon was requested in the request, returns the UUID
1269
 * of that taxon. Returns a stored UUID if no taxon was requested.
1270
 * TODO where does the stored UUID come from?
1271
 *
1272
 * @return string
1273
 *   The taxon id found, or FALSE.
1274
 *
1275
 * @deprecated use get_current_taxon_uuid() instead
1276
 */
1277
function _cdm_get_taxonuuid() {
1278

    
1279
  if (arg(0) == "cdm_dataportal" && arg(1) == "taxon" && arg(2) !== 0) {
1280
    $taxon_uuid = arg(2);
1281
  }
1282
  else {
1283
    $taxon_uuid = FALSE;
1284
    // TODO is this SESSION variable ['cdm_dataportal']['tree']['taxon_uuid'] use at all?
1285
    if (isset($_SESSION['cdm_dataportal']['tree']['taxon_uuid'])) {
1286
      $taxon_uuid = $_SESSION['cdm_dataportal']['tree']['taxon_uuid'];
1287
    }
1288

    
1289
  }
1290
  return $taxon_uuid;
1291
}
(5-5/16)