[ Index ]
 

Code source de eGroupWare 1.2.106-2

Accédez au Source d'autres logiciels libresSoutenez Angelica Josefina !

title

Body

[fermer]

/phpgwapi/inc/ -> common_functions.inc.php (source)

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


Généré le : Sun Feb 25 17:20:01 2007 par Balluche grâce à PHPXref 0.7