Refactored time_to_decimal for clarity.
[timetracker.git] / WEB-INF / lib / common.lib.php
1 <?php
2 // +----------------------------------------------------------------------+
3 // | Anuko Time Tracker
4 // +----------------------------------------------------------------------+
5 // | Copyright (c) Anuko International Ltd. (https://www.anuko.com)
6 // +----------------------------------------------------------------------+
7 // | LIBERAL FREEWARE LICENSE: This source code document may be used
8 // | by anyone for any purpose, and freely redistributed alone or in
9 // | combination with other software, provided that the license is obeyed.
10 // |
11 // | There are only two ways to violate the license:
12 // |
13 // | 1. To redistribute this code in source form, with the copyright
14 // |    notice or license removed or altered. (Distributing in compiled
15 // |    forms without embedded copyright notices is permitted).
16 // |
17 // | 2. To redistribute modified versions of this code in *any* form
18 // |    that bears insufficient indications that the modifications are
19 // |    not the work of the original author(s).
20 // |
21 // | This license applies to this document only, not any other software
22 // | that it may be combined with.
23 // |
24 // +----------------------------------------------------------------------+
25 // | Contributors:
26 // | https://www.anuko.com/time_tracker/credits.htm
27 // +----------------------------------------------------------------------+
28
29         /**
30          * @return unknown
31          * @param file unknown
32          * @param version = "" unknown
33          * @desc Loads a class
34          */
35         function import( $class_name ) {
36             $libs = array(
37                         dirname($_SERVER["SCRIPT_FILENAME"]),
38                         LIBRARY_DIR
39                 );
40
41             $pos = strpos($class_name, ".");
42         if (!($pos === false)) {
43             $peaces = explode(".", $class_name);
44             $p = "";
45             for ($i=0; $i<count($peaces)-1; $i++) {
46                 $p = $p . "/" . $peaces[$i];
47             }
48                         $libs = array_merge(array(LIBRARY_DIR . $p),$libs);
49             $class_name = $peaces[count($peaces)-1];
50         }
51
52                 $filename = $class_name . '.class.php';
53
54                 foreach($libs as $lib) {
55                         $inc_filename = $lib . '/' . $filename;
56                         if (file_exists($inc_filename)) {
57                                         require_once($inc_filename);
58                                         return $class_name;
59                         }
60                 }
61
62                 print '<br><b>load_class: error loading file "'.$filename.'"</b>';
63                 die();
64         }
65
66         // The mu_sort function is used to sort a multi-dimensional array.
67         // It looks like the code example is taken from the PHP manual http://ca2.php.net/manual/en/function.sort.php
68         function mu_sort($array, $key_sort) {
69                 $n = 0;
70                 if (!is_array($array) || count($array)==0)
71                         return array();
72
73                 $key_sorta = explode(",", $key_sort);
74                 $keys = array_keys($array[0]);
75
76                 for($m=0; $m < count($key_sorta); $m++) {
77                         $nkeys[$m] = trim($key_sorta[$m]);
78                 }
79                 $n += count($key_sorta);
80
81                 for($i=0; $i < count($keys); $i++) {
82                         if(!in_array($keys[$i], $key_sorta)) {
83                                 $nkeys[$n] = $keys[$i];
84                                 $n += "1";
85                         }
86                 }
87
88                 for($u=0;$u<count($array); $u++) {
89                         $arr = $array[$u];
90                         for($s=0; $s<count($nkeys); $s++) {
91                                 $k = $nkeys[$s];
92                                 $output[$u][$k] = $array[$u][$k];
93                         }
94                 }
95                 sort($output);
96                 return $output;
97         }
98
99         /**
100          * return float type
101          *
102          * @param unknown $value
103          * @return unknown
104          */
105         function toFloat($value) {
106                 if (isset($value) && (strlen($value) > 0)) {
107                         $value = str_replace(",",".",$value);
108                         return floatval($value);
109                 }
110                 return null;
111         }
112
113         function stripslashes_deep($value) {
114             $value = is_array($value) ?
115                 array_map('stripslashes_deep', $value) :
116                 stripslashes($value);
117         return $value;
118         }
119
120         function &getConnection() {
121         if (!isset($GLOBALS["_MDB2_CONNECTION"])) {
122
123                 require_once('MDB2.php');
124
125                 $mdb2 = MDB2::connect(DSN);
126                         if (is_a($mdb2, 'PEAR_Error')) {
127                         die($mdb2->getMessage());
128                         }
129
130                         $mdb2->setOption('debug', true);
131                         $mdb2->setFetchMode(MDB2_FETCHMODE_ASSOC);
132                         
133                         $GLOBALS["_MDB2_CONNECTION"] = $mdb2;
134         }
135         return $GLOBALS["_MDB2_CONNECTION"];
136         }
137
138
139         function closeConnection() {
140                 if (isset($GLOBALS["_DB_CONNECTION"])) {
141                         $GLOBALS["_DB_CONNECTION"]->close();
142                         unset($GLOBALS["_DB_CONNECTION"]);
143                 }
144         }
145
146 // time_to_decimal converts a time string such as 1:15 to its decimal representation such as 1.25 or 1,25.
147 function time_to_decimal($val) {
148   global $user;
149   $parts = explode(':', $val); // parts[0] is hours, parts[1] is minutes.
150
151   $minutePercent = round($parts[1]*100/60); // Integer value (0-98) of percent of minutes portion in the hour.
152   if($minutePercent < 10) $minutePercent = '0'.$minutePercent; // Pad small values with a 0 to always have 2 digits.
153
154   $decimalTime = $parts[0].$user->decimal_mark.$minutePercent; // Construct decimal representation of time value.
155
156   return $decimalTime;
157 }
158
159 function sec_to_time_fmt_hm($sec)
160 {
161   return sprintf("%d:%02d", $sec / 3600, $sec % 3600 / 60);
162 }
163
164 function magic_quotes_off()
165 {
166   // if (get_magic_quotes_gpc()) { // This check is now done before calling this function.
167     $_POST = array_map('stripslashes_deep', $_POST);
168     $_GET = array_map('stripslashes_deep', $_GET);
169     $_COOKIE = array_map('stripslashes_deep', $_COOKIE);
170   // }
171 }
172
173 // check_extension checks whether a required PHP extension is loaded and dies if not so.
174 function check_extension($ext)
175 {
176   if (!extension_loaded($ext))
177     die("PHP extension '{$ext}' is required but is not loaded. Read Time Tracker Install Guide for help.");
178 }
179
180 // isTrue is a helper function to return correct false for older config.php values defined as a string 'false'.
181 function isTrue($val)
182 {
183   return ($val == false || $val === 'false') ? false : true;
184 }
185
186 // ttValidString is used to check user input to validate a string.
187 function ttValidString($val, $emptyValid = false)
188 {
189   $val = trim($val);
190   if (strlen($val) == 0 && !$emptyValid)
191     return false;
192     
193   // String must not be XSS evil (to insert JavaScript).
194   if (stristr($val, '<script>') || stristr($val, '<script '))
195     return false;
196     
197   return true;    
198 }
199
200 // ttValidEmail is used to check user input to validate an email string.
201 function ttValidEmail($val, $emptyValid = false)
202 {
203   $val = trim($val);
204   if (strlen($val) == 0)
205     return ($emptyValid ? true : false);
206         
207   // String must not be XSS evil (to insert JavaScript).
208   if (stristr($val, '<script>') || stristr($val, '<script '))
209     return false;
210     
211   // Validate a single email address. TODO: improve for compliancy with RFC.
212   if (!preg_match("/^[_a-zA-Z\d\'-\.]+@([_a-zA-Z\d\-]+(\.[_a-zA-Z\d\-]+)+)$/", $val))
213     return false;
214   
215   return true;    
216 }
217
218 // ttValidEmailList is used to check user input to validate an email string.
219 function ttValidEmailList($val, $emptyValid = false)
220 {
221   $val = trim($val);
222   if (strlen($val) == 0)
223     return ($emptyValid ? true : false);
224         
225   // String must not be XSS evil (to insert JavaScript).
226   if (stristr($val, '<script>') || stristr($val, '<script '))
227     return false;
228     
229   // Validates a list of email addresses separated by a comma with optional spaces.
230   if (!preg_match("/^[_a-zA-Z\d\'-\.]+@([_a-zA-Z\d\-]+(\.[_a-zA-Z\d\-]+)+)(,\s*[_a-zA-Z\d\'-\.]+@([_a-zA-Z\d\-]+(\.[_a-zA-Z\d\-]+)+))*$/", $val))
231     return false;
232     
233   return true;
234 }
235
236 // ttValidFloat is used to check user input to validate a float value.
237 function ttValidFloat($val, $emptyValid = false)
238 {
239   $val = trim($val);
240   if (strlen($val) == 0)
241     return ($emptyValid ? true : false);
242     
243   global $user;
244   $decimal = $user->decimal_mark;
245         
246   if (!preg_match('/^-?[0-9'.$decimal.']+$/', $val))
247     return false;
248     
249   return true;    
250 }
251
252 // ttValidDate is used to check user input to validate a date.
253 function ttValidDate($val)
254 {
255   $val = trim($val);
256   if (strlen($val) == 0)
257     return false;
258
259   // This should accept a string in format 'YYYY-MM-DD', 'MM/DD/YYYY', 'DD.MM.YYYY', or 'DD.MM.YYYY whatever'.
260   if (!preg_match('/^\d\d\d\d-\d\d-\d\d$/', $val) &&
261     !preg_match('/^\d\d\/\d\d\/\d\d\d\d$/', $val) &&
262     !preg_match('/^\d\d\.\d\d\.\d\d\d\d$/', $val) &&
263     !preg_match('/^\d\d\.\d\d\.\d\d\d\d .+$/', $val))
264     return false;
265     
266   return true;    
267 }
268
269 // ttValidInteger is used to check user input to validate an integer.
270 function ttValidInteger($val, $emptyValid = false)
271 {
272   $val = trim($val);
273   if (strlen($val) == 0)
274     return ($emptyValid ? true : false);
275     
276   if (!preg_match('/^[0-9]+$/', $val))
277     return false;
278
279   return true;
280 }
281
282 // ttValidCronSpec is used to check user input to validate cron specification.
283 function ttValidCronSpec($val)
284 {
285   // This code is adapted from http://stackoverflow.com/questions/235504/validating-crontab-entries-w-php
286   $numbers= array(
287      'min'=>'[0-5]?\d',
288      'hour'=>'[01]?\d|2[0-3]',
289      'day'=>'0?[1-9]|[12]\d|3[01]',
290      'month'=>'[1-9]|1[012]',
291      'dow'=>'[0-7]'
292   );
293
294   foreach($numbers as $field=>$number) {
295     $range= "($number)(-($number)(\/\d+)?)?";
296     $field_re[$field]= "\*(\/\d+)?|$range(,$range)*";
297   }
298
299   $field_re['month'].='|jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec';
300   $field_re['dow'].='|mon|tue|wed|thu|fri|sat|sun';
301
302   $fields_re= '('.join(')\s+(', $field_re).')';
303
304   /*
305   $replacements= '@reboot|@yearly|@annually|@monthly|@weekly|@daily|@midnight|@hourly';
306
307   $regexp = '^\s*('.
308                 '$'.
309                 '|#'.
310                 '|\w+\s*='.
311                 "|$fields_re\s+\S".
312                 "|($replacements)\s+\S".
313             ')';
314    */
315   // The above block from the link did not work for me.
316
317   // But this works.
318   $regexp = '/^'.$fields_re.'$/';
319         
320   if (!preg_match($regexp, $val))
321     return false;
322
323   return true;
324 }
325
326 // ttAccessCheck is used to check whether user is allowed to proceed. This function is used
327 // as an initial check on all publicly available pages.
328 function ttAccessCheck($required_rights)
329 {
330   global $auth;
331   global $user;
332   
333   // Redirect to login page if user is not authenticated.
334   if (!$auth->isAuthenticated()) {
335     header('Location: login.php');
336     exit();
337   }
338   
339   // Check rights.
340   if (!($required_rights & $user->rights))
341     return false;
342     
343   return true;
344 }