aboutsummaryrefslogtreecommitdiff
path: root/classes/BiblioIsisDb.php
blob: d32f548314329d52ba3492a5eee84e9057b8a0ed (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
<?php

/**
 * Biblio::Isis implementation of IsisDb.
 */
class BiblioIsisDb implements IsisDb {
  /**
   * @var $fdt
   *   Field description table.
   */
  var $fdt;

  /**
   * Class instance of a perl interpreter;
   */
  var $perl;

  /**
   * @var $format
   *   Database format, derived from $schema.
   */
  var $format;

  /**
   * @var $log
   *   Class action log.
   */
  var $log;

  /**
   * Constructor.
   *
   * @see IsisDb::__construct()
   */ 
  public function __construct($schema) {
    // Save db schema.
    $this->format = $schema;

    // Setup $fdt.
    foreach ($schema['fields'] as $field => $info) {
      $this->fdt[$field] = $info['name'];
    }

    // Create a perl instance.
    $this->perl = new Perl();
  }

  /**
   * Class logger.
   *
   * @param $message
   *   Log message.
   *
   * @todo
   *   Decide how logging should be implemented.
   */
  function logger($message) {
    $this->log[] = $message;
  }

  /**
   * Send requests to the perl backend.
   *
   * @param $method
   *   Backend method name to invoke.
   *
   * @param $args
   *   Backend method arguments.
   *
   * @return
   *   Backend return value.
   */
  function backend($method = 'count', $args = NULL) {
    // Setup the database.
    $name = $this->format['db']['name'];
    $db   = CinisisDb::file("$name/$name", 'db');

    // Setup arguments.
    if ($args != NULL) {
      $args = '('. $args .')';
    }

    try {
      // Call backend.
      return $this->perl->eval('
        use Biblio::Isis;

        my $isis = new Biblio::Isis(
           isisdb => "'. $db .'",
        );

        return $isis->'. $method . $args .';');
    }
    catch (PerlException $exception) {
      echo __CLASS__ .': Perl error: ' . $exception->getMessage();
      return FALSE;
    }    
  }

  /**
   * Read an entry.
   *
   * @param $id
   *   Record Id.
   *
   * @param $method
   *   Database read method.
   *
   * @see IsisDb::read()
   */  
  public function read($id, $method = 'fetch') {
    // Database query.
    $results = $this->backend($method, $id);

    if ($results) {
      // Tag results.
      $data = $this->tag($results, $method);

      // Charset conversion.
      if (is_array($data)) {
        array_walk_recursive($data, array(__CLASS__, 'charset'));
      }

      // Return the result.
      return $data;
    }
  }

  /**
   * Return number of rows in the database.
   *
   * @see IsisDb::read()
   */  
  public function rows() {
    return $this->backend('count');
  }

  /**
   * Return an example schema.
   *
   * @see IsisDb::example()
   */  
  public function example() {
    return SchemaDb::example();
  }

  /**
   * Check configuration.
   *
   * @see IsisDb::check()
   */  
  static function check($schema, $section = NULL) {
    // Check API availability.
    if (!class_exists('Perl')) {
      throw new Exception('Could not find Perl class. Please check your php-perl installation.');
      return FALSE;
    }

    // Check schema configuration.
    return SchemaDb::check($schema, $section);
  }

  /**
   * Tag results of a db query.
   *
   * This function converts the keys of query result from field numbers
   * to names.
   *
   * @param $results
   *   Database query results.
   *
   * @param $method
   *   Database read method.
   *
   * @return
   *   Tagged database result.
   */
  function tag($results, $method = 'fetch') {
    foreach ($results as $key => $value) {
      // Key '000' used to hold MFN.
      if ($key != '000') {
        if (!isset($this->format['fields'][$key])) {
          continue;
        }

        // Format, repetition and subfield handling.
        $name        = $this->format['fields'][$key]['name'];
        $data[$name] = $this->repetition($key, $value);
        $data[$name] = $this->subfields($data[$name], $key, $method);
      }
    }

    return $data;
  }

  /**
   * Checks whether a field has subfields.
   *
   * @param $key
   *   Field key.
   *
   * @return
   *   True if has subfields, false otherwise.
   */
  function has_subfields($key) {
    if (isset($this->format['fields'][$key]['subfields'])) {
      return TRUE;
    }

    return FALSE;
  }

  /**
   * Switch keys on subfields.
   *
   * @param $key
   *   Field key.
   *
   * @param $value
   *   Dataset.
   */
  function subfields_switch($key, &$value) {
    if (!is_array($value)) {
      return;
    }

    foreach ($value as $subkey => $subvalue) {
      if (isset($this->format['fields'][$key]['subfields'][$subkey])) {
        $subname = $this->format['fields'][$key]['subfields'][$subkey];
      } else {
        $subname = $subkey;
      }

      $value[$subname] = $subvalue;

      if ($subkey != $subname) {
        unset($value[$subkey]);
      }
    }
  }

  /**
   * Makes subfield substitution in a dataset.
   *
   * @param $name
   *   Dataset.
   *
   * @param $key
   *   Field key.
   *
   * @param $method
   *   Database read method.
   *
   * @return
   *   Data with processed subfields.
   */
  function subfields($name, $key, $method) {
    if ($this->has_subfields($key) && is_array($name)) {
      $method = 'subfields_from_'. $method;
      return $this->{$method}($name, $key);
    }
    else {
      foreach ($name as $value) {
        $data[] = array($this->main_field_name($key) => $value);
      }
    }

    return $data;
  }

  /**
   * Subfield handling for data read by 'to_hash' method. This method
   * is not fully supported and therefore not recommended.
   *
   * It does not deal very well when data has "main" fields and
   * subfields (like "data1^adata2^bdata3") and doesn't deal with
   * advanced configuration such as 'join_subfields'.
   *
   * @param $name
   *   Dataset.
   *
   * @param $key
   *   Field key.
   *
   * @return
   *   Data with processed subfields.
   */
  function subfields_from_to_hash($name, $key) {
    if ($this->is_repetitive($key, $name)) {
      foreach ($name as $entry => $value) {
        $this->subfields_switch($key, $value);
        $name[$entry] = $value;
      }
    }
    else {
      $this->subfields_switch($key, $name);
    }

    return $name;
  }

  /**
   * Subfield handling for data read by 'from_fetch' method.
   *
   * @param name$
   *   Dataset.
   *
   * @param $key
   *   Field key.
   *
   * @return
   *   Data with processed subfields.
   */
  function subfields_from_fetch($name, $key) {
    foreach ($name as $entry => $value) {
      if (substr($value, 0, 1) != '^') {
        $field     = preg_replace('/\^.*/', '', $value);
        $subfields = substr($value, strlen($field) + 1);
        $subfields = (!empty($subfields)) ? $subfields = explode('^', $subfields) : array();

        if (isset($field)) {
          $data[$entry]['field'] = $field;
        }
      }
      else {
        $subfields = explode('^', substr($value, 1));
      }

      // Subfield tagging.
      foreach ($subfields as $subfield => $subvalue) {
        $subkey = substr($subvalue, 0, 1);
        if (isset($this->format['fields'][$key]['subfields'][$subkey])) {
          $subkey = $this->format['fields'][$key]['subfields'][$subkey];
        }
        $data[$entry]['subfields'][$subkey] = substr($subvalue, 1);
      }

      // Join subfields and main field if needed.
      if ($this->join_subfields()) {
        $data[$entry] = $data[$entry]['subfields'];
        if (isset($field)) {
          $data[$entry][$this->main_field_name($key)] = $field;
        }
      }
    }

    return $data;
  }

  /**
   * Whether to join field and subfields in a single array.
   *
   * @return
   *   Boolean.
   */
  public function join_subfields() {
    if ($this->format['db']['join_subfields']) {
      return TRUE;
    }

    return FALSE;
  }

  /**
   * Determine the main field name depending on db configuration.
   *
   * @param $key
   *   Field key.
   *
   * @return
   *   Main field name, 'field' by default;
   */
  public function main_field_name($key) {
    if ($this->join_subfields()) {
      return $this->format['fields'][$key]['name'];
    }

    return 'field';
  }

  /**
   * Deals with repetition.
   *
   * As Biblio::Isis always return field values as arrays, we
   * have to check the database schema to see if we want to
   * convert then to a single value.
   *
   * @param $field
   *   Database field.
   *
   * @param $value
   *   Data (with or without repetition).
   *
   * @return
   *   True if repetitive, false otherwise.
   */
  function is_repetitive($field, $value) {
    if (isset($this->format['fields'][$field]['repeat']) &&
      $this->format['fields'][$field]['repeat'] == FALSE) {
        if (is_array($value) && count($value) > 1) {
          $this->logger("$field is configured as non repetitive but data shows a repetition for value". var_dump($value));
        }
        return FALSE;
      }

    return TRUE;
  }

  /**
   * Deals with repetition.
   *
   * As Biblio::Isis always return field values as arrays, we
   * have to check the database schema to see if we want to
   * convert then to a single value. The current implementation
   * is just a placeholder as no conversion is done.
   *
   * @param $key
   *   Database key.
   *
   * @param $value
   *   Query field result.
   *
   * @return
   *   The value according to the repetition config.
   */
  function repetition($key, $value) {
    return $value;
  }

  /**
   * Charset conversion.
   *
   * Converts a string from the database charset to UTF-8.
   *
   * @param $data
   *   String to be converted.
   *
   * @return
   *   String converted to UTF-8.
   */
  function charset(&$data) {
    $data = iconv($this->format['db']['charset'], 'UTF-8', $data);
  }
}