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