[ Index ]
 

Code source de CMS made simple 1.0.5

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

title

Body

[fermer]

/lib/ -> misc.functions.php (source)

   1  <?php
   2  #CMS - CMS Made Simple
   3  #(c)2004 by Ted Kulp (wishy@users.sf.net)
   4  #This project's homepage is: http://cmsmadesimple.sf.net
   5  #
   6  #This program is free software; you can redistribute it and/or modify
   7  #it under the terms of the GNU General Public License as published by
   8  #the Free Software Foundation; either version 2 of the License, or
   9  #(at your option) any later version.
  10  #
  11  #This program is distributed in the hope that it will be useful,
  12  #but WITHOUT ANY WARRANTY; without even the implied warranty of
  13  #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14  #GNU General Public License for more details.
  15  #You should have received a copy of the GNU General Public License
  16  #along with this program; if not, write to the Free Software
  17  #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  18  #
  19  #$Id: misc.functions.php 3832 2007-03-21 12:10:27Z dittmann $
  20  
  21  /**
  22   * Misc functions
  23   *
  24   * @package CMS
  25   */
  26  /**
  27   * Redirects to relative URL on the current site
  28   *
  29   * @author http://www.edoceo.com/
  30   * @since 0.1
  31   */
  32  function redirect($to, $noappend=false)
  33  {
  34      $_SERVER['PHP_SELF'] = null;
  35  
  36      global $gCms;
  37      if (isset($gCms))
  38          $config =& $gCms->GetConfig();
  39      else
  40          $config = array();
  41  
  42      $schema = $_SERVER['SERVER_PORT'] == '443' ? 'https' : 'http';
  43      $host = strlen($_SERVER['HTTP_HOST'])?$_SERVER['HTTP_HOST']:$_SERVER['SERVER_NAME'];
  44  
  45      $components = parse_url($to);
  46      if(count($components) > 0)
  47      {
  48          $to =  (isset($components['scheme']) && startswith($components['scheme'], 'http') ? $components['scheme'] : $schema) . '://';
  49          $to .= isset($components['host']) ? $components['host'] : $host;
  50          $to .= isset($components['port']) ? ':' . $components['port'] : '';
  51          if(isset($components['path']))
  52          {
  53              if(in_array(substr($components['path'],0,1),array('\\','/')))//Path is absolute, just append.
  54              {
  55                  $to .= $components['path'];
  56              }
  57              //Path is relative, append current directory first.
  58              else if (isset($_SERVER['PHP_SELF']) && !is_null($_SERVER['PHP_SELF'])) //Apache
  59              {
  60                  $to .= (strlen(dirname($_SERVER['PHP_SELF'])) > 1 ?  dirname($_SERVER['PHP_SELF']).'/' : '/') . $components['path'];
  61              }
  62              else if (isset($_SERVER['REQUEST_URI']) && !is_null($_SERVER['REQUEST_URI'])) //Lighttpd
  63              {
  64                  if (endswith($_SERVER['REQUEST_URI'], '/'))
  65                      $to .= (strlen($_SERVER['REQUEST_URI']) > 1 ? $_SERVER['REQUEST_URI'] : '/') . $components['path'];
  66                  else
  67                      $to .= (strlen(dirname($_SERVER['REQUEST_URI'])) > 1 ? dirname($_SERVER['REQUEST_URI']).'/' : '/') . $components['path'];
  68              }
  69          }
  70          $to .= isset($components['query']) ? '?' . $components['query'] : '';
  71          $to .= isset($components['fragment']) ? '#' . $components['fragment'] : '';
  72      }
  73      else
  74      {
  75          $to = $schema."://".$host."/".$to;
  76      }
  77  
  78      //If session trans-id is being used, and they is on yo website, add it.
  79      /*
  80      if (ini_get("session.use_trans_sid") != "0" && $noappend == false && strpos($to,$host) !== false)
  81      {
  82          if(strpos($to,'?') !== false)//If there are no arguments start a querystring
  83          {
  84              //$to = $to."?".session_name()."=".session_id();
  85          }
  86          else//There are arguments, print an arg seperator
  87          {
  88              //$to = $to.ini_get('arg_separator.input').session_name()."=".session_id();
  89          }
  90      }
  91      */
  92  
  93      if (headers_sent() && !(isset($config) && $config['debug'] == true))
  94      {
  95          // use javascript instead
  96          echo '<script type="text/javascript">
  97              <!--
  98                  location.replace("'.$to.'");
  99              // -->
 100              </script>
 101              <noscript>
 102                  <meta http-equiv="Refresh" content="0;URL='.$to.'">
 103              </noscript>';
 104          exit;
 105  
 106      }
 107      else
 108      {
 109          if (isset($config['debug']) && $config['debug'] == true)
 110          {
 111              echo "Debug is on.  Redirecting disabled...  Please click this link to continue.<br />";
 112              echo "<a href=\"".$to."\">".$to."</a><br />";
 113              echo '<div id="DebugFooter">';
 114              global $sql_queries;
 115              if (FALSE == empty($sql_queries))
 116                { 
 117                  echo "<div>".$sql_queries."</div>\n";
 118                }
 119              foreach ($gCms->errors as $error)
 120              {   
 121                  echo $error;
 122              }
 123              echo '</div> <!-- end DebugFooter -->';
 124              exit();
 125          }
 126          else
 127          {
 128              header("Location: $to");
 129              exit();
 130          }
 131      }
 132  }
 133  
 134  
 135  /**
 136   * Given a page ID or an alias, redirect to it
 137   */
 138  function redirect_to_alias($alias)
 139  {
 140      global $gCms;
 141      $manager =& $gCms->GetHierarchyManager();
 142      $node =& $manager->sureGetNodeByAlias($alias);
 143      $content =& $node->GetContent();
 144      if (isset($content))
 145      {
 146          if ($content->GetURL() != '')
 147          {
 148              redirect($content->GetURL());
 149          }
 150      }
 151  }
 152  
 153  /**
 154   * Shows the difference in seconds between two microtime() values
 155   *
 156   * @since 0.3
 157   */
 158  function microtime_diff($a, $b) {
 159      list($a_dec, $a_sec) = explode(" ", $a);
 160      list($b_dec, $b_sec) = explode(" ", $b);
 161      return $b_sec - $a_sec + $b_dec - $a_dec;
 162  }
 163  
 164  /**
 165   * Joins a path together using proper directory separators
 166   * Taken from: http://www.php.net/manual/en/ref.dir.php
 167   *
 168   * @since 0.14
 169   */
 170  function cms_join_path()
 171  {
 172       $num_args = func_num_args();
 173      $args = func_get_args();
 174      $path = $args[0];
 175  
 176      if( $num_args > 1 )
 177      {
 178          for ($i = 1; $i < $num_args; $i++)
 179          {
 180              $path .= DIRECTORY_SEPARATOR.$args[$i];
 181          }
 182      }
 183  
 184      return $path;
 185  }
 186  
 187  
 188  /**
 189   * Shows a very close approximation of an Apache generated 404 error.
 190   *
 191   * Shows a very close approximation of an Apache generated 404 error.
 192   * It also sends the actual header along as well, so that generic
 193   * browser error pages (like what IE does) will be displayed.
 194   *
 195   * @since 0.3
 196   */
 197  #function ErrorHandler404($errno, $errmsg, $filename, $linenum, $vars)
 198  function ErrorHandler404()
 199  {
 200      #if ($errno == E_USER_WARNING) {
 201          @ob_end_clean();
 202          header("HTTP/1.0 404 Not Found");
 203          header("Status: 404 Not Found");
 204          echo '<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
 205  <html><head>
 206  <title>404 Not Found</title>
 207  </head><body>
 208  <h1>Not Found</h1>
 209  <p>The requested URL was not found on this server.</p>
 210  </body></html>';
 211          exit();
 212      #}
 213  }
 214  
 215  /**
 216   * Simple template parser
 217   *
 218   * @since 0.6.1
 219   */
 220  
 221  	function parse_template ($template, $tpl_array, $warn=0)
 222      {
 223          while ( list ($key,$val) = each ($tpl_array) )
 224          {
 225              if (!(empty($key)))
 226              {
 227                  if(gettype($val) != "string")
 228                  {
 229                      settype($val,"string");
 230                  }
 231                  $template = eregi_replace('\{' . $key . '\}',$val,$template);
 232              }
 233          }
 234  
 235          if(!$warn)
 236          {
 237              // Silently remove anything not already found
 238  
 239              $template = ereg_replace('\{[A-Z0-9_]+\}', "", $template);
 240          }
 241          else
 242          {
 243              // Warn about unresolved template variables
 244              if (ereg('\{[A-Z0-9_]+\}',$template))
 245              {
 246                  $unknown = split("\n",$template);
 247                  while (list ($Element,$Line) = each($unknown) )
 248                  {
 249                      $UnkVar = $Line;
 250                      if(!(empty($UnkVar)))
 251                      {
 252                          $this->show_unknowns($UnkVar);
 253                      }
 254                  }
 255              }
 256          }
 257          return $template;
 258  
 259      }    // end parse_template();
 260  
 261  function cms_htmlentities($string, $param=ENT_QUOTES, $charset="UTF-8")
 262  {
 263      $result = "";
 264      #$result = htmlentities($string, $param, $charset);
 265      $result = my_htmlentities($string);
 266      return $result;
 267  }
 268  
 269  /**
 270   * Figures out the page name from the uri string.  Has to use different logic
 271   * based on the type of httpd server.
 272   */
 273  function cms_calculate_url()
 274  {
 275      $result = '';
 276      
 277      global $gCms;
 278      $config =& $gCms->GetConfig();
 279  
 280      //Apache
 281      /*
 282      if (isset($_SERVER["PHP_SELF"]) && !endswith($_SERVER['PHP_SELF'], 'index.php'))
 283      {
 284          $matches = array();
 285  
 286          //Seems like PHP_SELF has whatever is after index.php in certain situations
 287          if (strpos($_SERVER['PHP_SELF'], 'index.php') !== FALSE) {
 288              if (preg_match('/.*index\.php\/(.*?)$/', $_SERVER['PHP_SELF'], $matches))
 289              {
 290                  $result = $matches[1];
 291              }
 292          }
 293          else
 294          {
 295              $result = $_SERVER['PHP_SELF'];
 296          }
 297      }
 298      */
 299      //lighttpd
 300      #else if (isset($_SERVER["REQUEST_URI"]) && !endswith($_SERVER['REQUEST_URI'], 'index.php'))
 301  
 302      //apache and lighttpd
 303      if (isset($_SERVER["REQUEST_URI"]) && !endswith($_SERVER['REQUEST_URI'], 'index.php'))
 304      {
 305          $matches = array();
 306          if (preg_match('/.*index\.php\/(.*?)$/', $_SERVER['REQUEST_URI'], $matches))
 307          {
 308              $result = $matches[1];
 309          }
 310      }
 311      
 312      //trim off the extension, if there is one set
 313      if ($config['page_extension'] != '' && endswith($result, $config['page_extension']))
 314      {
 315          $result = substr($result, 0, strlen($result) - strlen($config['page_extension']));
 316      }
 317  
 318      return $result;
 319      
 320  }
 321  
 322  /**
 323   * Enter description here...
 324   *
 325   * @param unknown $val
 326   * @param integer $quote_style
 327   * @return unknown
 328   * 
 329   * $quote_style may be one of:
 330   *     ENT_COMPAT   : Will convert double-quotes and leave single-quotes alone. 
 331   *     ENT_QUOTES   : Will convert both double and single quotes. 
 332   *     ENT_NOQUOTES : Will leave both double and single quotes unconverted. 
 333   */
 334  function my_htmlentities($val)
 335  {
 336      if ($val == "")
 337      {
 338          return "";
 339      }
 340      $val = str_replace( "&#032;", " ", $val ); 
 341  
 342      //Remove sneaky spaces 
 343      // $val = str_replace( chr(0xCA), "", $val );   
 344  
 345      $val = str_replace( "&"            , "&amp;"         , $val ); 
 346      $val = str_replace( "<!--"         , "&#60;&#33;--"  , $val ); 
 347      $val = str_replace( "-->"          , "--&#62;"       , $val ); 
 348      $val = preg_replace( "/<script/i"  , "&#60;script"   , $val ); 
 349      $val = str_replace( ">"            , "&gt;"          , $val ); 
 350      $val = str_replace( "<"            , "&lt;"          , $val ); 
 351      
 352      
 353      $val = str_replace( "\""           , "&quot;"        , $val ); 
 354  
 355      // Uncomment it if you need to convert literal newlines 
 356      //$val = preg_replace( "/\n/"        , "<br>"          , $val ); 
 357  
 358      $val = preg_replace( "/\\$/"      , "&#036;"        , $val ); 
 359  
 360      // Uncomment it if you need to remove literal carriage returns 
 361      //$val = preg_replace( "/\r/"        , ""              , $val ); 
 362  
 363      $val = str_replace( "!"            , "&#33;"         , $val ); 
 364      $val = str_replace( "'"            , "&#39;"         , $val ); 
 365       
 366      // Uncomment if you need to convert unicode chars 
 367      //$val = preg_replace("/&#([0-9]+);/s", "&#\1;", $val ); 
 368  
 369      // Strip slashes if not already done so. 
 370  
 371      //if ( get_magic_quotes_gpc() ) 
 372      //{ 
 373      //    $val = stripslashes($val); 
 374      //} 
 375  
 376      // Swop user inputted backslashes 
 377  
 378      //$val = preg_replace( "/\(?!&#|?#)/", "&#092;", $val );
 379  
 380      return $val;
 381  }
 382  
 383  
 384  /**
 385   * Enter description here...
 386   *
 387   * @param unknown $val
 388   * @return unknown
 389   */
 390  function cms_utf8entities($val)
 391  {
 392      if ($val == "")
 393      {
 394          return "";
 395      }
 396      $val = str_replace( "&#032;", " ", $val ); 
 397  
 398      //Remove sneaky spaces 
 399      // $val = str_replace( chr(0xCA), "", $val );   
 400  
 401      $val = str_replace( "&"            , "\u0026"         , $val ); 
 402  #    $val = str_replace( "<!--"         , "&#60;&#33;--"  , $val ); 
 403  #    $val = str_replace( "-->"          , "--&#62;"       , $val ); 
 404  #    $val = preg_replace( "/<script/i"  , "&#60;script"   , $val ); 
 405      $val = str_replace( ">"            , "\u003E"          , $val ); 
 406      $val = str_replace( "<"            , "\u003C"          , $val ); 
 407      
 408      
 409      $val = str_replace( "\""           , "\u0022"        , $val ); 
 410  
 411      // Uncomment it if you need to convert literal newlines 
 412      //$val = preg_replace( "/\n/"        , "<br>"          , $val ); 
 413  
 414      #$val = preg_replace( "/\\$/"      , "&#036;"        , $val ); 
 415  
 416      // Uncomment it if you need to remove literal carriage returns 
 417      //$val = preg_replace( "/\r/"        , ""              , $val ); 
 418  
 419      $val = str_replace( "!"            , "\u0021"         , $val ); 
 420      $val = str_replace( "'"            , "\u0027"         , $val ); 
 421       
 422      // Uncomment if you need to convert unicode chars 
 423      //$val = preg_replace("/&#([0-9]+);/s", "&#\1;", $val ); 
 424  
 425      // Strip slashes if not already done so. 
 426  
 427      //if ( get_magic_quotes_gpc() ) 
 428      //{ 
 429      //    $val = stripslashes($val); 
 430      //} 
 431  
 432      // Swop user inputted backslashes 
 433  
 434      //$val = preg_replace( "/\(?!&#|?#)/", "&#092;", $val );
 435  
 436      return $val;
 437  }
 438  
 439  
 440  //Taken from http://www.webmasterworld.com/forum88/164.htm
 441  function nl2pnbr( $text )
 442  {
 443      // Use \n for newline on all systems
 444      $text = preg_replace("/(\r\n|\n|\r)/", "\n", $text);
 445  
 446      // Only allow two newlines in a row.
 447      $text = preg_replace("/\n\n+/", "\n\n", $text);
 448  
 449      // Put <p>..</p> around paragraphs
 450      $text = preg_replace('/\n?(.+?)(\n\n|\z)/s', "<p>$1</p>", $text);
 451  
 452      // Convert newlines not preceded by </p> to a <br /> tag
 453      $text = preg_replace('|(?<!</p>)\s*\n|', "<br />", $text);
 454  
 455      return $text;
 456  }
 457  
 458  function debug_bt() 
 459  { 
 460      $bt=debug_backtrace(); 
 461      $file = $bt[0]['file']; 
 462      $line = $bt[0]['line']; 
 463   
 464      echo "\n\n<p><b>Backtrace in $file on line $line</b></p>\n"; 
 465   
 466      $bt = array_reverse($bt); 
 467      echo "<pre><dl>\n"; 
 468      foreach($bt as $trace) 
 469      { 
 470          $file = $trace['file']; 
 471          $line = $trace['line']; 
 472          $function = $trace['function']; 
 473          $args = implode(',', $trace['args']); 
 474          echo "
 475          <dt><b>$function</b>($args) </dt> 
 476          <dd>$file on line $line</dd> 
 477          ";
 478      } 
 479      echo "</dl></pre>\n"; 
 480  }
 481  
 482  /**
 483  * Debug function to display $var nicely in html.
 484  * 
 485  * @param mixed $var
 486  * @param string $title (optional)
 487  * @param boolean $echo_to_screen (optional)
 488  * @return string
 489  */
 490  function debug_display($var, $title="", $echo_to_screen = true, $use_html = true)
 491  {
 492      global $gCms;
 493      $variables =& $gCms->variables;
 494  
 495      $starttime = microtime();
 496      if (isset($variables['starttime']))
 497          $starttime = $variables['starttime'];
 498      else
 499          $variables['starttime'] = $starttime;
 500      
 501      $titleText = "Debug: ";
 502      if($title)
 503      {
 504          $titleText = "Debug display of '$title':";
 505      }
 506      $titleText .= '(' . microtime_diff($starttime,microtime()) . ')';
 507      
 508      if (function_exists('memory_get_usage'))
 509      {
 510          $titleText .= ' - ('.memory_get_usage().')';
 511      }
 512  
 513      ob_start();
 514      if ($use_html)
 515          echo "<div><b>$titleText</b>\n";
 516  
 517      if(FALSE == empty($var))
 518      {
 519          if ($use_html)
 520          {
 521              echo '<pre>';
 522          }
 523          if(is_array($var))
 524          {
 525              echo "Number of elements: " . count($var) . "\n";
 526              print_r($var);
 527          }
 528          elseif(is_object($var))
 529          {
 530              print_r($var);
 531          }
 532          elseif(is_string($var))
 533          {
 534              print_r(htmlentities(str_replace("\t", '  ', $var)));
 535          }
 536          elseif(is_bool($var))
 537          {
 538              echo $var === true ? 'true' : 'false';
 539          }
 540          else
 541          {
 542              print_r($var);
 543          }
 544          if ($use_html)
 545          {
 546              echo '</pre>';
 547          }
 548      }
 549      if ($use_html)
 550          echo "</div>\n";
 551  
 552      $output = ob_get_contents();
 553      ob_end_clean();
 554  
 555      if($echo_to_screen)
 556      {
 557          echo $output;
 558      }
 559  
 560      return $output;
 561  }
 562  
 563  /**
 564   * Display $var nicely only if $config["debug"] is set
 565   *
 566   * @param mixed $var
 567   * @param string $title
 568   */
 569  function debug_output($var, $title="")
 570  {
 571      global $gCms;
 572      if($gCms->config["debug"] == true)
 573      {
 574          debug_display($var, $title, true);
 575      }
 576  
 577  }
 578  
 579  function debug_to_log($var, $title='')
 580  {
 581      global $gCms;
 582  
 583      $errlines = explode("\n",debug_display($var, $title, false, false));
 584      $filename = TMP_CACHE_LOCATION . '/debug.log';
 585      //$filename = dirname(dirname(__FILE__)) . '/uploads/debug.log';
 586      foreach ($errlines as $txt)
 587      {
 588          error_log($txt . "\n", 3, $filename);
 589      }
 590  }
 591  
 592  /**
 593   * Display $var nicely to the $gCms->errors array if $config['debug'] is set
 594   *
 595   * @param mixed $var
 596   * @param string $title
 597   */
 598  function debug_buffer($var, $title="")
 599  {
 600      global $gCms;
 601      if ($gCms)
 602      {
 603          $config =& $gCms->GetConfig();
 604      
 605          //debug_to_log($var, $title='');
 606  
 607          if($config["debug"] == true)
 608          {
 609              $gCms->errors[] = debug_display($var, $title, false, true);
 610          }
 611      }
 612  }
 613  
 614  function debug_sql($str, $newline)
 615  {
 616      global $gCms;
 617      if ($gCms)
 618      {
 619          $config =& $gCms->GetConfig();
 620      
 621          if($config["debug"] == true)
 622          {
 623              $gCms->errors[] = debug_display($str, '', false, true);
 624          }
 625      }
 626  }
 627  
 628  /**
 629  * Retrieve value from $_REQUEST. Returns $default_value if
 630  *        value is not in $_REQUEST or is not the same basic type as
 631  *        $default_value.
 632  *        If $session_key is set, then will return session value in preference
 633  *        to $default_value if $_REQUEST[$value] is not set.
 634  * 
 635  * @param string $value
 636  * @param mixed $default_value (optional)
 637  * @param string $session_key (optional)
 638  * @return mixed
 639  */
 640  function get_request_value($value, $default_value = '', $session_key = '')
 641  {
 642      if($session_key != '')
 643      {
 644          if(isset($_SESSION['request_values'][$session_key][$value]))
 645          {
 646              $default_value = $_SESSION['request_values'][$session_key][$value];
 647          }
 648      }
 649      if(isset($_REQUEST[$value]))
 650      {
 651          $result = get_value_with_default($_REQUEST[$value], $default_value);
 652      }
 653      else
 654      {
 655          $result = $default_value;
 656      }
 657  
 658      if($session_key != '')
 659      {
 660          $_SESSION['request_values'][$session_key][$value] = $result;
 661      }
 662  
 663      return $result;
 664  }
 665  
 666  /**
 667  * Return $value if it's set and same basic type as $default_value,
 668  *            otherwise return $default_value. Note. Also will trim($value)
 669  *            if $value is not numeric.
 670  * 
 671  * @param string $value
 672  * @param mixed $default_value
 673  * @return mixed
 674  */
 675  function get_value_with_default($value, $default_value = '', $session_key = '')
 676  {
 677      if($session_key != '')
 678      {
 679          if(isset($_SESSION['default_values'][$session_key]))
 680          {
 681              $default_value = $_SESSION['default_values'][$session_key];
 682          }
 683      }
 684  
 685      // set our return value to the default initially and overwrite with $value if we like it.
 686      $return_value = $default_value;
 687  
 688      if(isset($value))
 689      {
 690          if(is_array($value))
 691          {
 692              // $value is an array - validate each element.
 693              $return_value = array();
 694              foreach($value as $element)
 695              {
 696                  $return_value[] = get_value_with_default($element, $default_value);
 697              }
 698          }
 699          else
 700          {
 701              if(is_numeric($default_value))
 702              {
 703                  if(is_numeric($value))
 704                  {
 705                      $return_value = $value;
 706                  }
 707              }
 708              else
 709              {
 710                  $return_value = trim($value);
 711              }
 712          }
 713      }
 714      
 715      if($session_key != '')
 716      {
 717          $_SESSION['default_values'][$session_key] = $return_value;
 718      }
 719      
 720      return $return_value;
 721  }
 722  
 723  /**
 724   * Retrieve the $value from the $parameters array checking for
 725   * $parameters[$value] and $params[$id.$value]. Returns $default
 726   * if $value is not in $params array. 
 727   * Note: This function will also trim() string values.
 728   *
 729   * @param array $parameters
 730   * @param string $value
 731   * @param mixed $default_value
 732   * @param string $session_key
 733   * @return mixed
 734   */
 735  function get_parameter_value($parameters, $value, $default_value = '', $session_key = '')
 736  {
 737      if($session_key != '')
 738      {
 739          if(isset($_SESSION['parameter_values'][$session_key]))
 740          {
 741              $default_value = $_SESSION['parameter_values'][$session_key];
 742          }
 743      }
 744  
 745      // set our return value to the default initially and overwrite with $value if we like it.
 746      $return_value = $default_value;
 747      if(isset($parameters[$value]))
 748      {
 749          if(is_bool($default_value))
 750          {
 751              // want a boolean return_value
 752              if(isset($parameters[$value]))
 753              {
 754                  $return_value = (boolean)$parameters[$value];
 755              }
 756          }
 757          else
 758          {
 759              // is $default_value a number?
 760              $is_number = false;
 761              if(is_numeric($default_value))
 762              {
 763                  $is_number = true;
 764              }
 765          
 766              if(is_array($parameters[$value]))
 767              {
 768                  // $parameters[$value] is an array - validate each element.
 769                  $return_value = array();
 770                  foreach($parameters[$value] as $element)
 771                  {
 772                      $return_value[] = get_value_with_default($element, $default_value);
 773                  }
 774              }
 775              else
 776              {
 777                  if(is_numeric($default_value))
 778                  {
 779                      // default value is a number, we only like $parameters[$value] if it's a number too.
 780                      if(is_numeric($parameters[$value]))
 781                      {
 782                          $return_value = $parameters[$value];
 783                      }
 784                  }
 785                  elseif(is_string($default_value))
 786                  {
 787                      $return_value = trim($parameters[$value]);
 788                  }
 789                  else
 790                  {
 791                      $return_value = $parameters[$value];
 792                  }
 793              }
 794          }
 795      }
 796  
 797      if($session_key != '')
 798      {
 799          $_SESSION['parameter_values'][$session_key] = $return_value;
 800      }
 801      
 802      return $return_value;
 803  }
 804  
 805  function create_encoding_dropdown($name = 'encoding', $selected = '')
 806  {
 807      $result = '';
 808  
 809      $encodings = array(''=>'Default','UTF-8'=>'Unicode','ISO-8859-1'=>'Latin 1/West European','ISO-8859-2'=>'Latin 2/Central European','ISO-8859-3'=>'Latin 3/South European','ISO-8859-4'=>'Latin 4/North European','ISO-8859-5'=>'Cyrilic','ISO-8859-6'=>'Arabic','ISO-8859-7'=>'Greek','ISO-8859-8'=>'Hebrew','ISO-8859-9'=>'Latin 5/Turkish','ISO-8859-11'=>'TIS-620/Thai','ISO-8859-14'=>'Latin 8','ISO-8859-15'=>'Latin 9','Big5'=>'Taiwanese','GB2312'=>'Chinese','EUC-JP'=>'Japanese','EUC-KR'=>'Korean','KOI8-R'=>'Russian','Windows-1250'=>'Central Europe','Windows-1251'=>'Cyrilic','Windows-1252'=>'Latin 1','Windows-1253'=>'Greek','Windows-1254'=>'Turkish','Windows-1255'=>'Hebrew','Windows-1256'=>'Arabic','Windows-1257'=>'Baltic','Windows-1258'=>'Vietnam');
 810  
 811      $result .= '<select name="'.$name.'">';
 812      foreach ($encodings as $key=>$value)
 813      {
 814          $result .= '<option value="'.$key.'"';
 815          if ($selected == $key)
 816          {
 817              $result .= ' selected="selected"';
 818          }
 819          $result .= '>'.$key.($key!=''?' - ':'').$value.'</option>';
 820      }
 821      $result .= '</select>';
 822  
 823      return $result;
 824  }
 825  
 826  function cms_mapi_create_permission($cms, $permission_name, $permission_text)
 827  {
 828      global $gCms;
 829      $db = &$gCms->GetDb();
 830  
 831      $query = "SELECT permission_id FROM ".cms_db_prefix()."permissions WHERE permission_name =" . $db->qstr($permission_name); 
 832      $result = $db->Execute($query);
 833  
 834      if ($result && $result->RecordCount() < 1) {
 835  
 836          $new_id = $db->GenID(cms_db_prefix()."permissions_seq");
 837          $query = "INSERT INTO ".cms_db_prefix()."permissions (permission_id, permission_name, permission_text, create_date, modified_date) VALUES ($new_id, ".$db->qstr($permission_name).",".$db->qstr($permission_text).",".$db->DBTimeStamp(time()).",".$db->DBTimeStamp(time()).")";
 838          $db->Execute($query);
 839      }
 840      
 841      if ($result) $result->Close();
 842  }
 843  
 844  
 845  function filespec_is_excluded( $file, $excludes )
 846  {
 847    // strip the path from the file
 848    foreach( $excludes as $excl )
 849      {
 850        if( @preg_match( "/".$excl."/i", basename($file) ) )
 851      {
 852        return true;
 853      }
 854      }
 855    return false;
 856  }
 857  
 858  
 859  /**
 860   * Check the permissions of a directory recursively to make sure that
 861   * we have write permission to all files
 862   * &param  path      start path
 863  */
 864  function is_directory_writable( $path )
 865  {
 866  //   if( can_admin_upload() == FALSE )
 867  //     {
 868  //       return false;
 869  //     }
 870  
 871    if ( substr ( $path , strlen ( $path ) - 1 ) != '/' )
 872      { 
 873        $path .= '/' ; 
 874      }     
 875  
 876    $result = true;
 877    if( $handle = @opendir( $path ) )
 878      {
 879        while( false !== ( $file = readdir( $handle ) ) )
 880      {
 881        if( $file == '.' || $file == '..' )
 882          {
 883            continue;
 884          }
 885        
 886        $p = $path.$file;
 887        
 888        if( !@is_writable( $p ) )
 889          {
 890            return false;
 891          }
 892        
 893        if( @is_dir( $p ) )
 894          {
 895            $result = is_directory_writable( $p );
 896            if( !$result )
 897          {
 898            return false;
 899          }
 900          }
 901      }
 902        @closedir( $handle );
 903      }
 904    else
 905      {
 906        return false;
 907      }
 908    
 909    return true;
 910  }
 911  
 912  /**
 913   * Return an array containing a list of files in a directory
 914   * performs a recursive serach
 915   * @param  path      start path
 916   * @param  maxdepth  how deep to browse (-1=unlimited)
 917   * @param  mode      "FULL"|"DIRS"|"FILES"
 918   * @param  d         for internal use only
 919  **/
 920  function get_recursive_file_list ( $path , $excludes, $maxdepth = -1 , $mode = "FULL" , $d = 0 )
 921  {
 922     if ( substr ( $path , strlen ( $path ) - 1 ) != '/' ) { $path .= '/' ; }     
 923     $dirlist = array () ;
 924     if ( $mode != "FILES" ) { $dirlist[] = $path ; }
 925     if ( $handle = opendir ( $path ) )
 926     {
 927         while ( false !== ( $file = readdir ( $handle ) ) )
 928         {
 929         $excluded = filespec_is_excluded( $file, $excludes );
 930             if ( $file != '.' && $file != '..' && $excluded == false )
 931             {
 932                 $file = $path . $file ;
 933                 if ( ! @is_dir ( $file ) ) { if ( $mode != "DIRS" ) { $dirlist[] = $file ; } }
 934                 elseif ( $d >=0 && ($d < $maxdepth || $maxdepth < 0) )
 935                 {
 936             $result = get_recursive_file_list ( $file . '/' , $excludes, $maxdepth , $mode , $d + 1 ) ;
 937                     $dirlist = array_merge ( $dirlist , $result ) ;
 938                 }
 939         }
 940         }
 941         closedir ( $handle ) ;
 942     }
 943     if ( $d == 0 ) { natcasesort ( $dirlist ) ; }
 944     return ( $dirlist ) ;
 945  }
 946  
 947  
 948  function recursive_delete( $dirname )
 949  {
 950    // all subdirectories and contents:
 951    if(is_dir($dirname))$dir_handle=opendir($dirname);
 952    while($file=readdir($dir_handle))
 953    {
 954      if($file!="." && $file!="..")
 955      {
 956        if(!is_dir($dirname."/".$file))
 957      {
 958        if( !@unlink ($dirname."/".$file) )
 959          {
 960            closedir( $dir_handle );
 961            return false;
 962          }
 963      }
 964        else 
 965      {
 966        recursive_delete($dirname."/".$file);
 967      }
 968      }
 969    }
 970    closedir($dir_handle);
 971    if( ! @rmdir($dirname) )
 972      {
 973        return false;
 974      }
 975    return true;
 976  }
 977  
 978  
 979  function chmod_r( $path, $mode )
 980  {
 981    if( !is_dir( $path ) )
 982      return chmod( $path, $mode );
 983  
 984    $dh = @opendir( $path );
 985    if( !$dh ) return FALSE;
 986  
 987    while( $file = readdir( $dh ) )
 988    {
 989      if( $file == '.' || $file == '..' ) continue;
 990      
 991      $p = $path.DIRECTORY_SEPARATOR.$file;
 992      if( is_dir( $p ) )
 993      {
 994        if( !@chmod_r( $p, $mode ) )
 995      {
 996        closedir( $dh );
 997        return false;
 998      }
 999      }
1000      else if( !is_link( $p ) )
1001      {
1002        if( !@chmod( $p, $mode ) )
1003      {
1004        closedir( $dh );
1005        return false;
1006      }
1007      }
1008    }
1009    @closedir( $dh );
1010    return @chmod( $path, $mode );
1011  }
1012  
1013  
1014  function SerializeObject(&$object)
1015  {
1016      return base64_encode(serialize($object));
1017  }
1018  
1019  function UnserializeObject(&$serialized)
1020  {
1021      return  unserialize(base64_decode($serialized));
1022  }
1023  
1024  function startswith( $str, $sub )
1025  {
1026      return ( substr( $str, 0, strlen( $sub ) ) == $sub );
1027  }
1028  
1029  function endswith( $str, $sub )
1030  {
1031      return ( substr( $str, strlen( $str ) - strlen( $sub ) ) == $sub );
1032  }
1033  
1034  function showmem($string = '')
1035  {
1036      var_dump($string . ' -- ' . memory_get_usage());
1037  }
1038  
1039  function munge_string_to_url($alias, $tolower = false)
1040  {
1041      // replacement.php is encoded utf-8 and must be the first modification of alias
1042      include(dirname(__FILE__) . '/replacement.php');
1043      $alias = str_replace($toreplace, $replacement, $alias);
1044      
1045      // lowercase only on empty aliases
1046      if ($tolower == true)
1047      {
1048          $alias = strtolower($alias);
1049      }
1050          
1051      $alias = preg_replace("/[^\w-]+/", "-", $alias);
1052      $alias = trim($alias, '-');
1053  
1054      return $alias;
1055  }
1056  
1057  if(!function_exists("file_get_contents"))
1058  {
1059     function file_get_contents($filename)
1060     {
1061         if(($contents = file($filename)))
1062         {
1063             $contents = implode('', $contents);
1064             return $contents;
1065         }
1066         else
1067             return false;
1068     }
1069  }
1070  
1071  // create the array_walk_recursive function in PHP4
1072  // from http://www.php.net/manual/en/function.array-walk-recursive.php
1073  if (!function_exists('array_walk_recursive'))
1074  {
1075     function array_walk_recursive(&$input, $funcname, $userdata = "")
1076     {
1077         if (!is_callable($funcname))
1078         {
1079             return false;
1080         }
1081        
1082         if (!is_array($input))
1083         {
1084             return false;
1085         }
1086        
1087         foreach ($input AS $key => $value)
1088         {
1089             if (is_array($input[$key]))
1090             {
1091                 array_walk_recursive($input[$key], $funcname, $userdata);
1092             }
1093             else
1094             {
1095                 $saved_value = $value;
1096                 if (!empty($userdata))
1097                 {
1098                     $funcname($value, $key, $userdata);
1099                 }
1100                 else
1101                 {
1102                     $funcname($value, $key);
1103                 }
1104                
1105                 if ($value != $saved_value)
1106                 {
1107                     $input[$key] = $value;
1108                 }
1109             }
1110         }
1111         return true;
1112      }
1113  }
1114  
1115  /*
1116   * Sanitize input to prevent against XSS and other nasty stuff.
1117   * Taken from cakephp (http://cakephp.org)
1118   * Licensed under the MIT License
1119   */
1120  function cleanValue($val) {
1121      if ($val == "") {
1122          return $val;
1123      }
1124      //Replace odd spaces with safe ones
1125      $val = str_replace(" ", " ", $val);
1126      $val = str_replace(chr(0xCA), "", $val);
1127      //Encode any HTML to entities (including \n --> <br />)
1128      $val = cleanHtml($val);
1129      //Double-check special chars and remove carriage returns
1130      //For increased SQL security
1131      $val = preg_replace("/\\\$/", "$", $val);
1132      $val = preg_replace("/\r/", "", $val);
1133      $val = str_replace("!", "!", $val);
1134      $val = str_replace("'", "'", $val);
1135      //Allow unicode (?)
1136      $val = preg_replace("/&amp;#([0-9]+);/s", "&#\\1;", $val);
1137      //Add slashes for SQL
1138      //$val = $this->sql($val);
1139      //Swap user-inputted backslashes (?)
1140      $val = preg_replace("/\\\(?!&amp;#|\?#)/", "\\", $val);
1141      return $val;
1142  }
1143  
1144  /*
1145   * Method to sanitize incoming html.
1146   * Take from cakephp (http://cakephp.org)
1147   * Licensed under the MIT License
1148   */
1149  function cleanHtml($string, $remove = false) {
1150      if ($remove) {
1151          $string = strip_tags($string);
1152      } else {
1153          $patterns = array("/\&/", "/%/", "/</", "/>/", '/"/', "/'/", "/\(/", "/\)/", "/\+/", "/-/");
1154          $replacements = array("&amp;", "&#37;", "&lt;", "&gt;", "&quot;", "&#39;", "&#40;", "&#41;", "&#43;", "&#45;");
1155          $string = preg_replace($patterns, $replacements, $string);
1156      }
1157      return $string;
1158  }
1159  
1160  /**
1161   * Returns all parameters sent that are destined for the module with
1162   * the given $id
1163   */
1164  function GetModuleParameters($id)
1165  {
1166      $params = array();
1167  
1168      if ($id != '')
1169      {
1170          foreach ($_REQUEST as $key=>$value)
1171          {
1172              if (strpos($key, (string)$id) !== FALSE && strpos($key, (string)$id) == 0)
1173              {
1174                  $key = str_replace($id, '', $key);
1175                  $params[$key] = $value;
1176              }
1177          }
1178      }
1179  
1180      return $params;
1181  }
1182  
1183  
1184  function can_users_upload()
1185  {
1186    # first, check to see if safe mode is enabled
1187    # if it is, then check to see the owner of the index.php, moduleinterface.php
1188    # and the uploads and modules directory.  if they all match, then we
1189    # can upload files.
1190    # if safe mode is off, then we just have to check the permissions.
1191    global $gCms;
1192    $file_index = $gCms->config['root_path'].DIRECTORY_SEPARATOR.'index.php';
1193    $dir_uploads = $gCms->config['uploads_path'];
1194  
1195    $stat_index = @stat($file_index);
1196    $stat_uploads = @stat($dir_uploads);
1197  
1198    if( $stat_index == FALSE || $stat_uploads == FALSE )
1199      {
1200        // couldn't get some necessary information.
1201        return false;
1202      }
1203  
1204    $safe_mode = (strtolower(ini_get('safe_mode')) == "off")?FALSE:TRUE;  
1205    if( $safe_mode == TRUE )
1206      {
1207        // we're in safe mode.
1208        if( $stat_index[4] != $stat_uploads[4] )
1209      {
1210        return FALSE;
1211      }
1212      }
1213  
1214    // now check to see if we can write to the directories
1215    if( !is_writable( $dir_modules ) )
1216      {
1217        return FALSE;
1218      }
1219    if( !is_writable( $dir_uploads ) )
1220      {
1221        return FALSE;
1222      }
1223    
1224    // It all worked.
1225    return TRUE;
1226  }
1227  
1228  function can_admin_upload()
1229  {
1230    # first, check to see if safe mode is enabled
1231    # if it is, then check to see the owner of the index.php, moduleinterface.php
1232    # and the uploads and modules directory.  if they all match, then we
1233    # can upload files.
1234    # if safe mode is off, then we just have to check the permissions.
1235    global $gCms;
1236    $file_index = $gCms->config['root_path'].DIRECTORY_SEPARATOR.'index.php';
1237    $file_moduleinterface = $gCms->config['root_path'].DIRECTORY_SEPARATOR.
1238      $gCms->config['admin_dir'].DIRECTORY_SEPARATOR.'moduleinterface.php';
1239    $dir_uploads = $gCms->config['uploads_path'];
1240    $dir_modules = $gCms->config['root_path'].DIRECTORY_SEPARATOR.'modules';
1241  
1242    $stat_index = @stat($file_index);
1243    $stat_moduleinterface = @stat($file_moduleinterface);
1244    $stat_uploads = @stat($dir_uploads);
1245    $stat_modules = @stat($dir_modules);
1246  
1247    $my_uid = @getmyuid();
1248  
1249    if( $my_uid === FALSE || $stat_index == FALSE || 
1250        $stat_moduleinterface == FALSE || $stat_uploads == FALSE ||
1251        $stat_modules == FALSE )
1252      {
1253        // couldn't get some necessary information.
1254        return FALSE;
1255      }
1256  
1257    $safe_mode = (ini_get('safe_mode')==1)?TRUE:FALSE;
1258    if( $safe_mode == TRUE )
1259      {
1260  
1261        // we're in safe mode.
1262        if( ($stat_moduleinterface[4] != $stat_modules[4]) ||
1263        ($stat_moduleinterface[4] != $stat_uploads[4]) ||
1264        ($my_uid != $stat_moduleinterface[4]) )
1265      {
1266        // owners don't match
1267        return FALSE;
1268      }
1269      }
1270  
1271    // now check to see if we can write to the directories
1272    if( !is_writable( $dir_modules ) )
1273      {
1274        return FALSE;
1275      }
1276    if( !is_writable( $dir_uploads ) )
1277      {
1278        return FALSE;
1279      }
1280    
1281    // It all worked.
1282    return TRUE;
1283  }
1284  
1285  function interpret_permissions($perms)
1286  {
1287    $owner = array();
1288    $group = array();
1289    $other = array();
1290  
1291    if( $perms | 0400 )
1292      {
1293        $owner[] = lang('read');
1294      }
1295    if( $perms | 0200 )
1296      {
1297        $owner[] = lang('write');
1298      }
1299    if( $perms | 0100 )
1300      {
1301        $owner[] = lang('execute');
1302      }
1303  
1304    if( $perms | 0040 )
1305      {
1306        $group[] = lang('read');
1307      }
1308    if( $perms | 0020 )
1309      {
1310        $group[] = lang('write');
1311      }
1312    if( $perms | 0010 )
1313      {
1314        $group[] = lang('execute');
1315      }
1316  
1317    if( $perms | 0004 )
1318      {
1319        $other[] = lang('read');
1320      }
1321    if( $perms | 0002 )
1322      {
1323        $other[] = lang('write');
1324      }
1325    if( $perms | 0001 )
1326      {
1327        $other[] = lang('execute');
1328      }
1329  
1330    return array($owner,$group,$other);
1331  }
1332  # vim:ts=4 sw=4 noet
1333  ?>


Généré le : Tue Apr 3 18:50:37 2007 par Balluche grâce à PHPXref 0.7