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

Revision 1681, 34.3 KB checked in by rafaelraymundo, 14 years ago (diff)

Ticket #770 - função em common_functions,inc.php determina include p/templates.

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