Project

General

Profile

Download (37.3 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

    
118
  $form = array();
119
    switch ($delta) {
120
      case 'cdm_tree':
121
        /* TODO The option to use the cdm_taxontree for drupal vocabulaties also has been removed, the below code should be
122
           removed, see #7565
123
        $vocs = taxonomy_get_vocabularies();
124
        $options = array();
125
        foreach ($vocs as $voc) {
126
          $options[$voc->vid] = $voc->name;
127
        }
128
        $form['vid'] = array(
129
          '#type' => 'select',
130
          '#title' => t('Category'),
131
          '#default_value' => variable_get('cdm_taxontree_block_1_vid', 0),
132
          '#options' => $options,
133
        );
134
        */
135
    }
136
  return $form;
137
}
138

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

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

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

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

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

    
203
        case 'Georegion':
204
          $link = 'interest_by_georegion/';
205
          break;
206

    
207
        default:
208
          $link = 'taxonomy/term/';
209
      }
210
      return l($term->name, $link . $term->tid);
211

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

    
218

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

    
227
  if (isset($tids) && is_array($tids)) {
228

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

    
245
  if ($include_children) {
246
    foreach ($tid_list as $tid) {
247
      _cdm_taxontree_get_children($tid_list, $tid);
248
    }
249
  }
250

    
251
  return $tid_list;
252
}
253

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

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

    
280
  if ($_GET['destination']) {
281
    $destination = $_GET['destination'];
282
    unset($_GET['destination']);
283
    drupal_goto($destination);
284
  }
285
}
286

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

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

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

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

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

    
382
/**
383
 * Enter description here...
384
 *
385
 * @param unknown_type $tid
386
 * @param unknown_type $vid
387
 * @param unknown_type $theme
388
 */
389
function cdm_taxontree_taxonomy_children($tid, $vid, $theme) {
390
  $args = func_get_args();
391
  $tid = array_shift($args);
392
  $vid = array_shift($args);
393
  $theme = array_shift($args);
394

    
395
  $children = cdm_taxontree_get_children($tid, $vid);
396
  $children = cdm_taxontree_terms2treenodes($children);
397
  array_unshift($args, $theme, $children);
398
  print call_user_func_array('theme', $args);
399
}
400

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

    
415
/**
416
 * @todo Enter description here...
417
 *
418
 * @param unknown_type $uuid
419
 * @param unknown_type $vid
420
 *
421
 * @return unknown
422
 */
423
function cdm_taxontree_get_children($uuid, $vid = NULL) {
424

    
425
  if (is_numeric($vid)) {
426
    $terms = taxonomy_get_children($uuid, $vid);
427
    return cdm_taxontree_terms2treenodes($terms);
428
  }
429
  else {
430
    // FIXME Replace $uuid by path of parent $uuids.
431
    return cdm_ws_taxonomy_root_level($uuid);
432
  }
433
}
434

    
435
/**
436
 * @todo Enter description here...
437
 *
438
 * @param unknown_type $uuid
439
 *
440
 * @return unknown
441
 */
442
function cdm_taxontree_get_parents($uuid) {
443

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

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

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

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

    
503
  // Build the the branch for the focused node and merge it with the root.
504
  if ($taxonUuid) {
505
    $taxon_in_current_tree = taxon_in_current_classification($taxonUuid);
506
    if ($taxon_in_current_tree) {
507
      $branch = cdm_taxontree_build_path($taxonUuid, NULL, (cdm_taxontree_filters_active() ? NULL : TRUE));
508
      $root_tree = _cdm_taxontree_merge($root_tree, $branch);
509
    }
510
  }
511

    
512
   // Reorder siblings & populate expanded nodes with children and propagate
513
   // the filter attribute.
514
   $root_tree = cdm_taxontree_populate($root_tree, $compact_tree === FALSE);
515

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

    
530
  return $root_tree;
531
}
532

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

    
551
  $branch_path = array();
552

    
553
  $parents = cdm_taxontree_get_parents($taxonUuid);
554
  if (!$parents) {
555
    if ($is_filter_path) {
556
      // \remove invalid filter.
557
      cdm_taxontree_filters_remove($taxonUuid);
558
    }
559
    return FALSE;
560
  }
561

    
562
  $parents = _cdm_resultset2nodelist($parents, NULL);
563
  $lastParent = NULL;
564

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

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

    
604
  if (!is_array($tree)) {
605
    return FALSE;
606
  }
607
  foreach (array_keys($tree) as $uuid) {
608

    
609
    if (!isset($tree[$uuid]->filter)) {
610
      $tree[$uuid]->filter = $filter_default;
611
    }
612

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

    
615
      if (isset($tree[$uuid]->vid)) {
616
        //  TODO remove case, see #7565
617
        $children = cdm_taxontree_get_children($uuid, $tree[$uuid]->vid);
618
      }
619
      else {
620
        $children = cdm_taxontree_get_children($uuid);
621
      }
622
      $children = _cdm_resultset2nodelist($children, ($tree[$uuid]->filter == 'excludes'));
623

    
624
      // Store the children of the node for later processing.
625
      if (isset($tree[$uuid]->children) && is_array($tree[$uuid]->children)) {
626
        $pnode_children = $tree[$uuid]->children;
627
      }
628
      else {
629
        $pnode_children = FALSE;
630
      }
631
      // Replace the children by the newly retrieved child nodes.
632
      $tree[$uuid]->children = $children;
633

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

    
654
        // Sort.
655
        ksort($reordered);
656

    
657
        // Move the children back into the parent node.
658
        $tree[$uuid]->children = array();
659
        foreach ($reordered as $cnode) {
660
          $tree[$uuid]->children[$cnode->taxonUuid] = $cnode;
661
        }
662
      }
663
      if (!isset($tree[$uuid]->children)) {
664
        $tree[$uuid]->children = FALSE;
665
      }
666
      $tree[$uuid]->children = cdm_taxontree_populate($tree[$uuid]->children, $expand_excluded, $tree[$uuid]->filter);
667
    }
668
  }
669
  return $tree;
670
}
671

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

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

    
713
  if (!$branch || !is_array($branch)) {
714
    return $tree;
715
  }
716

    
717
  if (!is_array($tree)) {
718
    return;
719
  }
720

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

    
756

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

    
777
  if (!is_array($resultset)) {
778
    return FALSE;
779
  }
780

    
781
  $tree = array();
782
  foreach ($resultset as $treeNode) {
783
    if (!is_null($excluded)) {
784
      $treeNode->filter = ($excluded ? 'excluded' : 'included');
785
    }
786
    if (!is_null($expanded)) {
787
      $treeNode->expanded = ($expanded ? 'expanded' : 'collapsed');
788
    }
789
    $tree[$treeNode->taxonUuid] = $treeNode;
790
  }
791
  return $tree;
792
}
793

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

    
808
  $path_cdm_taxontree = drupal_get_path('module', 'cdm_taxontree');
809
  $path_preferred_module = drupal_get_path('module', 'cdm_dataportal') ? drupal_get_path('module', 'cdm_dataportal') : $path_cdm_taxontree;
810
  drupal_add_css($path_cdm_taxontree . '/cdm_taxontree.css');
811
  drupal_add_js($path_cdm_taxontree . '/js/cdm_taxontree.js');
812

    
813
  drupal_add_js('
814
      jQuery(document).ready(function()
815
      {
816
        jQuery(\'' . $parent_element_selector . '\').cdm_taxontree();
817
      });
818
      ', array('type' => 'inline'));
819
}
820

    
821
// ------------------------ THEME --------------------------- //
822

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

    
854
  // THEMERS: change the line below according to the
855
  // specific regions of your theme.
856
  $left_expand_region = 'right';
857

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

    
877
  $out .= theme('cdm_taxontree', array(
878
    'tree' => $tree,
879
    'filterIncludes' => !cdm_taxontree_filters_active(),
880
    'show_filter_switch' => $show_filter_switch,
881
    'tree_node_callback' => $tree_node_callback,
882
    ));
883

    
884
  if ($magicbox) {
885
    $out .= '</div></div></div>';
886
  }
887
  else {
888
    $out .= '</div>';
889
  }
890
  return $out;
891
}
892

    
893
/**
894
 * @todo Please document this function.
895
 * @see http://drupal.org/node/1354
896
 */
897
function theme_cdm_taxontree_controller($variables) {
898
  $compact_mode = $variables['compact_mode'];
899

    
900
  static $modes = array('expanded', 'compact', 'flattened');
901

    
902
  $out = '<div class="settings">';
903
  foreach ($modes as $mode) {
904
    if ($compact_mode == $mode) {
905
      $out .= t('@mode', array('@mode' => $mode));
906
    }
907
    else {
908
      $out .= l(t('@mode', array('@mode' => $mode)), 'cdm_taxontree/set/compact_mode/' . $mode, array('query' => drupal_get_destination()));
909
    }
910
    $out .= ' ';
911
  }
912

    
913
  return $out . '</div>';
914
}
915

    
916
/**
917
 * @todo Please document this function.
918
 * @see http://drupal.org/node/1354
919
 */
920
function theme_cdm_taxontree($variables) {
921
  $tree = $variables['tree'];
922
  $filterIncludes = $variables['filterIncludes'];
923
  $show_filter_switch = $variables['show_filter_switch'];
924
  $tree_node_callback = $variables['tree_node_callback'];
925
  $element_name = $variables['element_name'];
926

    
927
  if(isset($tree->records)){
928
    // unwrap from pager object
929
    $tree = $tree->records;
930
  }
931

    
932
  if (!is_array($tree)) {
933
    return FALSE;
934
  }
935

    
936
  if (is_null($filterIncludes)) {
937
    // Set $filterIncludes TRUE if no filters are set.
938
    $filterIncludes = !cdm_taxontree_filters_active();
939
  }
940

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

    
958
/**
959
 * @todo Please document this function.
960
 * @see http://drupal.org/node/1354
961
 */
962
function theme_cdm_taxontree_node($variables) {
963
  $node = $variables['node'];
964
  $filterIncludes = $variables['filterIncludes'];
965
  $show_filter_switch = $variables['show_filter_switch'];
966
  $tree_node_callback = $variables['tree_node_callback'];
967

    
968
  $is_leaf = !$node->taxonomicChildrenCount || $node->taxonomicChildrenCount == 0;
969
  $is_expanded = isset($node->expanded) && $node->expanded = 'expanded';
970

    
971
  $focused_taxon_uuid = get_current_taxon_uuid();
972

    
973
  if (isset($node->tid)) {
974
    $node_name = $node->name;
975
    $path = "taxonomy/term/" . $node->tid;
976
    // disable filterswitch
977

    
978
    $show_filter_switch = FALSE;
979

    
980
  }
981
  elseif (module_exists('cdm_dataportal')) {
982
    $node_name = cdm_dataportal_shortname_of($node);
983
    $path = path_to_taxon($node->taxonUuid);
984
  }
985
  else {
986
    $node_name = "module cdm_dataportal missing";
987
    $path = "";
988
  }
989

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

    
1008
  $ahah_url = FALSE;
1009
  if (!$is_leaf && !$is_expanded && $filter_class != 'filter_excluded') {
1010
    if (isset($node->tid)) {
1011
      //  TODO remove case, see #7565
1012
      $ahah_url = url('cdm_taxontree/taxonomy/children/' . $node->tid . '/' . $node->vid . '/cdm_taxontree/' . ($nextLevelIncluded ? 1 : 0) . '/' . ($show_filter_switch ? 1 : 0) . '/' . $tree_node_callback);
1013
    }
1014
    elseif (module_exists('cdm_dataportal')) {
1015
      $ws_url = cdm_compose_taxonomy_root_level_path($node->taxonUuid);
1016
      $ahah_url = url('cdm_api/proxy/' . urlencode($ws_url) . '/cdm_taxontree/' . ($nextLevelIncluded ? 1 : 0) . '/' . ($show_filter_switch ? 1 : 0) . '/' . $tree_node_callback);
1017
    }
1018
  }
1019

    
1020
  // List item.
1021
  $out = '<li class="'
1022
    . ($node->taxonUuid == $focused_taxon_uuid ? 'focused ' : '')
1023
    . ($is_leaf ? 'leaf ' : ($is_expanded ? 'expanded ' : 'collapsed '))
1024
    . $filter_class . '"'
1025
    . ($ahah_url ? ' data-cdm-ahah-url="' . $ahah_url . '"' : '')
1026
    . '>';
1027

    
1028
  if ($show_filter_switch) {
1029
    // Filter icon.
1030
    $out .= theme('cdm_taxontree_node_filter_switch', array('node' => $node, 'filter_class' => $filter_class));
1031
  }
1032

    
1033
  // Taxon name.
1034
  $out .= '<span class="' . html_class_attribute_ref($node) . '">' . $name . '</span>';
1035

    
1036
  // Concept_switch or other theme callbacks.
1037
  if ($tree_node_callback) {
1038
     $out .= theme($tree_node_callback, array('node' => $node));
1039
  }
1040

    
1041
  if (isset($node->children) && is_array($node->children)) {
1042
    $out .= theme('cdm_taxontree', array(
1043
      'tree' => $node->children,
1044
      'filterIncludes' => $nextLevelIncluded,
1045
      'show_filter_switch' => $show_filter_switch,
1046
      'tree_node_callback' => $tree_node_callback,
1047
    ));
1048
  }
1049
  $out .= '</li>';
1050

    
1051
  return $out;
1052
}
1053

    
1054
/**
1055
 * @todo Please document this function.
1056
 * @see http://drupal.org/node/1354
1057
 */
1058
function theme_cdm_taxontree_node_filter_switch($variables) {
1059
  $node = $variables['node'];
1060
  $filter_class = $variables['filter_class'];
1061
  if (!module_exists('cdm_dataportal')) {
1062
    return '';
1063
  }
1064

    
1065
  $out = '';
1066
  switch ($filter_class) {
1067
    case 'filter_included':
1068
      $filter_icon = 'visible_implicit_small.gif';
1069
      break;
1070

    
1071
    case 'filter_excluded':
1072
      $filter_icon = 'invisible_small.gif';
1073
      break;
1074

    
1075
    case 'filter_on':
1076
      $filter_icon = 'visible_small.gif';
1077
      break;
1078

    
1079
  }
1080

    
1081
  $filter_op = $node->filter == 'on' ? 'remove' : 'add';
1082

    
1083
  $out .= '&nbsp;'
1084
    . l('<img src="' . base_path() . drupal_get_path('module', 'cdm_taxontree') . '/' . $filter_icon . '" alt="[f]" />',
1085
        'cdm_taxontree/filter/' . $filter_op . '/' . $node->taxonUuid, array(
1086
          'attributes' => array('class' => 'filter_' . $filter_op),
1087
          'query' => 'destination=' . path_to_taxon($node->taxonUuid),
1088
          'fragment' => NULL,
1089
          'absolute' => TRUE,
1090
          'html' => TRUE,
1091
        ));
1092

    
1093
  return $out;
1094
}
1095

    
1096
/**
1097
 * Returns HTML for a Taxontree-node concept switch.
1098
 *
1099
 * @param array $variables
1100
 *   An associative array containing:
1101
 *   - node: The node object.
1102
 *
1103
 * @ingroup themeable
1104
 */
1105
function theme_cdm_taxontree_node_concept_switch($variables) {
1106
  $node = $variables['node'];
1107
  $out = '';
1108

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

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

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

    
1171
  if (!isset($_SESSION['cdm']['filters'])) {
1172
    $_SESSION['cdm']['filters'] = array();
1173
  }
1174
  if ($taxonUuid || $op == 'list') {
1175
    switch ($op) {
1176
      case 'add':
1177
        cdm_taxontree_filters_add($taxonUuid);
1178
        break;
1179

    
1180
      case 'remove':
1181
        cdm_taxontree_filters_remove($taxonUuid);
1182
        break;
1183

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

    
1201
/**
1202
 * Checks if there are active filters.
1203
 *
1204
 * Filters are set in cdm_dataportal_view_filter().
1205
 * functions using filters should remove invalid filters.
1206
 *
1207
 * @return bool
1208
 *   TRUE if any filter is active.
1209
 */
1210
function cdm_taxontree_filters_active() {
1211
  return isset($_SESSION['cdm']['filters']) && count($_SESSION['cdm']['filters']) > 0;
1212
}
1213

    
1214
/**
1215
 * Filters are set in cdm_dataportal_view_filter().
1216
 *
1217
 * @return mixed
1218
 *   A reference on the filters array stored in the SESSION.
1219
 */
1220
function &cdm_taxontree_filters_get() {
1221
  if (!isset($_SESSION['cdm']['filters'])) {
1222
    $_SESSION['cdm']['filters'] = array();
1223
  }
1224
  return $_SESSION['cdm']['filters'];
1225
}
1226

    
1227
/**
1228
 * Adds a taxon to the filtered taxa array
1229
 *
1230
 * @param UUID $taxonUuid
1231
 */
1232
function cdm_taxontree_filters_add($taxonUuid) {
1233

    
1234
  $parents = cdm_ws_taxonomy_pathFromRoot($taxonUuid);
1235

    
1236
  $parents = array_reverse($parents);
1237

    
1238
  // Pop off last element since this is the TreeNode object for $taxonUuid!
1239
  $this_node = array_pop($parents);
1240

    
1241
  // Will contain the uuid of the parent nodes excluding the
1242
  // $taxonUuid node itself.
1243
  $parent_uuids = array();
1244

    
1245
  // Children override parents rule: remove all parent filters.
1246
  foreach ($parents as $pnode) {
1247
    unset($_SESSION['cdm']['filters'][$pnode->taxonUuid]);
1248
    $parent_uuids[] = $pnode->taxonUuid;
1249
  }
1250

    
1251
  // Search for potential children of this $taxonUuid.
1252
  foreach ($_SESSION['cdm']['filters'] as $uuid => $node) {
1253
    if (in_array($taxonUuid, $node->parentUuids)) {
1254
      unset($_SESSION['cdm']['filters'][$node->taxonUuid]);
1255
    }
1256
  }
1257
  // Finally add this $taxonUuid as new filter.
1258
  $this_node->parentUuids = $parent_uuids;
1259
  $_SESSION['cdm']['filters'][$taxonUuid] = $this_node;
1260
}
1261

    
1262
/**
1263
 * Unsets a taxon from the filtered taxa array.
1264
 *
1265
 * @param string $taxonUuid
1266
 */
1267
function cdm_taxontree_filters_remove($taxonUuid) {
1268
  unset($_SESSION['cdm']['filters'][$taxonUuid]);
1269
}
1270

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

    
1286
  if (arg(0) == "cdm_dataportal" && arg(1) == "taxon" && arg(2) !== 0) {
1287
    $taxon_uuid = arg(2);
1288
  }
1289
  else {
1290
    $taxon_uuid = FALSE;
1291
    // TODO is this SESSION variable ['cdm_dataportal']['tree']['taxon_uuid'] use at all?
1292
    if (isset($_SESSION['cdm_dataportal']['tree']['taxon_uuid'])) {
1293
      $taxon_uuid = $_SESSION['cdm_dataportal']['tree']['taxon_uuid'];
1294
    }
1295

    
1296
  }
1297
  return $taxon_uuid;
1298
}
(5-5/16)