summaryrefslogtreecommitdiff
path: root/php/helpers.php
blob: b86b42425ec94aff42b184b7f9881ac6bf98c087 (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
<?php
  // This file is in the public domain.

  /**
   * If '$arr[$idx]' exists, return it. Otherwise
   * set '$arr[$idx]' to '$default' and then return it
   * as well.
   */
  function &pull(&$arr, $idx, $default) {
    if (!isset($arr[$idx])) {
      $arr[$idx] = $default;
    }
    return $arr[$idx];
  }

  /**
   * Concatenates '$base' and '$path'.  Typically used
   * to add the path (represented by '$path') to a base URL
   * (represented by '$base').
   */
  function url_join($base, $path) {
    // Please note that this simplistic way of joining URLs is
    // to avoiding using pecl_http (painful installation!) and
    // to NOT bloat too much tutorial code.
    return $base . $path;
  }

  /**
   * Construct a URL having the host where the script is
   * running as the base URL, and concatenating '$path' to
   * it.  NOTE: $path must have a leading '/'.
   */
  function url_rel($path){
    // Make sure 'REQUEST_SCHEME' is http/https, as in some setups it may
    // be "HTTP/1.1".
    return $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].$path;
  }

  /**
   * Take date in Taler format, as "/Date(timestamp)/", and
   * convert it in a human-readable string.
   */
  function get_pretty_date($taler_date){
    $match = array();
    $timestamp = preg_match('/\/Date\(([0-9]+)\)\//', $taler_date, $match);
    $date = new DateTime();
    $date->setTimestamp(intval($match[1]));
    return $date->format('d/M/Y H:i:s');
  }

  /**
   * Takes amount object in Taler format, and converts it
   * in a human-readable string.  NOTE: Taler amounts objects
   * come from JSON of the form:
   * '{"value" x, "fraction": y, "currency": "CUR"}'
   */
  function get_amount($taler_amount){
    $PRECISION = 100000000;
    $fraction = $taler_amount->fraction / $PRECISION;
    $number = $taler_amount->value + $fraction;
    return sprintf("%s %s", $number, $taler_amount->currency);
  }

?>