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

Revision 2, 33.2 KB checked in by niltonneto, 17 years ago (diff)

Removida todas as tags usadas pelo CVS ($Id, $Source).
Primeira versão no CVS externo.

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