Project

General

Profile

Download (19.2 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
// $Id$
3

    
4
/*
5
 * @file
6
 * cdm_dataportal
7
 *
8
 * Copyright (C) 2007 EDIT
9
 * European Distributed Institute of Taxonomy
10
 * http://www.e-taxonomy.eu
11
 *
12
 * The contents of this file are subject to the Mozilla Public License Version 1.1
13
 * See LICENSE.TXT at the top of this package for the full license terms.
14
 */
15

    
16
require_once('cdm_dataportal.theme.php');
17

    
18
/* ====================== hook implementations ====================== */
19

    
20
/**
21
 * Implementation of hook_help()
22
 *
23
 * Display help and module information
24
 * @param section which section of the site we're displaying help
25
 * @return help text for section
26
 */
27
function cdm_dataportal_help($section='') {
28

    
29
  $out = '';
30
  switch ($section) {
31
    case "admin/modules#description":
32
      $out = t("The dataportal publishes CDM data hosted in a CommunityStore on the web.");
33
      break;
34
  }
35
  return $out;
36
}
37

    
38

    
39
/**
40
 * Implementation of hook_perm()
41
 *
42
 * Valid permissions for this module
43
 * @return array An array of valid permissions for the portfolio module
44
 */
45
function cdm_dataportal_perm() {
46
  return array(
47
    	'administer cdm_dataportal',
48
        'cdm_dataportal view notes',
49
  //TODO which else permission are required? -> check the WP6 requirements document
50
  );
51
}
52

    
53

    
54
/**
55
 * Implementation of hook_menu()
56
 */
57
function cdm_dataportal_menu($may_cache) {
58
  $items = array();
59
  if ($may_cache) {
60

    
61
    $items[] = array(
62
      'path' => 'admin/settings/cdm_dataportal',
63
      'title' => t('CDM Dataportal'),
64
      'description' => t('Setting for the CDM Dataportal'),
65
      'access' => user_access('administer cdm_dataportal'),
66
      'callback' => 'drupal_get_form',
67
      'callback arguments' => 'cdm_dataportal_settings',
68
    );
69
    
70
    /*$items[] = array(
71
      'path' => 'admin/settings/cdm_dataportal/ws',
72
      'title' => t('Web Service'),
73
      'description' => t('Setting for the CDM Dataportal'),
74
      'access' => user_access('administer cdm_dataportal'),
75
      'callback' => 'drupal_get_form',
76
      'callback arguments' => 'cdm_dataportal_settings',
77
      'weight' => 1,
78
      'type' => MENU_DEFAULT_LOCAL_TASK,
79
    );*/
80
    
81
    $items[] = array(
82
	    'path' => 'cdm_dataportal/names',
83
	    'callback' => 'cdm_dataportal_view_names',
84
	    'access' => true,
85
	    'type' => MENU_CALLBACK, 
86
    );
87
    // optional callback arguments: page
88
     
89
    $items[] = array(
90
	    'path' => 'cdm_dataportal/taxon',
91
	    'callback' => 'cdm_dataportal_view_taxon',
92
	    'access' => true,
93
	    'type' => MENU_CALLBACK, 
94
    // expected callback arguments: name_uuid
95
    );
96
    
97
    $items[] = array(
98
      'path' => 'cdm_dataportal/search/taxon',
99
      'callback' => 'cdm_dataportal_view_search_taxon',
100
      'access' => true,
101
      'type' => MENU_CALLBACK, 
102
    );
103
    
104
    $items[] = array(
105
      'path' => 'cdm_dataportal/filter',
106
      'callback' => 'cdm_dataportal_view_filter',
107
      'access' => true,
108
      'type' => MENU_CALLBACK, 
109
    );
110
    
111
    $items[] = array(
112
      'path' => 'cdm/xml2json',
113
      'callback' => 'cdm_view_xml2json',
114
      'access' => true,
115
      'type' => MENU_CALLBACK, 
116
    );
117
     
118
  }
119
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal').'/cdm_dataportal.css');
120
  //drupal_add_css(drupal_get_path('module', 'cdm_dataportal').'/cdm_dataportal_print.css', 'print');
121
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal').'/cdm_dataportal_screen.css', 'screen');
122
  return $items;
123
  
124
}
125

    
126
/**
127
 * Implementation of hook_block()
128
 *
129
 * Provides the following blocks:
130
 *  0: list of links useful during development
131
 *
132
 * @param String $op
133
 * @param int $delta
134
 */
135
function cdm_dataportal_block($op='list', $delta=0) {
136
  // listing of blocks, such as on the admin/block page
137
  if ($op == "list") {
138
    $block[0]["info"] = t("CDM DataPortal DevLinks");
139
    $block[1]["info"] = t("CDM DataPortal Credits");
140
    $block[2]["info"] = t("CDM Search Taxa");
141
    $block[3]["info"] = t("CDM Filters");
142
    return $block;
143
  }
144
  else if ($op == 'view') {
145
    switch($delta){
146
      case 0:
147
        $block['subject'] = t('CDM DataPortal DevLinks');
148
        $block['content'] = '<ul>
149
        <li>'.l('A Taxon Page', cdm_dataportal_taxon_path('5000001-stub')).'</li>
150
        <li>'.l('Name List - page1 of A', 'cdm_dataportal/names/A/1')
151
        //.'</li><li>'.l('xml2json', 'cdm/xml2json/namelist;startwith=A.xml')
152
        .'</li>
153
        </ul>';
154
        return $block;
155
      case 1:
156
        $block['subject'] = t('Credits');
157
        $block['content'] = theme('cdm_credits');
158
        return $block;
159
      case 2:
160
        $block['subject'] = t('Search Taxa');
161
        $block['content'] = drupal_get_form('cdm_dataportal_search_taxon_form');
162
        return $block;   
163
      case 3:
164
        $block['subject'] = t('Active Filters');
165
        $block['content'] = cdm_dataportal_view_filter('list');
166
        return $block;
167
    }
168
  }
169
}
170

    
171

    
172
/**
173
 * Implementation of hook_validate()
174
 *
175
 * @param $element
176
 */
177
function cdm_dataportal_settings_validate($form_id, $form_values){
178
  
179
  if (!str_endsWith($form_values['cdm_webservice_url'], '/')) {
180
    form_set_error('cdm_webservice_url', t("The URL to the CDM Web Service must end with a slash: '/'."));
181
  }
182

    
183
  $cdm_webservice_url_changed = variable_get('cdm_webservice_url', '') != $form_values['cdm_webservice_url'];
184
  
185
  if ($cdm_webservice_url_changed) {
186
    $form_values['cdm_secUuid_default'] = 0;
187
    //_cdm_dataportal_set_currentSecUuid(false);
188
    // reset all cdm related data stored in the session
189
    $_SESSION['cdm'] = null;
190
  }
191
  
192
}
193

    
194

    
195
function cdm_dataportal_search_taxon_form(){
196
  
197
  $url = 'cdm_dataportal/search/taxon';
198
  $form['#method'] = 'get';
199
  $form['#process'] = array('cdm_dataportal_search_process' => array());
200
  $form['#action'] = url($url, NULL, NULL, true);
201
  
202
  $form['queryString'] = array(
203
    '#type' => 'textfield',
204
    '#size' => 20,
205
    '#attributes' => array('title' => t('Enter the name or part of a name you wish to search for.')),
206
    '#default_value' => (isset($_SESSION['cdm']['search']['queryString']) ? $_SESSION['cdm']['search']['queryString'] : ''),
207
  );
208
  $form['onlyAccepted'] = array(
209
    '#type' => 'checkbox',
210
    '#title' => t('Only Accepted'),
211
    '#attributes' => array('title' => t('Search only for taxa which are accepted by the current treatment.')),
212
    '#default_value' => isset($_SESSION['cdm']['search']['onlyAccepted']) && $_SESSION['cdm']['search']['onlyAccepted'],
213
  );
214
  /*
215
  $form['vernacular'] = array(
216
    '#type' => 'checkbox',
217
    '#title' => t('Vernacular Names'),
218
    '#attributes' => array('title' => t('Search for vernacular names.')),
219
    '#default_value' => isset($_SESSION['cdm']['search']['vernacular']) && $_SESSION['cdm']['search']['vernacular'],
220
  );
221
  $form['language'] =  array(
222
    '#type' => 'select',
223
    '#title' => t('Language'),
224
    '#options' => array(
225
        '*' => t('ALL')
226
        ),
227
    '#description'   => t('The language of the vernacular name'),
228
    '#default_value' => (isset($_SESSION['cdm']['search']['language']) ? $_SESSION['cdm']['search']['language'] : ''),
229
  );
230
  */
231
  $form['page'] = array(
232
  '#type' => 'hidden',
233
  '#value' => '1',
234
  );
235
  
236
  $form['submit'] = array(
237
  '#type' => 'submit',
238
  '#name' => '', 
239
  '#value' => t('Search'),
240
  );
241
  
242
  // clean URL get forms breaks if we don't give it a 'q'.
243
  if (!(bool)variable_get('clean_url', '0')) {
244
    $form['q'] = array(
245
      '#type' => 'hidden',
246
      '#value' => $url,
247
      '#name' => 'q',
248
    );
249
  }
250
  return $form;
251
}
252

    
253

    
254
function cdm_dataportal_search_process($form) {
255
  unset($form['form_id']);
256
  unset($form['form_token']);
257
  return $form;
258
}
259

    
260
/**
261
 * Filters $_REQUEST by a list of valid request  parameters and also sets defaults if required.
262
 * returns the processed request parameters submitted by the search form.
263
 */
264
function cdm_dataportal_search_form_request(){
265
  // keys map $REQUEST Keys values are optional default parameters if not null
266
  static $search_form_params = array('queryString'=>null, 'onlyAccepted' =>'0', 'page'=>null);
267
  
268
  $form_params = array();
269
  foreach($search_form_params as $key=>$default ){
270
    $form_params[$key] = ( isset($_REQUEST[$key]) && $_REQUEST[$key] != '' ? $_REQUEST[$key] : $default);
271
  }
272
  return $form_params;
273
}
274
  
275

    
276
/*
277
function cdm_dataportal_search_taxon_form_submit($form_id, $form_values) {
278
  
279
  $_SESSION['cdm']['search'] = $form_values;
280
  //return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['vernacular']?'1':'0').'/'.$form_values['language'];      
281
  return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['onlyAccepted']?'1':'0');  
282
  //$paramstr = compose_url_prameterstr($form_values);
283
  //return url('/cdm_dataportal/search/taxon/', $paramstr);
284
}
285
*/
286
/* ====================== menu callback functions ====================== */
287

    
288
/**
289
 * Generate main administration form.
290
 *
291
 * @return
292
 *   An array containing form items to place on the module settings page.
293
 */
294
function cdm_dataportal_settings(){
295

    
296
  $form = cdm_api_settings_form();
297

    
298
  //TODO: settings are still incomplete, compare with trunk/dataportal/inc/config_default.php.inc
299
  $form['cdm_dataportal'] = array(
300
      '#type' => 'fieldset',
301
      '#title' => t('CDM DataPortal'),
302
      '#collapsible' => FALSE,
303
      '#collapsed' => TRUE,
304
  );
305
  $allSecRefs = cdm_ws_get(CDM_WS_SEC_REFERENCES_ALL);
306
  $secRef_default = isset($allSecRefs[0]) ? $allSecRefs[0] : false;
307
  $secUuid_options = array('0' => ' --- none ---');
308
  foreach($allSecRefs as $ref){
309
    $secUuid_options[$ref->uuid] =  $ref->citation.($ref->year ? ' ['.$ref->year.']' : '');
310
  }
311
  $form['cdm_dataportal']['cdm_secUuid_default'] =  array(
312
    '#type' => 'select',
313
    '#title'         => t('Default Concept Reference'),
314
    '#options' => $secUuid_options,
315
    '#default_value' => variable_get('cdm_secUuid_default', $secRef_default->uuid),
316
    '#description'   => t('The default \'sensu\' reference to start the cdm_dataportal with. Per user choices are possible and may override this value.'),
317
  );
318
   
319
  
320
  // TODO reset default secuuid  in session if changed in settings
321
  return system_settings_form($form);
322
}
323

    
324
/**
325
 * Displays a list of the known taxonomic names. Long lists are split up into multiple pages
326
 *
327
 * TODO: parameters are still preliminar
328
 * @param String $page page number to diplay defaults to page 1
329
 * @param boolean $hide_unaccepted whether to hide nams which are not accepted by the current view
330
 */
331
function cdm_dataportal_view_names($beginsWith = 'A', $page = 1, $onlyAccepted = false ){
332

    
333
  $request_params  = array(
334
    'q' => $beginsWith, 
335
         //'sec' = '',
336
         //'higherTaxa' => getFiters(),
337
          // 'matchAnywhere' => false, // default is false
338
    'page' => $page, 
339
    'onlyAccepted' => $onlyAccepted, 
340
    'pagesize' => 20  /*$_SESSION['cdm']['namelist_pagesize'] */);
341
  
342
  $taxonSTOs = cdm_ws_get(CDM_WS_FIND_TAXA, $request_params);
343
  /*
344
   * FIXME the filter for accepted names will be a form element, thus this widget
345
   * should be generated via form api preferably as block
346
   */
347
  //$out  = theme('cdm_dataportal_widget_filter_accepted', $onlyAccepted);
348
  //$out .= theme('cdm_dataportal_widget_names_list', $names, $page);
349
  $out .= theme('cdm_listof_taxa', $taxonSTOs);
350
  return $out;
351
}
352

    
353

    
354
/**
355
 * The taxon page gives detailed information on a taxon, it shows:
356
 *  - Taxon name
357
 *  - Full list of synonyms homotypic synonyms on top, followed by the
358
 *    heterotypic and finally followed by misapplied names.
359
 *    The list is ordered historically.
360
 *  - All facts associated with the very taxon concept and taxon name.
361
 *
362
 * @param String $uuid the UUID of the taxon
363
 */
364
function cdm_dataportal_view_taxon($uuid, $arg2 = null){
365

    
366

    
367
  if(isset($arg2) && !is_numeric($arg2)){
368
   
369
    switch ($args[0]){
370
      case 'alternatives':
371
        $alternatives = cdm_ws_get(CDM_WS_TAXON_ALTERNATIVES, $uuid);
372
        return theme('cdm_alternative_taxa', $alternatives);
373
    }
374
    
375
  } else {
376
  
377
    // display the page for the taxon defined by $uuid
378
    $taxonTO = cdm_ws_get(CDM_WS_TAXON ,$uuid);
379
  
380
    _cdm_dataportal_set_currentSecUuid($taxonTO->secUuid);
381
  
382
    drupal_set_title(theme('cdm_taxon', $taxonTO, true));
383
    //TODO retrieve complete synonymy and other data
384
  
385
    $out = theme('cdm_taxon_page', $taxonTO);
386
    return $out;
387
  }
388
}
389

    
390

    
391

    
392
/**
393
 * Expected URL request parameters:
394
 *  - text
395
 *  - language
396
 *  - vernacular
397
 * 
398
 * future extensions to meet palmweb mockup requirements:
399
 *  - habitat
400
 *  - uses
401
 *  - conservation status
402
 *  - locality / tdwg region
403
 */
404
function cdm_dataportal_view_search_taxon(){
405
  
406
  $request_params = cdm_dataportal_search_form_request();
407
  $sw_params = array_replace_key($request_params, array('queryString'=> 10 ));
408
  //FIXME remove debug code:
409
  $sw_params['page'] = '1'; // DEBUG code
410
  $resultPageSTO = cdm_ws_get(CDM_WS_FIND_TAXA, $sw_params);
411
  $resultPageSTO->pageNumber = $request_params['page'];
412
  return theme('cdm_search_results', $resultPageSTO, 'cdm_dataportal/search/taxon', $request_params);
413
}
414

    
415
/**
416
 * filters on children override already set parent filters and vice verca
417
 *
418
 * @param unknown_type $op
419
 * @param unknown_type $taxonUuid
420
 * @return unknown
421
 */
422
function cdm_dataportal_view_filter($op, $taxonUuid = null){
423
  
424
  if(!isset($_SESSION['cdm']['filters'])){
425
    $_SESSION['cdm']['filters'] = array();
426
  }
427
  if($taxonUuid || $op == 'list'){
428
    switch($op){
429
      case 'add':
430
        $parents = cdm_ws_get(CDM_WS_TREENODE_PARENTS, $taxonUuid);
431
        // pop off last element since this is the TreeNode object for $taxonUuid!
432
        $this_node = array_pop($parents);
433
        // will contain the uuid of the parent nodes excluding the $taxonUuid node itself
434
        $parent_uuids = array();
435
        
436
        // children override parents rule: remove all parent filters, 
437
        foreach($parents as $pnode){
438
          unset($_SESSION['cdm']['filters'][$pnode->uuid]);
439
          $parent_uuids[] = $pnode->uuid;
440
        }
441
        
442
        // search for potential children of this $taxonUuid
443
        foreach($_SESSION['cdm']['filters'] as $uuid=>$node){
444
          if(in_array($taxonUuid, $node->parentUuids)){
445
            unset($_SESSION['cdm']['filters'][$node->uuid]);
446
          }
447
        }
448
        // finally add this $taxonUuid as new filter
449
        $this_node->parentUuids = $parent_uuids;
450
        $_SESSION['cdm']['filters'][$taxonUuid] = $this_node;
451
        break;
452
      case 'remove':
453
        unset($_SESSION['cdm']['filters'][$taxonUuid]);
454
        break;
455
      case 'list':
456
        //TODO put in theme!!!
457
        $out = '<ul>';
458
        foreach($_SESSION['cdm']['filters'] as $uuid=>$node){
459
          $out .= '<li>'.cdm_dataportal_shortname_of($node).' '.l('[x]', 'cdm_dataportal/filter/remove/'.$uuid, array(), drupal_get_destination()).'</li>';
460
        }
461
        $out .= '</ul>';
462
        return $out;
463
    }
464
  }
465
  if($_REQUEST['destination']){
466
    $destination = $_REQUEST['destination'];
467
    unset($_REQUEST['destination']);
468
    drupal_goto($destination);
469
  }
470
}
471

    
472

    
473
function cdm_view_xml2json(){
474
  $file = arg(2);
475
  $datastr = get_content(variable_get('cdm_webservice_url', '').$file);
476
  return  xml2json::transformXmlStringToJson($datastr);
477

    
478
}
479

    
480
/**
481
 * Get a term for the current locale from the $localised_terms array.
482
 * Uses global variable $locale from drupal (see drupal functions locale_initialize() for details)
483
 * Function name is adapted from the drupal function t().
484
 *
485
 */
486
function cdm_dataportal_t($localised_terms){
487
  global $locale;  // drupal variable containing the current locale
488
  return cdm_get_localised_term($localised_terms, $locale);
489
}
490

    
491
/* ====================== other functions ====================== */
492

    
493
/**
494
 * Enter description here...
495
 *
496
 * @param String $uuid the UUID of the taxon
497
 * @return the URL
498
 */
499
function cdm_dataportal_taxon_path($uuid){
500
  return 'cdm_dataportal/taxon/'.$uuid;
501
}
502

    
503
/**
504
 * Creates a short taxonname by using the taggename field of NameSTO or NameTO instances.
505
 * If the taggename if empty the fullname will be returned.
506
 *
507
 * @param unknown_type $NameSTO a NameSTO, TreeNode or NameTO instance
508
 * @return string
509
 */
510
function cdm_dataportal_shortname_of($NameSTO){
511

    
512
  $name = trim(cdm_taggedtext_value($NameSTO->taggedName, 'name'));
513
  if($name){
514
    if( $pos = stripos($name, ' ')){
515
      return substr($name, 0, 1).'. '.substr($name, $pos);
516
    } else {
517
      return $name;
518
    }
519
  } else {
520
    return $NameSTO->fullname;
521
  }
522
}
523

    
524
/**
525
 * Sets the secUuid of the $taxonTO parameter to the current secUuid which is stored in the users session
526
 *
527
 * @param TaxonTO $taxonTO
528
 */
529
function _cdm_dataportal_set_currentSecUuid($secUuid){
530

    
531
  if( !isset($_SESSION['cdm']['currentSecRef']['uuid']) ||  $_SESSION['cdm']['currentSecRef']['uuid'] != $secUuid){
532
    if(!$secUuid){
533
      $_SESSION['cdm']['currentSecRef'] = null;
534
    } else {
535
      $secRef = cdm_ws_get(CDM_WS_REFERENCE ,$secUuid);
536
      $_SESSION['cdm']['currentSecRef'] = (array)$secRef;
537
    }
538
  }
539
}
540

    
541
/**
542
 * returns the current secRef array from the users session. 
543
 * If the according session variable is not jet set the default
544
 * as configured in the setting is used otherwise null.
545
 * 
546
 * currentSecRef['uuid']
547
 * currentSecRef[....
548
 *
549
 * @return array
550
 */
551
function _cdm_dataportal_currentSecRef_array(){
552
  
553
  if( !isset($_SESSION['cdm']['currentSecRef']['uuid'])){
554
     $secUuid = variable_get('cdm_secUuid_default', null);
555
     _cdm_dataportal_set_currentSecUuid($secUuid);
556
  }
557
  return  $_SESSION['cdm']['currentSecRef'];
558
}
559

    
560
function cdm_dataportal_filters_areset(){
561
 return isset($_SESSION['cdm']['filters']) && count($_SESSION['cdm']['filters']) > 0;
562
}
563

    
564
/**
565
 * @return a reference on the filters array stored in the SESSION
566
 */
567
function &cdm_dataportal_filters_get(){
568
  if(!isset($_SESSION['cdm']['filters'])){
569
    $_SESSION['cdm']['filters'] = array();
570
  }
571
 return $_SESSION['cdm']['filters'];
572
}
573

    
574

    
575
/**
576
 * @param $str the string to truncate
577
 * @param $len the maximun length
578
 * @param $appendix an optional appendix.
579
 *
580
 * @return the string truncated to the specified length or the original string as given as parameter.
581
 * if an appendix has been defined the resulting string
582
 * will have the specified length inculding the the appendix.
583
 */
584
function str_trunk(&$str, $len, $appendix=''){
585
  if(strlen($str) >= $len )
586
  return  substr($str, 0, $len - strlen($appendix)).$appendix;
587
  else
588
  return $str;
589
}
590

    
591
/**
592
 * @param string $str
593
 * @param string $sub
594
 * @return boolean
595
 */
596
function str_beginsWith( $str, $sub ) {
597
  return ( substr( $str, 0, strlen( $sub ) ) === $sub );
598
}
599

    
600
/**
601
 *
602
 * @param string $str
603
 * @param string $sub
604
 * @return boolean
605
 */
606
function str_endsWith( $str, $sub ) {
607
  return ( substr( $str, strlen( $str ) - strlen( $sub ) ) === $sub );
608
}
609

    
610

    
611
function array_replace_key($array, $replace_map){
612
  foreach($replace_map as $key=>$newkey){
613
    if(isset($array[$key])){
614
      $array[$newkey] = $array[$key];
615
      unset($array[$key]);
616
    }
617
  }
618
  return $array;
619
}
620

    
621

    
622
function compose_url_prameterstr($parameters = array()){
623
  $pstr = '';
624
  foreach($parameters as $key=>$value){
625
     $pstr .= ($pstr ? '&' :'').$key.'='.urlencode($value);
626
  }
627
  return $pstr;
628
}
629

    
(5-5/9)