source: trunk/phpgwapi/inc/common_functions.inc.php @ 7655

Revision 7655, 35.5 KB checked in by douglasz, 11 years ago (diff)

Ticket #3236 - Melhorias de performance no codigo do Expresso.

  • Property svn:eol-style set to native
  • Property svn:executable set to *
Line 
1<?php
2         /**************************************************************************\
3         * eGroupWare API - phpgwapi loader                                         *
4         * This file written by Dan Kuykendall <seek3r@phpgroupware.org>            *
5         * and Joseph Engo <jengo@phpgroupware.org>                                 *
6         * Has a few functions, but primary role is to load the phpgwapi            *
7         * Copyright (C) 2000, 2001 Dan Kuykendall                                  *
8         * -------------------------------------------------------------------------*
9         * This library is part of the eGroupWare API                               *
10         * http://www.egroupware.org/api                                            *
11         * ------------------------------------------------------------------------ *
12         * This library is free software; you can redistribute it and/or modify it  *
13         * under the terms of the GNU Lesser General Public License as published by *
14         * the Free Software Foundation; either version 2.1 of the License,         *
15         * or any later version.                                                    *
16         * This library is distributed in the hope that it will be useful, but      *
17         * WITHOUT ANY WARRANTY; without even the implied warranty of               *
18         * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.                     *
19         * See the GNU Lesser General Public License for more details.              *
20         * You should have received a copy of the GNU Lesser General Public License *
21         * along with this library; if not, write to the Free Software Foundation,  *
22         * Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA            *
23         \**************************************************************************/
24
25
26        /****************************************************************************\
27         * Direct functions which are not part of the API classes                    *
28         * because they are required to be available at the lowest level.            *
29         \***************************************************************************/
30        /*!
31         @collection_start direct functions
32         @abstract Direct functions which are not part of the API classes because they are required to be available at the lowest level.
33        */
34
35        /*!
36         @function print_debug_subarray
37         @abstract Not to be used directly. Should only be used by print_debug()
38        */
39        function print_debug_subarray($array)
40        {
41//              while(list($key, $value) = each($array))
42                foreach($array as $key => $value)
43                {
44                        if (is_array($value))
45                        {
46                                $vartypes[$key] = print_debug_subarray($value);
47                        }
48                        else
49                        {
50                                $vartypes[$key] = gettype($value);
51                        }
52                }
53                return $vartypes;
54        }
55
56        /*!
57         @function print_debug
58         @abstract print debug data only when debugging mode is turned on.
59         @author seek3r
60         @discussion This function is used to debugging data.
61         @syntax print_debug('message', $somevar);
62         @example print_debug('this is some debugging data',$somevar);
63        */
64        function print_debug($message,$var = 'messageonly',$part = 'app', $level = 3)
65        {
66//              if (($part == 'app' && EXP_DEBUG_APP == True) || ($part == 'api' && DEBUG_API == True))
67                if (($part == 'app' && DEBUG_APP == True) || ($part == 'api' && DEBUG_API == True))
68                {
69                        if (!defined('DEBUG_OUTPUT'))
70                        {
71                                define('DEBUG_OUTPUT', 1);
72                        }
73                        if ($level >= DEBUG_LEVEL)
74                        {
75                                if (!is_array($var))
76                                {
77                                        if ($var != 'messageonly')
78                                        {
79                                                if (!DEBUG_DATATYPES)
80                                                {
81                                                        $output = "$message\n$var";
82                                                }
83                                                else
84                                                {
85                                                        $output = "$message\n$var is a ".gettype($var);
86                                                }
87                                        }
88                                        else
89                                        {
90                                                $output = $message;
91                                        }
92
93                                        /* Bit 1 means to output to screen */
94                                        if (!!(DEBUG_OUTPUT & 1))
95                                        {
96                                                echo "$output<br>\n";
97                                        }
98                                        /* Bit 2 means to output to sql */
99                                        if (!!(DEBUG_OUTPUT & 2))
100                                        {
101                                                /* Need to flesh this out still. I dont have a table to dump this in yet.*/
102                                                /* So the SQL statement will go here*/
103                                        }
104
105                                        /* Example of how this can be extended to output to other locations as well. This example uses a COM object */
106                                        /*
107                                        if (!!(DEBUG_OUTPUT & 32))
108                                        {
109                                                $obj_debug = new COM('Some_COM_App.Class','localhost');
110                                                if (is_object($obj_debug))
111                                                {
112                                                        $DebugMessage_return = $obj_debug->DebugMessage($output);
113                                                }
114                                        }
115                                        */
116                                }
117                                else
118                                {
119                                        if (floor(phpversion()) > 3 && !!(DEBUG_OUTPUT & 2))
120                                        {
121                                                ob_start();
122                                        }
123                                        echo "<pre>\n$message\n";
124                                        print_r($var);
125                                        if (DEBUG_DATATYPES)
126                                        {
127//                                              while(list($key, $value) = each($var))
128                                                foreach($var as $key => $value)
129                                                {
130                                                        if (is_array($value))
131                                                        {
132                                                                $vartypes[$key] = print_debug_subarray($value);
133                                                        }
134                                                        else
135                                                        {
136                                                                $vartypes[$key] = gettype($value);
137                                                        }
138                                                }
139                                                echo "Data Types:\n";
140                                                print_r($vartypes);
141                                        }
142                                        echo "\n<pre>\n";
143                                        if (floor(phpversion()) > 3 && !!(DEBUG_OUTPUT & 2))
144                                        {
145                                                $output .= ob_get_contents();
146                                                ob_end_clean();
147                                                /* Need to flesh this out still. I dont have a table to dump this in yet.*/
148                                                /* So the SQL statement will go here*/
149                                                if (!!(DEBUG_OUTPUT & 1))
150                                                {
151                                                        echo "$output<br>\n";
152                                                }
153                                        }
154                                }
155                        }
156                }
157        }
158
159        /*!
160         @function safe_args
161         @abstract Allows for array and direct function params as well as sanatization.
162         @author seek3r
163         @discussion This function is used to validate param data as well as offer flexible function usage.
164         @syntax safe_args($expected_args, $recieved_args,__LINE__,__FILE__);
165         @example
166                function somefunc()
167                {
168                        $expected_args[0] = Array('name'=>'fname','default'=>'joe', 'type'=>'string');
169                        $expected_args[1] = Array('name'=>'mname','default'=>'hick', 'type'=>'string');
170                        $expected_args[2] = Array('name'=>'lname','default'=>'bob', 'type'=>'string');
171                        $recieved_args = func_get_args();
172                        $args = safe_args($expected_args, $recieved_args,__LINE__,__FILE__);
173                        echo 'Full name: '.$args['fname'].' '.$args['fname'].' '.$args['lname'].'<br>';
174                        //default result would be:
175                        // Full name: joe hick bob<br>
176                }
177               
178                Using this it is possible to use the function in any of the following ways
179                somefunc('jack','city','brown');
180                or
181                somefunc(array('fname'=>'jack','mname'=>'city','lname'=>'brown'));
182                or
183                somefunc(array('lname'=>'brown','fname'=>'jack','mname'=>'city'));
184               
185                For the last one, when using named params in an array you dont have to follow any order
186                All three would result in - Full name: jack city brown<br>
187               
188                When you use this method of handling params you can secure your functions as well offer
189                flexibility needed for both normal use and web services use.
190                If you have params that are required just set the default as ##REQUIRED##
191                Users of your functions can also use ##DEFAULT## to use your default value for a param
192                when using the standard format like this:
193                somefunc('jack','##DEFAULT##','brown');
194                This would result in - Full name: jack hick brown<br>
195                Its using the default value for the second param.
196                Of course if you have the second param as a required field it will fail to work.
197        */
198        function safe_args($expected, $recieved, $line='??', $file='??')
199        {
200                /* This array will contain all the required fields */
201                $required = Array();
202
203                /* This array will contain all types for sanatization checking */
204                /* only used when an array is passed as the first arg          */
205                $types = Array();
206               
207                /* start by looping thru the expected list and set params with */
208                /* the default values                                          */
209                $num = count($expected);
210                for ($i = 0; $i < $num; ++$i)
211                {
212                        $args[$expected[$i]['name']] = $expected[$i]['default'];
213                        if ($expected[$i]['default'] === '##REQUIRED##')
214                        {
215                                $required[$expected[$i]['name']] = True;
216                        }
217                        $types[$expected[$i]['name']] = $expected[$i]['type'];
218                }
219               
220                /* Make sure they passed at least one param */
221                if(count($recieved) != 0)
222                {
223                        /* if used as standard function we loop thru and set by position */
224                        if(!is_array($recieved[0]))
225                        {
226                        for ($i = 0; $i < $num; ++$i)
227                                {
228                                        if(isset($recieved[$i]) && $recieved[$i] !== '##DEFAULT##')
229                                        {
230                                                if(sanitize($recieved[$i],$expected[$i]['type']))
231                                                {
232                                                        $args[$expected[$i]['name']] = $recieved[$i];
233                                                        unset($required[$expected[$i]['name']]);
234                                                }
235                                                else
236                                                {
237                                                        echo 'Fatal Error: Invalid paramater type for '.$expected[$i]['name'].' on line '.$line.' of '.$file.'<br>';
238                                                        exit;
239                                                }
240                                        }
241                                }
242                        }
243                        /* if used as standard function we loop thru and set by position */
244                        else
245                        {
246                                for ($i = 0; $i < $num; ++$i)
247                                {
248                                        $types[$expected[$i]['name']] = $expected[$i]['type'];
249                                }
250                                while(list($key,$val) = each($recieved[0]))
251                                {
252                                        if($val !== '##DEFAULT##')
253                                        {
254                                                if(sanitize($val,$types[$key]) == True)
255                                                {
256                                                        $args[$key] = $val;
257                                                        unset($required[$key]);
258                                                }
259                                                else
260                                                {
261                                                        echo 'Fatal Error: Invalid paramater type for '.$key.' on line '.$line.' of '.$file.'<br>';
262                                                        exit;
263                                                }
264                                        }
265                                }
266                        }
267                }
268                if(count($required) != 0)
269                {
270                        while (list($key) = each($required))
271                        {
272                                echo 'Fatal Error: Missing required paramater '.$key.' on line '.$line.' of '.$file.'<br>';
273                        }
274                        exit;
275                }
276                return $args;
277        }
278
279        /*!
280         @function sanitize
281         @abstract Validate data.
282         @author seek3r
283         @discussion This function is used to validate input data.
284         @syntax sanitize('type', 'match string');
285         @example sanitize('number',$somestring);
286        */
287
288        /*
289        $GLOBALS['phpgw_info']['server']['sanitize_types']['number'] = Array('type' => 'preg_match', 'string' => '/^[0-9]+$/i');
290        */
291
292        function sanitize($string,$type)
293        {
294                switch ($type)
295                {
296                        case 'bool':
297                                if ($string == 1 || $string == 0)
298                                {
299                                        return True;
300                                }
301                                break;
302                        case 'isprint':
303                                $length = strlen($string);
304                                $position = 0;
305                                while ($length > $position)
306                                {
307                                        $char = substr($string, $position, 1);
308                                        if ($char < ' ' || $char > '~')
309                                        {
310                                                return False;
311                                        }
312                                        $position = $position + 1;
313                                }
314                                return True;
315                                break;
316                        case 'alpha':
317                                if (preg_match("/^[a-z]+$/i", $string))
318                                {
319                                        return True;
320                                }
321                                break;
322                        case 'number':
323                                if (preg_match("/^[0-9]+$/i", $string))
324                                {
325                                        return True;
326                                }
327                                break;
328                        case 'alphanumeric':
329                                if (preg_match("/^[a-z0-9 -._]+$/i", $string))
330                                {
331                                        return True;
332                                }
333                                break;
334                        case 'string':
335                                if (preg_match("/^[a-z]+$/i", $string))
336                                {
337                                        return True;
338                                }
339                                break;
340                        case 'ip':
341                                if (preg_match('/^[0-9]{1,3}(\.[0-9]{1,3}){3}$/i',$string))
342                                {
343                                        $octets = preg_split('/\./',$string);
344                                        for ($i=0; $i != count($octets); ++$i)
345                                        {
346                                                if ($octets[$i] < 0 || $octets[$i] > 255)
347                                                {
348                                                        return False;
349                                                }
350                                        }
351                                        return True;
352                                }
353                                return False;
354                                break;
355                        case 'file':
356                                if (preg_match("/^[a-z0-9_]+\.+[a-z]+$/i", $string))
357                                {
358                                        return True;
359                                }
360                                break;
361                        case 'email':
362                                if (preg_match('/^([[:alnum:]_%+=.-]+)@([[:alnum:]_.-]+)\.([a-z]{2,3}|[0-9]{1,3})$/i',$string))
363                                {
364                                        return True;
365                                }
366                                break;
367                        case 'password':
368                                $password_length = strlen($string);
369                                $password_numbers = Array('0','1','2','3','4','5','6','7','8','9');
370                                $password_special_chars = Array(' ','~','`','!','@','#','$','%','^','&','*','(',')','_','+','-','=','{','}','|','[',']',"\\",':','"',';',"'",'<','>','?',',','.','/');
371
372                                if(@isset($GLOBALS['phpgw_info']['server']['pass_min_length']) && is_int($GLOBALS['phpgw_info']['server']['pass_min_length']) && $GLOBALS['phpgw_info']['server']['pass_min_length'] > 1)
373                                {
374                                        $min_length = $GLOBALS['phpgw_info']['server']['pass_min_length'];
375                                }
376                                else
377                                {
378                                        $min_length = 1;
379                                }
380
381                                if(@isset($GLOBALS['phpgw_info']['server']['pass_require_non_alpha']) && $GLOBALS['phpgw_info']['server']['pass_require_non_alpha'] == True)
382                                {
383                                        $pass_verify_non_alpha = False;
384                                }
385                                else
386                                {
387                                        $pass_verify_non_alpha = True;
388                                }
389                               
390                                if(@isset($GLOBALS['phpgw_info']['server']['pass_require_numbers']) && $GLOBALS['phpgw_info']['server']['pass_require_numbers'] == True)
391                                {
392                                        $pass_verify_num = False;
393                                }
394                                else
395                                {
396                                        $pass_verify_num = True;
397                                }
398
399                                if(@isset($GLOBALS['phpgw_info']['server']['pass_require_special_char']) && $GLOBALS['phpgw_info']['server']['pass_require_special_char'] == True)
400                                {
401                                        $pass_verify_special_char = False;
402                                }
403                                else
404                                {
405                                        $pass_verify_special_char = True;
406                                }
407                               
408                                if ($password_length >= $min_length)
409                                {
410                                        for ($i=0; $i != $password_length; ++$i)
411                                        {
412                                                $cur_test_string = substr($string, $i, 1);
413                                                if (in_array($cur_test_string, $password_numbers) || in_array($cur_test_string, $password_special_chars))
414                                                {
415                                                        $pass_verify_non_alpha = True;
416                                                        if (in_array($cur_test_string, $password_numbers))
417                                                        {
418                                                                $pass_verify_num = True;
419                                                        }
420                                                        elseif (in_array($cur_test_string, $password_special_chars))
421                                                        {
422                                                                $pass_verify_special_char = True;
423                                                        }
424                                                }
425                                        }
426
427                                        if ($pass_verify_num == False)
428                                        {
429                                                $GLOBALS['phpgw_info']['flags']['msgbox_data']['Password requires at least one non-alpha character']=False;
430                                        }
431
432                                        if ($pass_verify_num == False)
433                                        {
434                                                $GLOBALS['phpgw_info']['flags']['msgbox_data']['Password requires at least one numeric character']=False;
435                                        }
436
437                                        if ($pass_verify_special_char == False)
438                                        {
439                                                $GLOBALS['phpgw_info']['flags']['msgbox_data']['Password requires at least one special character (non-letter and non-number)']=False;
440                                        }
441                                       
442                                        if ($pass_verify_num == True && $pass_verify_special_char == True)
443                                        {
444                                                return True;
445                                        }
446                                        return False;
447                                }
448                                $GLOBALS['phpgw_info']['flags']['msgbox_data']['Password must be at least '.$min_length.' characters']=False;
449                                return False;
450                                break;
451                        case 'any':
452                                return True;
453                                break;
454                        default :
455                                if (isset($GLOBALS['phpgw_info']['server']['sanitize_types'][$type]['type']))
456                                {
457                                        if ($GLOBALS['phpgw_info']['server']['sanitize_types'][$type]['type']($GLOBALS['phpgw_info']['server']['sanitize_types'][$type]['string'], $string))
458                                        {
459                                                return True;
460                                        }
461                                }
462                                return False;
463                }
464        }
465
466        function reg_var($varname, $method='any', $valuetype='alphanumeric',$default_value='',$register=True)
467        {
468                if($method == 'any' || $method == array('any'))
469                {
470                        $method = Array('POST','GET','COOKIE','SERVER','FILES','GLOBAL','DEFAULT');
471                }
472                elseif(!is_array($method))
473                {
474                        $method = Array($method);
475                }
476                $cnt = count($method);
477                for($i=0;$i<$cnt;++$i)
478                {
479                        switch(strtoupper($method[$i]))
480                        {
481                                case 'DEFAULT':
482                                        if($default_value)
483                                        {
484                                                $value = $default_value;
485                                                $i = $cnt+1; /* Found what we were looking for, now we end the loop */
486                                        }
487                                        break;
488                                case 'GLOBAL':
489                                        if(@isset($GLOBALS[$varname]))
490                                        {
491                                                $value = $GLOBALS[$varname];
492                                                $i = $cnt+1;
493                                        }
494                                        break;
495                                case 'POST':
496                                case 'GET':
497                                case 'COOKIE':
498                                case 'SERVER':
499                                        if(phpversion() >= '4.1.0')
500                                        {
501                                                $meth = '_'.strtoupper($method[$i]);
502                                        }
503                                        else
504                                        {
505                                                $meth = 'HTTP_'.strtoupper($method[$i]).'_VARS';
506                                        }
507                                        if(@isset($GLOBALS[$meth][$varname]))
508                                        {
509                                                $value = $GLOBALS[$meth][$varname];
510                                                $i = $cnt+1;
511                                        }
512                                        if(get_magic_quotes_gpc() && isset($value))
513                                        {
514                                                // we need to stripslash 3 levels of arrays
515                                                // because of the password function in preferences
516                                                // it's named ['user']['variablename']['pw']
517                                                // or something like this in projects
518                                                // $values['budgetBegin']['1']['year']
519                                                if(@is_array($value))
520                                                {
521                                                        /* stripslashes on the first level of array values */
522                                                        foreach($value as $name => $val)
523                                                        {
524                                                                if(@is_array($val))
525                                                                {
526                                                                        foreach($val as $name2 => $val2)
527                                                                        {
528                                                                                if(@is_array($val2))
529                                                                                {
530                                                                                        foreach($val2 as $name3 => $val3)
531                                                                                        {
532                                                                                                $value[$name][$name2][$name3] = stripslashes($val3);
533                                                                                        }
534                                                                                }
535                                                                                else
536                                                                                {
537                                                                                        $value[$name][$name2] = stripslashes($val2);
538                                                                                }
539                                                                        }
540                                                                }
541                                                                else
542                                                                {
543                                                                        $value[$name] = stripslashes($val);
544                                                                }
545                                                        }
546                                                }
547                                                else
548                                                {
549                                                        /* stripslashes on this (string) */
550                                                        $value = stripslashes($value);
551                                                }
552                                        }
553                                        break;
554                                case 'FILES':
555                                        if(phpversion() >= '4.1.0')
556                                        {
557                                                $meth = '_FILES';
558                                        }
559                                        else
560                                        {
561                                                $meth = 'HTTP_POST_FILES';
562                                        }
563                                        if(@isset($GLOBALS[$meth][$varname]))
564                                        {
565                                                $value = $GLOBALS[$meth][$varname];
566                                                $i = $cnt+1;
567                                        }
568                                        break;
569                                default:
570                                        if(@isset($GLOBALS[strtoupper($method[$i])][$varname]))
571                                        {
572                                                $value = $GLOBALS[strtoupper($method[$i])][$varname];
573                                                $i = $cnt+1;
574                                        }
575                                        break;
576                        }
577                }
578
579                if (@!isset($value))
580                {
581                        $value = $default_value;
582                }
583
584                if (@!is_array($value))
585                {
586                        if ($value == '')
587                        {
588                                $result = $value;
589                        }
590                        else
591                        {
592                                if (sanitize($value,$valuetype) == 1)
593                                {
594                                        $result = $value;
595                                }
596                                else
597                                {
598                                        $result = $default_value;
599                                }
600                        }
601                }
602                else
603                {
604                        reset($value);
605                        while(list($k, $v) = each($value))
606                        {
607                                if ($v == '')
608                                {
609                                        $result[$k] = $v;
610                                }
611                                else
612                                {
613                                        if (is_array($valuetype))
614                                        {
615                                                $vt = $valuetype[$k];
616                                        }
617                                        else
618                                        {
619                                                $vt = $valuetype;
620                                        }
621
622                                        if (sanitize($v,$vt) == 1)
623                                        {
624                                                $result[$k] = $v;
625                                        }
626                                        else
627                                        {
628                                                if (is_array($default_value))
629                                                {
630                                                        $result[$k] = $default_value[$k];
631                                                }
632                                                else
633                                                {
634                                                        $result[$k] = $default_value;
635                                                }
636                                        }
637                                }
638                        }
639                }
640                if($register)
641                {
642                        $GLOBALS['phpgw_info'][$GLOBALS['phpgw_info']['flags']['currentapp']][$varname] = $result;
643                }
644                return $result;
645        }
646
647        /*!
648         @function get_var
649         @abstract retrieve a value from either a POST, GET, COOKIE, SERVER or from a class variable.
650         @author skeeter
651         @discussion This function is used to retrieve a value from a user defined order of methods.
652         @syntax get_var('id',array('HTTP_POST_VARS'||'POST','HTTP_GET_VARS'||'GET','HTTP_COOKIE_VARS'||'COOKIE','GLOBAL','DEFAULT'));
653         @example $this->id = get_var('id',array('HTTP_POST_VARS'||'POST','HTTP_GET_VARS'||'GET','HTTP_COOKIE_VARS'||'COOKIE','GLOBAL','DEFAULT'));
654         @param $variable name
655         @param $method ordered array of methods to search for supplied variable
656         @param $default_value (optional)
657        */
658        function get_var($variable,$method='any',$default_value='')
659        {
660                if(!@is_array($method))
661                {
662                        $method = array($method);
663                }
664                return reg_var($variable,$method,'any',$default_value,False);
665        }
666
667        /*!
668         @function include_class
669         @abstract This will include the class once and guarantee that it is loaded only once.  Similar to CreateObject, but does not instantiate the class.
670         @author skeeter
671         @discussion This will include the API class once and guarantee that it is loaded only once.  Similar to CreateObject, but does not instantiate the class.
672         @syntax include_class('setup');
673         @example include_class('setup');
674         @param $included_class API class to load
675        */
676        function include_class($included_class)
677        {
678                if (!isset($GLOBALS['phpgw_info']['flags']['included_classes'][$included_class]) ||
679                        !$GLOBALS['phpgw_info']['flags']['included_classes'][$included_class])
680                {
681                        $GLOBALS['phpgw_info']['flags']['included_classes'][$included_class] = True;   
682                        include(PHPGW_SERVER_ROOT.'/phpgwapi/inc/class.'.$included_class.'.inc.php');
683                }
684        }
685
686        /*!
687         @function personalize_include_path
688         @abstract return path to include a "ile.php"
689         @author Serpro
690         @author Antonio Carlos da SIlva
691         @discussion This function is used to generate a path with $app and $prefix paramameters.
692         @example include(personalize_include_path('phpgwapi','login');
693         @example Will generate : /var/www/expresso/phpgwapi/templates/default/login_default.php
694         @example if "default" is the 'login_template_set' .
695         @param $app : name of application
696         @param $prefix : value to affix in login_template_set
697         */
698        function personalize_include_path($app,$prefix)
699        {
700                $file_include = PHPGW_SERVER_ROOT . '/' . $app . '/templates/' . $GLOBALS['phpgw_info']['login_template_set'] . '/' . $prefix . '_' . $GLOBALS['phpgw_info']['login_template_set'] . '.php';
701                if(!$file_include || !file_exists($file_include))
702                {
703                        $file_include = PHPGW_SERVER_ROOT . '/' . $app . '/templates/default/' . $prefix .'_default.php';
704                }
705        return $file_include;
706        }
707
708        /*!
709         @function nearest_to_me
710         @abstract return host nearest to client
711         @Include by Serpro ( Antonio Carlos da Silva).
712         */
713        function nearest_to_me()
714        {
715                $proxies=explode(',',$_SERVER['HTTP_X_FORWARDED_HOST']);
716                return isset($_SERVER['HTTP_X_FORWARDED_HOST']) ? $proxies[0] : $_SERVER['HTTP_HOST'];
717        }
718
719        /*!
720         @function session_convert
721         @abstract cipher/decipher session id.
722         @Include by Serpro ( Antonio Carlos da Silva).
723         @discussion This function cipher/decipher session id to captcha.
724         */
725        function session_convert($str,$ky='')
726        {
727            if($ky=='') return $str;
728            $ky=str_replace(chr(32),'',$ky);
729            if(strlen($ky)<8) return '';
730            $kl=strlen($ky)<32?strlen($ky):32;
731            $k=array();
732            for($i=0;$i<$kl;++$i)
733                {
734                    $k[$i]=ord($ky{$i})&0x1F;
735                }
736            $j=0;
737            for($i=0;$i<strlen($str);++$i)
738                {
739                    $e=ord($str{$i});
740                    $str{$i}=$e&0xE0?chr($e^$k[$j]):chr($e);
741                    ++$j;$j=$j==$kl?0:$j;
742                }
743            return $str;
744        }
745
746        /*!
747         @function CreateObject
748         @abstract Load a class and include the class file if not done so already.
749         @author mdean
750         @author milosch
751         @author (thanks to jengo and ralf)
752         @discussion This function is used to create an instance of a class, and if the class file has not been included it will do so.
753         @syntax CreateObject('app.class', 'constructor_params');
754         @example $phpgw->acl = CreateObject('phpgwapi.acl');
755         @param $classname name of class
756         @param $p1-$p16 class parameters (all optional)
757        */
758        function CreateObject($class,
759                $p1='_UNDEF_',$p2='_UNDEF_',$p3='_UNDEF_',$p4='_UNDEF_',
760                $p5='_UNDEF_',$p6='_UNDEF_',$p7='_UNDEF_',$p8='_UNDEF_',
761                $p9='_UNDEF_',$p10='_UNDEF_',$p11='_UNDEF_',$p12='_UNDEF_',
762                $p13='_UNDEF_',$p14='_UNDEF_',$p15='_UNDEF_',$p16='_UNDEF_')
763        {
764                global $phpgw_info, $phpgw;
765
766                /*
767                if(is_object(@$GLOBALS['phpgw']->log) && $class != 'phpgwapi.error' && $class != 'phpgwapi.errorlog')
768                {
769                        $GLOBALS['phpgw']->log->write(array('text'=>'D-Debug, dbg: %1','p1'=>'This class was run: '.$class,'file'=>__FILE__,'line'=>__LINE__));
770                }
771                */
772
773                /* error_reporting(0); */
774                list($appname,$classname) = explode('.', $class);
775                $filename = PHPGW_INCLUDE_ROOT.'/'.$appname.'/inc/class.'.$classname.'.inc.php';
776                $included_files = get_included_files();
777
778                if(!isset($included_files[$filename]))
779                {
780                        if(@file_exists($filename))
781                        {
782                                include_once($filename);
783                                $is_included = True;
784                        }
785                        else
786                        {
787                                $is_included = False;
788                        }
789                }
790                else
791                {
792                        $is_included = True;
793                }
794
795                if($is_included)
796                {
797                        if($p1 == '_UNDEF_' && $p1 != 1)
798                        {
799                                $obj = new $classname;
800                        }
801                        else
802                        {
803                                $input = array($p1,$p2,$p3,$p4,$p5,$p6,$p7,$p8,$p9,$p10,$p11,$p12,$p13,$p14,$p15,$p16);
804                                $i = 1;
805                                $code = '$obj = new ' . $classname . '(';
806                                foreach($input as $test)
807                                {
808                                        if(($test == '_UNDEF_' && $test != 1 ) || $i == 17)
809                                        {
810                                                break;
811                                        }
812                                        else
813                                        {
814                                                $code .= '$p' . $i . ',';
815                                        }
816                                        ++$i;
817                                }
818                                $code = substr($code,0,-1) . ');';
819                                eval($code);
820                        }
821                        /* error_reporting(E_ERROR | E_WARNING | E_PARSE); */
822                        return $obj;
823                }
824        }
825
826        /*!
827         @function ExecMethod
828         @abstract Execute a function, and load a class and include the class file if not done so already.
829         @author seek3r
830         @discussion This function is used to create an instance of a class, and if the class file has not been included it will do so.
831         @syntax ExecObject('app.class', 'constructor_params');
832         @param $method to execute
833         @param $functionparams function param should be an array
834         @param $loglevel developers choice of logging level
835         @param $classparams params to be sent to the contructor
836         @example ExecObject('phpgwapi.acl.read');
837        */
838        function ExecMethod($method, $functionparams = '_UNDEF_', $loglevel = 3, $classparams = '_UNDEF_')
839        {
840                /* Need to make sure this is working against a single dimensional object */
841                $partscount = count(explode('.',$method)) - 1;
842                if ($partscount == 2)
843                {
844                        list($appname,$classname,$functionname) = explode(".", $method);
845                        if (!is_object($GLOBALS[$classname]))
846                        {
847                                if ($classparams != '_UNDEF_' && ($classparams || $classparams != 'True'))
848                                {
849                                        $GLOBALS[$classname] = CreateObject($appname.'.'.$classname, $classparams);
850                                }
851                                else
852                                {
853                                        $GLOBALS[$classname] = CreateObject($appname.'.'.$classname);
854                                }
855                        }
856
857                        if (!method_exists($GLOBALS[$classname],$functionname))
858                        {
859                                echo "<p><b>".function_backtrace()."</b>: no methode '$functionname' in class '$classname'</p>\n";
860                                return False;
861                        }
862                        if ((is_array($functionparams) || $functionparams != '_UNDEF_') && ($functionparams || $functionparams != 'True'))
863                        {
864                                return $GLOBALS[$classname]->$functionname($functionparams);
865                        }
866                        else
867                        {
868                                return $GLOBALS[$classname]->$functionname();
869                        }
870                }
871                /* if the $method includes a parent class (multi-dimensional) then we have to work from it */
872                elseif ($partscount >= 3)
873                {
874                        $GLOBALS['methodparts'] = explode(".", $method);
875                        $classpartnum = $partscount - 1;
876                        $appname = $GLOBALS['methodparts'][0];
877                        $classname = $GLOBALS['methodparts'][$classpartnum];
878                        $functionname = $GLOBALS['methodparts'][$partscount];
879                        /* Now we clear these out of the array so that we can do a proper */
880                        /* loop and build the $parentobject */
881                        unset ($GLOBALS['methodparts'][0]);
882                        unset ($GLOBALS['methodparts'][$classpartnum]);
883                        unset ($GLOBALS['methodparts'][$partscount]);
884                        reset ($GLOBALS['methodparts']);
885                        $firstparent = 'True';
886//                      while (list ($key, $val) = each ($GLOBALS['methodparts']))
887                        foreach($GLOBALS['methodparts'] as $val)
888                        {
889                                if ($firstparent == 'True')
890                                {
891                                        $parentobject = '$GLOBALS["'.$val.'"]';
892                                        $firstparent = False;
893                                }
894                                else
895                                {
896                                        $parentobject .= '->'.$val;
897                                }
898                        }
899                        unset($GLOBALS['methodparts']);
900                        $code = '$isobject = is_object('.$parentobject.'->'.$classname.');';
901                        eval ($code);
902                        if (!$isobject)
903                        {
904                                if ($classparams != '_UNDEF_' && ($classparams || $classparams != 'True'))
905                                {
906                                        if (is_string($classparams))
907                                        {
908                                                eval($parentobject.'->'.$classname.' = CreateObject("'.$appname.'.'.$classname.'", "'.$classparams.'");');
909                                        }
910                                        else
911                                        {
912                                                eval($parentobject.'->'.$classname.' = CreateObject("'.$appname.'.'.$classname.'", '.$classparams.');');
913                                        }
914                                }
915                                else
916                                {
917                                        eval($parentobject.'->'.$classname.' = CreateObject("'.$appname.'.'.$classname.'");');
918                                }
919                        }
920
921                        if ($functionparams != '_UNDEF_' && ($functionparams || $functionparams != 'True'))
922                        {
923                                eval('$returnval = '.$parentobject.'->'.$classname.'->'.$functionname.'('.$functionparams.');');
924                                return $returnval;
925                        }
926                        else
927                        {
928                                eval('$returnval = '.$parentobject.'->'.$classname.'->'.$functionname.'();');
929                                return $returnval;
930                        }
931                }
932                else
933                {
934                        return 'error in parts';
935                }
936        }
937
938        /*!
939         @function copyobj
940         @abstract duplicates the result of copying an object under php3/4 even when using php5
941         @author milosch
942         @discussion This is critical when looping on db object output and updating or inserting to the database using a copy of the db object.  This was first added to GroupWhere
943         @syntax copyobj($source_object,$target_object);
944         @example copyobj($GLOBALS['phpgw']->db,$mydb);
945         @param $a   - Source Object
946         @param $b   - Target Object (copy)
947        */
948        function copyobj($a,&$b)
949        {
950                if(floor(phpversion()) > 4)
951                {
952                        $b = clone($a);
953                }
954                else
955                {
956                        $b = $a;
957                }
958                return;
959        }
960
961        /*!
962         @function get_account_id
963         @abstract Return a properly formatted account_id.
964         @author skeeter
965         @discussion This function will return a properly formatted account_id. This can take either a name or an account_id as paramters. If a name is provided it will return the associated id.
966         @syntax get_account_id($accountid);
967         @example $account_id = get_account_id($accountid);
968         @param $account_id either a name or an id
969         @param $default_id either a name or an id
970        */
971        function get_account_id($account_id = '',$default_id = '')
972        {
973                if (gettype($account_id) == 'integer')
974                {
975                        return $account_id;
976                }
977                elseif ($account_id == '')
978                {
979                        if ($default_id == '')
980                        {
981                                return (isset($GLOBALS['phpgw_info']['user']['account_id'])?$GLOBALS['phpgw_info']['user']['account_id']:0);
982                        }
983                        elseif (is_string($default_id))
984                        {
985                                return $GLOBALS['phpgw']->accounts->name2id($default_id);
986                        }
987                        return (int)$default_id;
988                }
989                elseif (is_string($account_id))
990                {
991                        if($GLOBALS['phpgw']->accounts->exists((int)$account_id) == True)
992                        {
993                                return (int)$account_id;
994                        }
995                        else
996                        {
997                                return $GLOBALS['phpgw']->accounts->name2id($account_id);
998                        }
999                }
1000        }
1001
1002        /*!
1003         @function filesystem_separator
1004         @abstract sets the file system seperator depending on OS
1005         @result file system separator
1006        */
1007        function filesystem_separator()
1008        {
1009                if(PHP_OS == 'Windows' || PHP_OS == 'OS/2' || PHP_OS == 'WINNT')
1010                {
1011                        return '\\';
1012                }
1013                else
1014                {
1015                        return '/';
1016                }
1017        }
1018
1019        function _debug_array($array,$print=True)
1020        {
1021                $four = False;
1022                if(@floor(phpversion()) > 3)
1023                {
1024                        $four = True;
1025                }
1026                if($four)
1027                {
1028                        if(!$print)
1029                        {
1030                                ob_start();
1031                        }
1032                        echo '<pre>';
1033                        print_r($array);
1034                        echo '</pre>';
1035                        if(!$print)
1036                        {
1037                                $v = ob_get_contents();
1038                                ob_end_clean();
1039                                return $v;
1040                        }
1041                }
1042                else
1043                {
1044                        return print_r($array,False,$print);
1045                }
1046        }
1047
1048        /*
1049        @function alessthanb
1050        @abstract phpgw version checking, is param 1 < param 2 in phpgw versionspeak?
1051        @param  $a      phpgw version number to check if less than $b
1052        @param  $b      phpgw version number to check $a against
1053        #return True if $a < $b
1054        */
1055        function alessthanb($a,$b,$DEBUG=False)
1056        {
1057                $num = array('1st','2nd','3rd','4th');
1058
1059                if ($DEBUG)
1060                {
1061                        echo'<br>Input values: ' . 'A="'.$a.'", B="'.$b.'"';
1062                }
1063                $newa = str_replace('-','',str_replace('pre','.',$a));
1064                $newb = str_replace('-','',str_replace('pre','.',$b));
1065                $testa = explode('.',$newa);
1066                if(@$testa[1] == '')
1067                {
1068                        $testa[1] = 0;
1069                }
1070                if(@$testa[3] == '')
1071                {
1072                        $testa[3] = 0;
1073                }
1074                $testb = explode('.',$newb);
1075                if(@$testb[1] == '')
1076                {
1077                        $testb[1] = 0;
1078                }
1079                if(@$testb[3] == '')
1080                {
1081                        $testb[3] = 0;
1082                }
1083                $less = 0;
1084
1085                for ($i=0;$i<count($testa);++$i)
1086                {
1087                        if ($DEBUG) { echo'<br>Checking if '. (int)$testa[$i] . ' is less than ' . (int)$testb[$i] . ' ...'; }
1088                        if ((int)$testa[$i] < (int)$testb[$i])
1089                        {
1090                                if ($DEBUG) { echo ' yes.'; }
1091                                ++$less;
1092                                if ($i<3)
1093                                {
1094                                        /* Ensure that this is definitely smaller */
1095                                        if ($DEBUG) { echo"  This is the $num[$i] octet, so A is definitely less than B."; }
1096                                        $less = 5;
1097                                        break;
1098                                }
1099                        }
1100                        elseif((int)$testa[$i] > (int)$testb[$i])
1101                        {
1102                                if ($DEBUG) { echo ' no.'; }
1103                                $less--;
1104                                if ($i<2)
1105                                {
1106                                        /* Ensure that this is definitely greater */
1107                                        if ($DEBUG) { echo"  This is the $num[$i] octet, so A is definitely greater than B."; }
1108                                        $less = -5;
1109                                        break;
1110                                }
1111                        }
1112                        else
1113                        {
1114                                if ($DEBUG) { echo ' no, they are equal.'; }
1115                                $less = 0;
1116                        }
1117                }
1118                if ($DEBUG) { echo '<br>Check value is: "'.$less.'"'; }
1119                if ($less>0)
1120                {
1121                        if ($DEBUG) { echo '<br>A is less than B'; }
1122                        return True;
1123                }
1124                elseif($less<0)
1125                {
1126                        if ($DEBUG) { echo '<br>A is greater than B'; }
1127                        return False;
1128                }
1129                else
1130                {
1131                        if ($DEBUG) { echo '<br>A is equal to B'; }
1132                        return False;
1133                }
1134        }
1135
1136        /*!
1137        @function amorethanb
1138        @abstract phpgw version checking, is param 1 > param 2 in phpgw versionspeak?
1139        @param  $a      phpgw version number to check if more than $b
1140        @param  $b      phpgw version number to check $a against
1141        #return True if $a < $b
1142        */
1143        function amorethanb($a,$b,$DEBUG=False)
1144        {
1145                $num = array('1st','2nd','3rd','4th');
1146
1147                if ($DEBUG)
1148                {
1149                        echo'<br>Input values: ' . 'A="'.$a.'", B="'.$b.'"';
1150                }
1151                $newa = str_replace('-','',str_replace('pre','.',$a));
1152                $newb = str_replace('-','',str_replace('pre','.',$b));
1153                $testa = explode('.',$newa);
1154                if($testa[3] == '')
1155                {
1156                        $testa[3] = 0;
1157                }
1158                $testb = explode('.',$newb);
1159                if($testb[3] == '')
1160                {
1161                        $testb[3] = 0;
1162                }
1163                $less = 0;
1164
1165                for ($i=0;$i<count($testa);++$i)
1166                {
1167                        if ($DEBUG) { echo'<br>Checking if '. (int)$testa[$i] . ' is more than ' . (int)$testb[$i] . ' ...'; }
1168                        if ((int)$testa[$i] > (int)$testb[$i])
1169                        {
1170                                if ($DEBUG) { echo ' yes.'; }
1171                                ++$less;
1172                                if ($i<3)
1173                                {
1174                                        /* Ensure that this is definitely greater */
1175                                        if ($DEBUG) { echo"  This is the $num[$i] octet, so A is definitely greater than B."; }
1176                                        $less = 5;
1177                                        break;
1178                                }
1179                        }
1180                        elseif((int)$testa[$i] < (int)$testb[$i])
1181                        {
1182                                if ($DEBUG) { echo ' no.'; }
1183                                $less--;
1184                                if ($i<2)
1185                                {
1186                                        /* Ensure that this is definitely smaller */
1187                                        if ($DEBUG) { echo"  This is the $num[$i] octet, so A is definitely less than B."; }
1188                                        $less = -5;
1189                                        break;
1190                                }
1191                        }
1192                        else
1193                        {
1194                                if ($DEBUG) { echo ' no, they are equal.'; }
1195                                $less = 0;
1196                        }
1197                }
1198                if ($DEBUG) { echo '<br>Check value is: "'.$less.'"'; }
1199                if ($less>0)
1200                {
1201                        if ($DEBUG) { echo '<br>A is greater than B'; }
1202                        return True;
1203                }
1204                elseif($less<0)
1205                {
1206                        if ($DEBUG) { echo '<br>A is less than B'; }
1207                        return False;
1208                }
1209                else
1210                {
1211                        if ($DEBUG) { echo '<br>A is equal to B'; }
1212                        return False;
1213                }
1214        }
1215       
1216        /*!
1217         @function prepend_tables_prefix
1218         @abstract prepend a prefix to an array of table names
1219         @author Adam Hull (aka fixe) - No copyright claim
1220         @param $prefix the string to be prepended
1221         @param $tables and array of tables to have the prefix prepended to
1222         @return array of table names with the prefix prepended
1223        */
1224        function prepend_tables_prefix($prefix,$tables)
1225        {
1226                foreach($tables as $key => $value)
1227                {
1228                        $tables[$key] = $prefix.$value;
1229                }
1230                return $tables;
1231        }
1232
1233        /*!
1234         @function function_backtrace
1235         @abstract backtrace of the calling functions for php4.3+ else menuaction/scriptname
1236         @author ralfbecker
1237         @return function-names separated by slashes (beginning with the calling function not this one)
1238        */
1239        function function_backtrace($remove=0)
1240        {
1241                if (function_exists('debug_backtrace'))
1242                {
1243                        $backtrace = debug_backtrace();
1244                        //echo "<pre>".print_r($backtrace,True)."</pre>\n";
1245                        foreach($backtrace as $level)
1246                        {
1247                                if ($remove-- < 0)
1248                                {
1249                                        $ret[] = (isset($level['class'])?$level['class'].'::':'').$level['function'];
1250                                }
1251                        }
1252                        return implode(' / ',$ret);
1253                }
1254                return $_GET['menuaction'] ? $_GET['menuaction'] : str_replace(PHPGW_SERVER_ROOT,'',$_SERVER['SCRIPT_FILENAME']);
1255        }
1256
1257        function _check_script_tag(&$var,$name='')
1258        {
1259                if (is_array($var))
1260                {
1261                        foreach($var as $key => $val)
1262                        {
1263                                if (is_array($val))
1264                                {
1265                                        _check_script_tag($var[$key],$name.'['.$key.']');
1266                                }
1267                                else
1268                                {
1269                                        if (preg_match('/<\/?[^>]*(iframe|script|onabort|onblur|onchange|onclick|ondblclick|onerror|onfocus|onkeydown|onkeypress|onkeyup|onload|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|onreset|onselect|onsubmit|onunload|javascript)+[^>]*>/i',$val))
1270                                        {
1271                                                //echo "<p>*** _check_script_tag($name): unset($name [$key]) ***</p>\n";
1272                                                unset($var[$key]);
1273                                        }
1274                                }
1275                        }
1276                        // in case some stupid old code expects the array-pointer to be at the start of the array
1277                        reset($var);
1278                }
1279        }
1280               
1281        foreach(array('_GET','_POST','_REQUEST','HTTP_GET_VARS','HTTP_POST_VARS','HTTP_REQUEST_VARS') as $where)
1282        {
1283                $pregs = array(
1284                        'order' => '/^[a-zA-Z0-9_]*$/',
1285                        'sort'  => '/^(ASC|DESC|asc|desc|0|1|2|3|4|5|6|7){0,1}$/',
1286                );
1287                foreach(array('order','sort') as $name)
1288                {
1289                        if (isset($GLOBALS[$where][$name]) && !is_array($GLOBALS[$where][$name]) && !preg_match($pregs[$name],$GLOBALS[$where][$name]))
1290                        {
1291                                $GLOBALS[$where][$name] = '';
1292                        }
1293                }
1294                if (is_array($GLOBALS[$where]))
1295                {
1296                        _check_script_tag($GLOBALS[$where],$where);
1297                }
1298        }
1299       
1300        if(floor(phpversion()) <= 4)
1301        {
1302                /**
1303                 * clone function for php4, use as $new_obj = clone($old_obj);
1304                 */
1305                eval('
1306                function clone($obj)
1307                {
1308                        return $obj;
1309                }
1310                ');
1311        }
1312?>
Note: See TracBrowser for help on using the repository browser.