Project

General

Profile

Download (17.9 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
      'type' => MENU_NORMAL_ITEM,
69
    );
70

    
71
    $items[] = array(
72
	    'path' => 'cdm_dataportal/names',
73
	    'callback' => 'cdm_dataportal_view_names',
74
	    'access' => true,
75
	    'type' => MENU_CALLBACK, 
76
    );
77
    // optional callback arguments: page
78
     
79
    $items[] = array(
80
	    'path' => 'cdm_dataportal/taxon',
81
	    'callback' => 'cdm_dataportal_view_taxon',
82
	    'access' => true,
83
	    'type' => MENU_CALLBACK, 
84
    // expected callback arguments: name_uuid
85
    );
86
    
87
    $items[] = array(
88
      'path' => 'cdm_dataportal/search/taxon',
89
      'callback' => 'cdm_dataportal_view_search_taxon',
90
      'access' => true,
91
      'type' => MENU_CALLBACK, 
92
    );
93
    
94
    $items[] = array(
95
      'path' => 'cdm_dataportal/filter',
96
      'callback' => 'cdm_dataportal_view_filter',
97
      'access' => true,
98
      'type' => MENU_CALLBACK, 
99
    );
100
    
101
    $items[] = array(
102
      'path' => 'cdm/xml2json',
103
      'callback' => 'cdm_view_xml2json',
104
      'access' => true,
105
      'type' => MENU_CALLBACK, 
106
    );
107
     
108
  }
109
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal').'/cdm_dataportal.css');
110
  //drupal_add_css(drupal_get_path('module', 'cdm_dataportal').'/cdm_dataportal_print.css', 'print');
111
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal').'/cdm_dataportal_screen.css', 'screen');
112
  return $items;
113
  
114
}
115

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

    
161

    
162
/**
163
 * Implementation of hook_validate()
164
 *
165
 * @param $element
166
 */
167
function cdm_dataportal_settings_validate($form_id, $form_values){
168
  if (!str_endsWith($form_values['cdm_webservice_url'], '/')) {
169
    form_set_error('cdm_webservice_url', t("The URL to the CDM Web Service must end with a slash: '/'."));
170
  }
171
}
172

    
173
function cdm_dataportal_search_taxon_form(){
174
  
175
  $url = 'cdm_dataportal/search/taxon';
176
  $form['#method'] = 'get';
177
  $form['#process'] = array('cdm_dataportal_search_process' => array());
178
  $form['#action'] = url($url, NULL, NULL, true);
179
  
180
  $form['queryString'] = array(
181
    '#type' => 'textfield',
182
    '#size' => 20,
183
    '#attributes' => array('title' => t('Enter the name or part of a name you wish to search for.')),
184
    '#default_value' => (isset($_SESSION['cdm']['search']['queryString']) ? $_SESSION['cdm']['search']['queryString'] : ''),
185
  );
186
  $form['onlyAccepted'] = array(
187
    '#type' => 'checkbox',
188
    '#title' => t('Only Accepted'),
189
    '#attributes' => array('title' => t('Search only for taxa which are accepted by the current treatment.')),
190
    '#default_value' => isset($_SESSION['cdm']['search']['onlyAccepted']) && $_SESSION['cdm']['search']['onlyAccepted'],
191
  );
192
  /*
193
  $form['vernacular'] = array(
194
    '#type' => 'checkbox',
195
    '#title' => t('Vernacular Names'),
196
    '#attributes' => array('title' => t('Search for vernacular names.')),
197
    '#default_value' => isset($_SESSION['cdm']['search']['vernacular']) && $_SESSION['cdm']['search']['vernacular'],
198
  );
199
  $form['language'] =  array(
200
    '#type' => 'select',
201
    '#title' => t('Language'),
202
    '#options' => array(
203
        '*' => t('ALL')
204
        ),
205
    '#description'   => t('The language of the vernacular name'),
206
    '#default_value' => (isset($_SESSION['cdm']['search']['language']) ? $_SESSION['cdm']['search']['language'] : ''),
207
  );
208
  */
209
  $form['page'] = array(
210
  '#type' => 'hidden',
211
  '#value' => '1',
212
  );
213
  
214
  $form['submit'] = array(
215
  '#type' => 'submit',
216
  '#name' => '', 
217
  '#value' => t('Search'),
218
  );
219
  
220
  // clean URL get forms breaks if we don't give it a 'q'.
221
  if (!(bool)variable_get('clean_url', '0')) {
222
    $form['q'] = array(
223
      '#type' => 'hidden',
224
      '#value' => $url,
225
      '#name' => 'q',
226
    );
227
  }
228
  return $form;
229
}
230

    
231

    
232
function cdm_dataportal_search_process($form) {
233
  unset($form['form_id']);
234
  unset($form['form_token']);
235
  return $form;
236
}
237

    
238
/**
239
 * Filters $_REQUEST by a list of valid request  parameters and also sets defaults if required.
240
 * returns the processed request parameters submitted by the search form.
241
 */
242
function cdm_dataportal_search_form_request(){
243
  // keys map $REQUEST Keys values are optional default parameters if not null
244
  static $search_form_params = array('queryString'=>null, 'onlyAccepted' =>'0', 'page'=>null);
245
  
246
  $form_params = array();
247
  foreach($search_form_params as $key=>$default ){
248
    $form_params[$key] = ( isset($_REQUEST[$key]) && $_REQUEST[$key] != '' ? $_REQUEST[$key] : $default);
249
  }
250
  return $form_params;
251
}
252
  
253

    
254
/*
255
function cdm_dataportal_search_taxon_form_submit($form_id, $form_values) {
256
  
257
  $_SESSION['cdm']['search'] = $form_values;
258
  //return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['vernacular']?'1':'0').'/'.$form_values['language'];      
259
  return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['onlyAccepted']?'1':'0');  
260
  //$paramstr = compose_url_prameterstr($form_values);
261
  //return url('/cdm_dataportal/search/taxon/', $paramstr);
262
}
263
*/
264
/* ====================== menu callback functions ====================== */
265

    
266
/**
267
 * Generate main administration form.
268
 *
269
 * @return
270
 *   An array containing form items to place on the module settings page.
271
 */
272
function cdm_dataportal_settings(){
273

    
274
  $form = cdm_api_settings_form();
275

    
276
  //TODO: settings are still incomplete, compare with trunk/dataportal/inc/config_default.php.inc
277
  $form['cdm_dataportal'] = array(
278
      '#type' => 'fieldset',
279
      '#title' => t('CDM DataPortal'),
280
      '#collapsible' => FALSE,
281
      '#collapsed' => TRUE,
282
  );
283
  $allSecRefs = cdm_ws_get(CDM_WS_SEC_REFERENCES_ALL);
284
  $secRef_default = isset($allSecRefs[0]) ? $allSecRefs[0] : false;
285
  $secUuid_options = array();
286
  foreach($allSecRefs as $ref){
287
    $secUuid_options[$ref->uuid] =  $ref->citation.($ref->year ? ' ['.$ref->year.']' : '');
288
  }
289
  $form['cdm_dataportal']['cdm_secUuid_default'] =  array(
290
    '#type' => 'select',
291
    '#title'         => t('Default Concept Reference'),
292
    '#options' => $secUuid_options,
293
    '#default_value' => variable_get('cdm_secUuid_default', $secRef_default->uuid),
294
    '#description'   => t('The default \'sensu\' reference to start the cdm_dataportal with. Per user choices are possible and may override this value.'),
295
  );
296
   
297
  return system_settings_form($form);
298
}
299

    
300

    
301
/**
302
 * Displays a list of the known taxonomic names. Long lists are split up into multiple pages
303
 *
304
 * TODO: parameters are still preliminar
305
 * @param String $page page number to diplay defaults to page 1
306
 * @param boolean $hide_unaccepted whether to hide nams which are not accepted by the current view
307
 */
308
function cdm_dataportal_view_names($beginsWith = 'A', $page = 1, $onlyAccepted = false ){
309

    
310
  $request_params  = array(
311
    'q' => $beginsWith, 
312
         //'sec' = '',
313
         //'higherTaxa' => getFiters(),
314
          // 'matchAnywhere' => false, // default is false
315
    'page' => $page, 
316
    'onlyAccepted' => $onlyAccepted, 
317
    'pagesize' => 20  /*$_SESSION['cdm']['namelist_pagesize'] */);
318
  
319
  $taxonSTOs = cdm_ws_get(CDM_WS_FIND_TAXA, $request_params);
320
  /*
321
   * FIXME the filter for accepted names will be a form element, thus this widget
322
   * should be generated via form api preferably as block
323
   */
324
  //$out  = theme('cdm_dataportal_widget_filter_accepted', $onlyAccepted);
325
  //$out .= theme('cdm_dataportal_widget_names_list', $names, $page);
326
  $out .= theme('cdm_listof_taxa', $taxonSTOs);
327
  return $out;
328
}
329

    
330

    
331
/**
332
 * The taxon page gives detailed information on a taxon, it shows:
333
 *  - Taxon name
334
 *  - Full list of synonyms homotypic synonyms on top, followed by the
335
 *    heterotypic and finally followed by misapplied names.
336
 *    The list is ordered historically.
337
 *  - All facts associated with the very taxon concept and taxon name.
338
 *
339
 * @param String $uuid the UUID of the taxon
340
 */
341
function cdm_dataportal_view_taxon($uuid, $arg2 = null){
342

    
343

    
344
  if(isset($arg2) && !is_numeric($arg2)){
345
   
346
    switch ($args[0]){
347
      case 'alternatives':
348
        $alternatives = cdm_ws_get(CDM_WS_TAXON_ALTERNATIVES, $uuid);
349
        return theme('cdm_alternative_taxa', $alternatives);
350
    }
351
    
352
  } else {
353
  
354
    // display the page for the taxon defined by $uuid
355
    $taxonTO = cdm_ws_get(CDM_WS_TAXON ,$uuid);
356
  
357
    _cdm_dataportal_set_currentSecUuid($taxonTO->secUuid);
358
  
359
    drupal_set_title(theme('cdm_taxon', $taxonTO, true));
360
    //TODO retrieve complete synonymy and other data
361
  
362
    $out = theme('cdm_taxon_page', $taxonTO);
363
    return $out;
364
  }
365
}
366

    
367

    
368

    
369
/**
370
 * Expected URL request parameters:
371
 *  - text
372
 *  - language
373
 *  - vernacular
374
 * 
375
 * future extensions to meet palmweb mockup requirements:
376
 *  - habitat
377
 *  - uses
378
 *  - conservation status
379
 *  - locality / tdwg region
380
 */
381
function cdm_dataportal_view_search_taxon(){
382
  
383
  $request_params = cdm_dataportal_search_form_request();
384
  $sw_params = array_replace_key($request_params, array('queryString'=> 10 ));
385
  //FIXME remove debug code:
386
  $sw_params['page'] = '1'; // DEBUG code
387
  $resultPageSTO = cdm_ws_get(CDM_WS_FIND_TAXA, $sw_params);
388
  $resultPageSTO->pageNumber = $request_params['page'];
389
  return theme('cdm_search_results', $resultPageSTO, 'cdm_dataportal/search/taxon', $request_params);
390
}
391

    
392
/**
393
 * filters on children override already set parent filters and vice verca
394
 *
395
 * @param unknown_type $op
396
 * @param unknown_type $taxonUuid
397
 * @return unknown
398
 */
399
function cdm_dataportal_view_filter($op, $taxonUuid = null){
400
  
401
  if(!isset($_SESSION['cdm']['filters'])){
402
    $_SESSION['cdm']['filters'] = array();
403
  }
404
  if($taxonUuid || $op == 'list'){
405
    switch($op){
406
      case 'add':
407
        $parents = cdm_ws_get(CDM_WS_TREENODE_PARENTS, $taxonUuid);
408
        // pop off last element since this is the TreeNode object for $taxonUuid!
409
        $this_node = array_pop($parents);
410
        // will contain the uuid of the parent nodes excluding the $taxonUuid node itself
411
        $parent_uuids = array();
412
        
413
        // children override parents rule: remove all parent filters, 
414
        foreach($parents as $pnode){
415
          unset($_SESSION['cdm']['filters'][$pnode->uuid]);
416
          $parent_uuids[] = $pnode->uuid;
417
        }
418
        
419
        // search for potential children of this $taxonUuid
420
        foreach($_SESSION['cdm']['filters'] as $uuid=>$node){
421
          if(in_array($taxonUuid, $node->parentUuids)){
422
            unset($_SESSION['cdm']['filters'][$node->uuid]);
423
          }
424
        }
425
        // finally add this $taxonUuid as new filter
426
        $this_node->parentUuids = $parent_uuids;
427
        $_SESSION['cdm']['filters'][$taxonUuid] = $this_node;
428
        break;
429
      case 'remove':
430
        unset($_SESSION['cdm']['filters'][$taxonUuid]);
431
        break;
432
      case 'list':
433
        //TODO put in theme!!!
434
        $out = '<ul>';
435
        foreach($_SESSION['cdm']['filters'] as $uuid=>$node){
436
          $out .= '<li>'.cdm_dataportal_shortname_of($node).' '.l('[x]', 'cdm_dataportal/filter/remove/'.$uuid, array(), drupal_get_destination()).'</li>';
437
        }
438
        $out .= '</ul>';
439
        return $out;
440
    }
441
  }
442
  if($_REQUEST['destination']){
443
    $destination = $_REQUEST['destination'];
444
    unset($_REQUEST['destination']);
445
    drupal_goto($destination);
446
  }
447
}
448

    
449

    
450
function cdm_view_xml2json(){
451
  $file = arg(2);
452
  $datastr = get_content(variable_get('cdm_webservice_url', '').$file);
453
  return  xml2json::transformXmlStringToJson($datastr);
454

    
455
}
456

    
457
/**
458
 * Get a term for the current locale from the $localised_terms array.
459
 * Uses global variable $locale from drupal (see drupal functions locale_initialize() for details)
460
 * Function name is adapted from the drupal function t().
461
 *
462
 */
463
function cdm_dataportal_t($localised_terms){
464
  global $locale;  // drupal variable containing the current locale
465
  return cdm_get_localised_term($localised_terms, $locale);
466
}
467

    
468
/* ====================== other functions ====================== */
469

    
470
/**
471
 * Enter description here...
472
 *
473
 * @param String $uuid the UUID of the taxon
474
 * @return the URL
475
 */
476
function cdm_dataportal_taxon_path($uuid){
477
  return 'cdm_dataportal/taxon/'.$uuid;
478
}
479

    
480
/**
481
 * Creates a short taxonname by using the taggename field of NameSTO or NameTO instances.
482
 * If the taggename if empty the fullname will be returned.
483
 *
484
 * @param unknown_type $NameSTO a NameSTO, TreeNode or NameTO instance
485
 * @return string
486
 */
487
function cdm_dataportal_shortname_of($NameSTO){
488

    
489
  $name = trim(cdm_taggedtext_value($NameSTO->taggedName, 'name'));
490
  if($name){
491
    if( $pos = stripos($name, ' ')){
492
      return substr($name, 0, 1).'. '.substr($name, $pos);
493
    } else {
494
      return $name;
495
    }
496
  } else {
497
    return $NameSTO->fullname;
498
  }
499
}
500

    
501
/**
502
 * Sets the secUuid of the $taxonTO parameter to the current secUuid which is stored in the users session
503
 *
504
 * @param TaxonTO $taxonTO
505
 */
506
function _cdm_dataportal_set_currentSecUuid($secUuid){
507

    
508
  if( !isset($_SESSION['cdm']['currentSecRef']['uuid']) ||  $_SESSION['cdm']['currentSecRef']['uuid'] != $secUuid){
509
    $secRef = cdm_ws_get(CDM_WS_REFERENCE ,$secUuid);
510
    $_SESSION['cdm']['currentSecRef'] = (array)$secRef;
511
  }
512
}
513

    
514
/**
515
 * returns the current secRef array from the users session. 
516
 * If the according session variable is not jet set the default
517
 * as configured in the setting is used.
518
 * 
519
 * currentSecRef['uuid']
520
 * currentSecRef[....
521
 *
522
 * @return array
523
 */
524
function _cdm_dataportal_currentSecRef_array(){
525
  
526
  if( !isset($_SESSION['cdm']['currentSecRef']['uuid'])){
527
     $secUuid = variable_get('cdm_secUuid_default', false);
528
     _cdm_dataportal_set_currentSecUuid($secUuid);
529
  }
530
  return  $_SESSION['cdm']['currentSecRef'];
531
}
532

    
533
/**
534
 * @param $str the string to truncate
535
 * @param $len the maximun length
536
 * @param $appendix an optional appendix.
537
 *
538
 * @return the string truncated to the specified length or the original string as given as parameter.
539
 * if an appendix has been defined the resulting string
540
 * will have the specified length inculding the the appendix.
541
 */
542
function str_trunk(&$str, $len, $appendix=''){
543
  if(strlen($str) >= $len )
544
  return  substr($str, 0, $len - strlen($appendix)).$appendix;
545
  else
546
  return $str;
547
}
548

    
549
/**
550
 * @param string $str
551
 * @param string $sub
552
 * @return boolean
553
 */
554
function str_beginsWith( $str, $sub ) {
555
  return ( substr( $str, 0, strlen( $sub ) ) === $sub );
556
}
557

    
558
/**
559
 *
560
 * @param string $str
561
 * @param string $sub
562
 * @return boolean
563
 */
564
function str_endsWith( $str, $sub ) {
565
  return ( substr( $str, strlen( $str ) - strlen( $sub ) ) === $sub );
566
}
567

    
568

    
569
function array_replace_key($array, $replace_map){
570
  foreach($replace_map as $key=>$newkey){
571
    if(isset($array[$key])){
572
      $array[$newkey] = $array[$key];
573
      unset($array[$key]);
574
    }
575
  }
576
  return $array;
577
}
578

    
579

    
580
function compose_url_prameterstr($parameters = array()){
581
  $pstr = '';
582
  foreach($parameters as $key=>$value){
583
     $pstr .= ($pstr ? '&' :'').$key.'='.urlencode($value);
584
  }
585
  return $pstr;
586
}
(4-4/7)