source: branches/2.2/phpgwapi/inc/common_functions.inc.php @ 3437

Revision 3437, 35.2 KB checked in by rafaelraymundo, 14 years ago (diff)

Ticket #990 - Vulnerabilidades no Anti robo Captcha do Login.

  • 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 (eregi("^[0-9]{1,3}(\.[0-9]{1,3}){3}$",$string))
342                                {
343                                        $octets = 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 (eregi("^([[:alnum:]_%+=.-]+)@([[:alnum:]_.-]+)\.([a-z]{2,3}|[0-9]{1,3})$",$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 session_convert
710         @abstract cipher/decipher session id.
711         @Include by Serpro ( Antonio Carlos da Silva).
712         @discussion This function cipher/decipher session id to captcha.
713         */
714        function session_convert($str,$ky='')
715        {
716            if($ky=='') return $str;
717            $ky=str_replace(chr(32),'',$ky);
718            if(strlen($ky)<8) return '';
719            $kl=strlen($ky)<32?strlen($ky):32;
720            $k=array();
721            for($i=0;$i<$kl;$i++)
722                {
723                    $k[$i]=ord($ky{$i})&0x1F;
724                }
725            $j=0;
726            for($i=0;$i<strlen($str);$i++)
727                {
728                    $e=ord($str{$i});
729                    $str{$i}=$e&0xE0?chr($e^$k[$j]):chr($e);
730                    $j++;$j=$j==$kl?0:$j;
731                }
732            return $str;
733        }
734
735        /*!
736         @function CreateObject
737         @abstract Load a class and include the class file if not done so already.
738         @author mdean
739         @author milosch
740         @author (thanks to jengo and ralf)
741         @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.
742         @syntax CreateObject('app.class', 'constructor_params');
743         @example $phpgw->acl = CreateObject('phpgwapi.acl');
744         @param $classname name of class
745         @param $p1-$p16 class parameters (all optional)
746        */
747        function CreateObject($class,
748                $p1='_UNDEF_',$p2='_UNDEF_',$p3='_UNDEF_',$p4='_UNDEF_',
749                $p5='_UNDEF_',$p6='_UNDEF_',$p7='_UNDEF_',$p8='_UNDEF_',
750                $p9='_UNDEF_',$p10='_UNDEF_',$p11='_UNDEF_',$p12='_UNDEF_',
751                $p13='_UNDEF_',$p14='_UNDEF_',$p15='_UNDEF_',$p16='_UNDEF_')
752        {
753                global $phpgw_info, $phpgw;
754
755                /*
756                if(is_object(@$GLOBALS['phpgw']->log) && $class != 'phpgwapi.error' && $class != 'phpgwapi.errorlog')
757                {
758                        $GLOBALS['phpgw']->log->write(array('text'=>'D-Debug, dbg: %1','p1'=>'This class was run: '.$class,'file'=>__FILE__,'line'=>__LINE__));
759                }
760                */
761
762                /* error_reporting(0); */
763                list($appname,$classname) = explode('.', $class);
764                $filename = PHPGW_INCLUDE_ROOT.'/'.$appname.'/inc/class.'.$classname.'.inc.php';
765                $included_files = get_included_files();
766
767                if(!isset($included_files[$filename]))
768                {
769                        if(@file_exists($filename))
770                        {
771                                include_once($filename);
772                                $is_included = True;
773                        }
774                        else
775                        {
776                                $is_included = False;
777                        }
778                }
779                else
780                {
781                        $is_included = True;
782                }
783
784                if($is_included)
785                {
786                        if($p1 == '_UNDEF_' && $p1 != 1)
787                        {
788                                $obj = new $classname;
789                        }
790                        else
791                        {
792                                $input = array($p1,$p2,$p3,$p4,$p5,$p6,$p7,$p8,$p9,$p10,$p11,$p12,$p13,$p14,$p15,$p16);
793                                $i = 1;
794                                $code = '$obj = new ' . $classname . '(';
795                                foreach($input as $test)
796                                {
797                                        if(($test == '_UNDEF_' && $test != 1 ) || $i == 17)
798                                        {
799                                                break;
800                                        }
801                                        else
802                                        {
803                                                $code .= '$p' . $i . ',';
804                                        }
805                                        $i++;
806                                }
807                                $code = substr($code,0,-1) . ');';
808                                eval($code);
809                        }
810                        /* error_reporting(E_ERROR | E_WARNING | E_PARSE); */
811                        return $obj;
812                }
813        }
814
815        /*!
816         @function ExecMethod
817         @abstract Execute a function, and load a class and include the class file if not done so already.
818         @author seek3r
819         @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.
820         @syntax ExecObject('app.class', 'constructor_params');
821         @param $method to execute
822         @param $functionparams function param should be an array
823         @param $loglevel developers choice of logging level
824         @param $classparams params to be sent to the contructor
825         @example ExecObject('phpgwapi.acl.read');
826        */
827        function ExecMethod($method, $functionparams = '_UNDEF_', $loglevel = 3, $classparams = '_UNDEF_')
828        {
829                /* Need to make sure this is working against a single dimensional object */
830                $partscount = count(explode('.',$method)) - 1;
831                if ($partscount == 2)
832                {
833                        list($appname,$classname,$functionname) = explode(".", $method);
834                        if (!is_object($GLOBALS[$classname]))
835                        {
836                                if ($classparams != '_UNDEF_' && ($classparams || $classparams != 'True'))
837                                {
838                                        $GLOBALS[$classname] = CreateObject($appname.'.'.$classname, $classparams);
839                                }
840                                else
841                                {
842                                        $GLOBALS[$classname] = CreateObject($appname.'.'.$classname);
843                                }
844                        }
845
846                        if (!method_exists($GLOBALS[$classname],$functionname))
847                        {
848                                echo "<p><b>".function_backtrace()."</b>: no methode '$functionname' in class '$classname'</p>\n";
849                                return False;
850                        }
851                        if ((is_array($functionparams) || $functionparams != '_UNDEF_') && ($functionparams || $functionparams != 'True'))
852                        {
853                                return $GLOBALS[$classname]->$functionname($functionparams);
854                        }
855                        else
856                        {
857                                return $GLOBALS[$classname]->$functionname();
858                        }
859                }
860                /* if the $method includes a parent class (multi-dimensional) then we have to work from it */
861                elseif ($partscount >= 3)
862                {
863                        $GLOBALS['methodparts'] = explode(".", $method);
864                        $classpartnum = $partscount - 1;
865                        $appname = $GLOBALS['methodparts'][0];
866                        $classname = $GLOBALS['methodparts'][$classpartnum];
867                        $functionname = $GLOBALS['methodparts'][$partscount];
868                        /* Now we clear these out of the array so that we can do a proper */
869                        /* loop and build the $parentobject */
870                        unset ($GLOBALS['methodparts'][0]);
871                        unset ($GLOBALS['methodparts'][$classpartnum]);
872                        unset ($GLOBALS['methodparts'][$partscount]);
873                        reset ($GLOBALS['methodparts']);
874                        $firstparent = 'True';
875//                      while (list ($key, $val) = each ($GLOBALS['methodparts']))
876                        foreach($GLOBALS['methodparts'] as $val)
877                        {
878                                if ($firstparent == 'True')
879                                {
880                                        $parentobject = '$GLOBALS["'.$val.'"]';
881                                        $firstparent = False;
882                                }
883                                else
884                                {
885                                        $parentobject .= '->'.$val;
886                                }
887                        }
888                        unset($GLOBALS['methodparts']);
889                        $code = '$isobject = is_object('.$parentobject.'->'.$classname.');';
890                        eval ($code);
891                        if (!$isobject)
892                        {
893                                if ($classparams != '_UNDEF_' && ($classparams || $classparams != 'True'))
894                                {
895                                        if (is_string($classparams))
896                                        {
897                                                eval($parentobject.'->'.$classname.' = CreateObject("'.$appname.'.'.$classname.'", "'.$classparams.'");');
898                                        }
899                                        else
900                                        {
901                                                eval($parentobject.'->'.$classname.' = CreateObject("'.$appname.'.'.$classname.'", '.$classparams.');');
902                                        }
903                                }
904                                else
905                                {
906                                        eval($parentobject.'->'.$classname.' = CreateObject("'.$appname.'.'.$classname.'");');
907                                }
908                        }
909
910                        if ($functionparams != '_UNDEF_' && ($functionparams || $functionparams != 'True'))
911                        {
912                                eval('$returnval = '.$parentobject.'->'.$classname.'->'.$functionname.'('.$functionparams.');');
913                                return $returnval;
914                        }
915                        else
916                        {
917                                eval('$returnval = '.$parentobject.'->'.$classname.'->'.$functionname.'();');
918                                return $returnval;
919                        }
920                }
921                else
922                {
923                        return 'error in parts';
924                }
925        }
926
927        /*!
928         @function copyobj
929         @abstract duplicates the result of copying an object under php3/4 even when using php5
930         @author milosch
931         @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
932         @syntax copyobj($source_object,$target_object);
933         @example copyobj($GLOBALS['phpgw']->db,$mydb);
934         @param $a   - Source Object
935         @param $b   - Target Object (copy)
936        */
937        function copyobj($a,&$b)
938        {
939                if(floor(phpversion()) > 4)
940                {
941                        $b = clone($a);
942                }
943                else
944                {
945                        $b = $a;
946                }
947                return;
948        }
949
950        /*!
951         @function get_account_id
952         @abstract Return a properly formatted account_id.
953         @author skeeter
954         @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.
955         @syntax get_account_id($accountid);
956         @example $account_id = get_account_id($accountid);
957         @param $account_id either a name or an id
958         @param $default_id either a name or an id
959        */
960        function get_account_id($account_id = '',$default_id = '')
961        {
962                if (gettype($account_id) == 'integer')
963                {
964                        return $account_id;
965                }
966                elseif ($account_id == '')
967                {
968                        if ($default_id == '')
969                        {
970                                return (isset($GLOBALS['phpgw_info']['user']['account_id'])?$GLOBALS['phpgw_info']['user']['account_id']:0);
971                        }
972                        elseif (is_string($default_id))
973                        {
974                                return $GLOBALS['phpgw']->accounts->name2id($default_id);
975                        }
976                        return (int)$default_id;
977                }
978                elseif (is_string($account_id))
979                {
980                        if($GLOBALS['phpgw']->accounts->exists((int)$account_id) == True)
981                        {
982                                return (int)$account_id;
983                        }
984                        else
985                        {
986                                return $GLOBALS['phpgw']->accounts->name2id($account_id);
987                        }
988                }
989        }
990
991        /*!
992         @function filesystem_separator
993         @abstract sets the file system seperator depending on OS
994         @result file system separator
995        */
996        function filesystem_separator()
997        {
998                if(PHP_OS == 'Windows' || PHP_OS == 'OS/2' || PHP_OS == 'WINNT')
999                {
1000                        return '\\';
1001                }
1002                else
1003                {
1004                        return '/';
1005                }
1006        }
1007
1008        function _debug_array($array,$print=True)
1009        {
1010                $four = False;
1011                if(@floor(phpversion()) > 3)
1012                {
1013                        $four = True;
1014                }
1015                if($four)
1016                {
1017                        if(!$print)
1018                        {
1019                                ob_start();
1020                        }
1021                        echo '<pre>';
1022                        print_r($array);
1023                        echo '</pre>';
1024                        if(!$print)
1025                        {
1026                                $v = ob_get_contents();
1027                                ob_end_clean();
1028                                return $v;
1029                        }
1030                }
1031                else
1032                {
1033                        return print_r($array,False,$print);
1034                }
1035        }
1036
1037        /*
1038        @function alessthanb
1039        @abstract phpgw version checking, is param 1 < param 2 in phpgw versionspeak?
1040        @param  $a      phpgw version number to check if less than $b
1041        @param  $b      phpgw version number to check $a against
1042        #return True if $a < $b
1043        */
1044        function alessthanb($a,$b,$DEBUG=False)
1045        {
1046                $num = array('1st','2nd','3rd','4th');
1047
1048                if ($DEBUG)
1049                {
1050                        echo'<br>Input values: ' . 'A="'.$a.'", B="'.$b.'"';
1051                }
1052                $newa = str_replace('-','',str_replace('pre','.',$a));
1053                $newb = str_replace('-','',str_replace('pre','.',$b));
1054                $testa = explode('.',$newa);
1055                if(@$testa[1] == '')
1056                {
1057                        $testa[1] = 0;
1058                }
1059                if(@$testa[3] == '')
1060                {
1061                        $testa[3] = 0;
1062                }
1063                $testb = explode('.',$newb);
1064                if(@$testb[1] == '')
1065                {
1066                        $testb[1] = 0;
1067                }
1068                if(@$testb[3] == '')
1069                {
1070                        $testb[3] = 0;
1071                }
1072                $less = 0;
1073
1074                for ($i=0;$i<count($testa);$i++)
1075                {
1076                        if ($DEBUG) { echo'<br>Checking if '. (int)$testa[$i] . ' is less than ' . (int)$testb[$i] . ' ...'; }
1077                        if ((int)$testa[$i] < (int)$testb[$i])
1078                        {
1079                                if ($DEBUG) { echo ' yes.'; }
1080                                $less++;
1081                                if ($i<3)
1082                                {
1083                                        /* Ensure that this is definitely smaller */
1084                                        if ($DEBUG) { echo"  This is the $num[$i] octet, so A is definitely less than B."; }
1085                                        $less = 5;
1086                                        break;
1087                                }
1088                        }
1089                        elseif((int)$testa[$i] > (int)$testb[$i])
1090                        {
1091                                if ($DEBUG) { echo ' no.'; }
1092                                $less--;
1093                                if ($i<2)
1094                                {
1095                                        /* Ensure that this is definitely greater */
1096                                        if ($DEBUG) { echo"  This is the $num[$i] octet, so A is definitely greater than B."; }
1097                                        $less = -5;
1098                                        break;
1099                                }
1100                        }
1101                        else
1102                        {
1103                                if ($DEBUG) { echo ' no, they are equal.'; }
1104                                $less = 0;
1105                        }
1106                }
1107                if ($DEBUG) { echo '<br>Check value is: "'.$less.'"'; }
1108                if ($less>0)
1109                {
1110                        if ($DEBUG) { echo '<br>A is less than B'; }
1111                        return True;
1112                }
1113                elseif($less<0)
1114                {
1115                        if ($DEBUG) { echo '<br>A is greater than B'; }
1116                        return False;
1117                }
1118                else
1119                {
1120                        if ($DEBUG) { echo '<br>A is equal to B'; }
1121                        return False;
1122                }
1123        }
1124
1125        /*!
1126        @function amorethanb
1127        @abstract phpgw version checking, is param 1 > param 2 in phpgw versionspeak?
1128        @param  $a      phpgw version number to check if more than $b
1129        @param  $b      phpgw version number to check $a against
1130        #return True if $a < $b
1131        */
1132        function amorethanb($a,$b,$DEBUG=False)
1133        {
1134                $num = array('1st','2nd','3rd','4th');
1135
1136                if ($DEBUG)
1137                {
1138                        echo'<br>Input values: ' . 'A="'.$a.'", B="'.$b.'"';
1139                }
1140                $newa = str_replace('-','',str_replace('pre','.',$a));
1141                $newb = str_replace('-','',str_replace('pre','.',$b));
1142                $testa = explode('.',$newa);
1143                if($testa[3] == '')
1144                {
1145                        $testa[3] = 0;
1146                }
1147                $testb = explode('.',$newb);
1148                if($testb[3] == '')
1149                {
1150                        $testb[3] = 0;
1151                }
1152                $less = 0;
1153
1154                for ($i=0;$i<count($testa);$i++)
1155                {
1156                        if ($DEBUG) { echo'<br>Checking if '. (int)$testa[$i] . ' is more than ' . (int)$testb[$i] . ' ...'; }
1157                        if ((int)$testa[$i] > (int)$testb[$i])
1158                        {
1159                                if ($DEBUG) { echo ' yes.'; }
1160                                $less++;
1161                                if ($i<3)
1162                                {
1163                                        /* Ensure that this is definitely greater */
1164                                        if ($DEBUG) { echo"  This is the $num[$i] octet, so A is definitely greater than B."; }
1165                                        $less = 5;
1166                                        break;
1167                                }
1168                        }
1169                        elseif((int)$testa[$i] < (int)$testb[$i])
1170                        {
1171                                if ($DEBUG) { echo ' no.'; }
1172                                $less--;
1173                                if ($i<2)
1174                                {
1175                                        /* Ensure that this is definitely smaller */
1176                                        if ($DEBUG) { echo"  This is the $num[$i] octet, so A is definitely less than B."; }
1177                                        $less = -5;
1178                                        break;
1179                                }
1180                        }
1181                        else
1182                        {
1183                                if ($DEBUG) { echo ' no, they are equal.'; }
1184                                $less = 0;
1185                        }
1186                }
1187                if ($DEBUG) { echo '<br>Check value is: "'.$less.'"'; }
1188                if ($less>0)
1189                {
1190                        if ($DEBUG) { echo '<br>A is greater than B'; }
1191                        return True;
1192                }
1193                elseif($less<0)
1194                {
1195                        if ($DEBUG) { echo '<br>A is less than B'; }
1196                        return False;
1197                }
1198                else
1199                {
1200                        if ($DEBUG) { echo '<br>A is equal to B'; }
1201                        return False;
1202                }
1203        }
1204       
1205        /*!
1206         @function prepend_tables_prefix
1207         @abstract prepend a prefix to an array of table names
1208         @author Adam Hull (aka fixe) - No copyright claim
1209         @param $prefix the string to be prepended
1210         @param $tables and array of tables to have the prefix prepended to
1211         @return array of table names with the prefix prepended
1212        */
1213        function prepend_tables_prefix($prefix,$tables)
1214        {
1215                foreach($tables as $key => $value)
1216                {
1217                        $tables[$key] = $prefix.$value;
1218                }
1219                return $tables;
1220        }
1221
1222        /*!
1223         @function function_backtrace
1224         @abstract backtrace of the calling functions for php4.3+ else menuaction/scriptname
1225         @author ralfbecker
1226         @return function-names separated by slashes (beginning with the calling function not this one)
1227        */
1228        function function_backtrace($remove=0)
1229        {
1230                if (function_exists('debug_backtrace'))
1231                {
1232                        $backtrace = debug_backtrace();
1233                        //echo "<pre>".print_r($backtrace,True)."</pre>\n";
1234                        foreach($backtrace as $level)
1235                        {
1236                                if ($remove-- < 0)
1237                                {
1238                                        $ret[] = (isset($level['class'])?$level['class'].'::':'').$level['function'];
1239                                }
1240                        }
1241                        return implode(' / ',$ret);
1242                }
1243                return $_GET['menuaction'] ? $_GET['menuaction'] : str_replace(PHPGW_SERVER_ROOT,'',$_SERVER['SCRIPT_FILENAME']);
1244        }
1245
1246        function _check_script_tag(&$var,$name='')
1247        {
1248                if (is_array($var))
1249                {
1250                        foreach($var as $key => $val)
1251                        {
1252                                if (is_array($val))
1253                                {
1254                                        _check_script_tag($var[$key],$name.'['.$key.']');
1255                                }
1256                                else
1257                                {
1258                                        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))
1259                                        {
1260                                                //echo "<p>*** _check_script_tag($name): unset($name [$key]) ***</p>\n";
1261                                                unset($var[$key]);
1262                                        }
1263                                }
1264                        }
1265                        // in case some stupid old code expects the array-pointer to be at the start of the array
1266                        reset($var);
1267                }
1268        }
1269               
1270        foreach(array('_GET','_POST','_REQUEST','HTTP_GET_VARS','HTTP_POST_VARS','HTTP_REQUEST_VARS') as $where)
1271        {
1272                $pregs = array(
1273                        'order' => '/^[a-zA-Z0-9_]*$/',
1274                        'sort'  => '/^(ASC|DESC|asc|desc|0|1|2|3|4|5|6|7){0,1}$/',
1275                );
1276                foreach(array('order','sort') as $name)
1277                {
1278                        if (isset($GLOBALS[$where][$name]) && !is_array($GLOBALS[$where][$name]) && !preg_match($pregs[$name],$GLOBALS[$where][$name]))
1279                        {
1280                                $GLOBALS[$where][$name] = '';
1281                        }
1282                }
1283                if (is_array($GLOBALS[$where]))
1284                {
1285                        _check_script_tag($GLOBALS[$where],$where);
1286                }
1287        }
1288       
1289        if(floor(phpversion()) <= 4)
1290        {
1291                /**
1292                 * clone function for php4, use as $new_obj = clone($old_obj);
1293                 */
1294                eval('
1295                function clone($obj)
1296                {
1297                        return $obj;
1298                }
1299                ');
1300        }
1301?>
Note: See TracBrowser for help on using the repository browser.