]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/Units.php
New simple interface to the units call. No fallback on windows yet (requires cygwin)
[SourceForge/phpwiki.git] / lib / Units.php
1 <?php rcs_id('$Id: Units.php,v 1.1 2007-01-03 21:22:48 rurban Exp $');
2 /**
3  * Interface to man units(1), /usr/share/units.dat
4  *
5  * $ units "372.0 mi2"
6  *         Definition: 9.6347558e+08 m^2
7  * $ units "372.0 mi2" m^2
8  *         Definition: 9.6347558e+08 m^2
9  *
10  * Windows requires the cygwin /usr/bin/units. 
11  * CHECK: All successfully parsed unit definitions might be stored in the wikidb,
12  * so that subsequent expansions will not require /usr/bin/units be called again.
13  * So far even on windows (cygwin) the process is fast enough.
14  */
15
16 class Units {
17     function Units ($UNITSFILE = false) {
18         if (DISABLE_UNITS)
19             $this->errcode = 1;
20         elseif (defined("UNITS_EXE")) // ignore dynamic check
21             $this->errcode = 0;
22         else
23             exec("units m2",$o,$this->errcode);
24     }
25
26     function Definition ($query) {
27         static $Definitions = array();
28         if (isset($Definitions[$query])) return $Definitions[$query];
29         if ($this->errcode)
30             return $query;
31         $query = preg_replace("/,/","", $query);
32         $def = $this->_cmd("\"$query\"");
33         if (preg_match("/Definition: (.+)$/",$def,$m))
34             return ($Definitions[$query] = $m[1]);
35         else {
36             trigger_error("units: ". $def, E_USER_WARNING);
37             return '';
38         }
39     }
40
41     function basevalue($query, $def = false) {
42         if (!$def) $def = $this->Definition($query);
43         if ($def) {
44             if (is_numeric($def)) // e.g. "1 million"
45                 return $def;
46             if (preg_match("/^([-0-9].*) \w.*$/",$def,$m))
47                 return $m[1];
48         }
49         return '';
50     }
51
52     function baseunit($query, $def  = false) {
53         if (!$def) $def = $this->Definition($query);
54         if ($def) {
55             if (preg_match("/ (.+)$/",$def,$m))
56                 return $m[1];
57         }
58         return '';
59     }
60
61     function _cmd($args) {
62         if ($this->errcode) return $args;
63         if (defined("UNITS_EXE")) {
64             $s = UNITS_EXE ." $args";
65             $result = `$s`;
66         }
67         else 
68             $result = `units $args`;
69         return trim($result);
70     }
71 }