[ Index ]

PHP Cross Reference of phpwcms V1.4.7 _r403 (01.11.10)

title

Body

[close]

/include/inc_lib/ -> general.inc.php (source)

   1  <?php
   2  /*************************************************************************************
   3     Copyright notice
   4     
   5     (c) 2002-2010 Oliver Georgi (oliver@phpwcms.de) // All rights reserved.
   6   
   7     This script is part of PHPWCMS. The PHPWCMS web content management system is
   8     free software; you can redistribute it and/or modify it under the terms of
   9     the GNU General Public License as published by the Free Software Foundation;
  10     either version 2 of the License, or (at your option) any later version.
  11    
  12     The GNU General Public License can be found at http://www.gnu.org/copyleft/gpl.html
  13     A copy is found in the textfile GPL.txt and important notices to the license 
  14     from the author is found in LICENSE.txt distributed with these scripts.
  15    
  16     This script is distributed in the hope that it will be useful, but WITHOUT ANY 
  17     WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
  18     PARTICULAR PURPOSE.  See the GNU General Public License for more details.
  19   
  20     This copyright notice MUST APPEAR in all copies of the script!
  21  *************************************************************************************/
  22  
  23  
  24  if(PHPWCMS_CHARSET == 'utf-8') {
  25      require_once  (PHPWCMS_ROOT.'/include/inc_lib/lib.php_special_entities.utf-8.php');
  26  } else {
  27      require_once  (PHPWCMS_ROOT.'/include/inc_lib/lib.php_special_entities.php');
  28  }
  29  require_once  (PHPWCMS_ROOT.'/include/inc_lib/charset_helper.inc.php');
  30  require_once  (PHPWCMS_ROOT.'/include/inc_ext/htmlfilter/htmlfilter.php');
  31  require_once  (PHPWCMS_ROOT.'/include/inc_lib/helper.inc.php');
  32  
  33  
  34  function isEmpty($string) {
  35      return ($string == NULL || $string == '') ? 1 : 0;
  36  }
  37  
  38  function slweg($string_wo_slashes_weg, $string_laenge=0, $trim=true) {
  39      // Falls die Serverfunktion magic_quotes_gpc aktiviert ist, so
  40      // sollen die Slashes herausgenommen werden, anderenfalls nicht
  41      if($trim) $string_wo_slashes_weg = trim($string_wo_slashes_weg);
  42      if( get_magic_quotes_gpc() ) $string_wo_slashes_weg = stripslashes ($string_wo_slashes_weg);
  43      if($string_laenge) $string_wo_slashes_weg = substr($string_wo_slashes_weg, 0, $string_laenge);
  44      $string_wo_slashes_weg = preg_replace( array('/<br>$/i','/<br \/>$/i','/<p><\/p>$/i','/<p>&nbsp;<\/p>$/i') , '', $string_wo_slashes_weg);
  45      return $string_wo_slashes_weg;
  46  }
  47  
  48  function clean_slweg($string_wo_slashes_weg, $string_laenge=0, $trim=true) {
  49      // Falls die Serverfunktion magic_quotes_gpc aktiviert ist, so
  50      // sollen die Slashes herausgenommen werden, anderenfalls nicht
  51      if($trim) $string_wo_slashes_weg = trim($string_wo_slashes_weg);
  52      if( get_magic_quotes_gpc() ) $string_wo_slashes_weg = stripslashes ($string_wo_slashes_weg);
  53      $string_wo_slashes_weg = strip_tags($string_wo_slashes_weg);
  54      if($string_laenge) $string_wo_slashes_weg = substr($string_wo_slashes_weg, 0, $string_laenge);
  55      return $string_wo_slashes_weg;
  56  }
  57  
  58  function getpostvar($formvar, $string_laenge=0) {
  59      //combines trim, stripslashes und apostrophe replace
  60      return aporeplace( slweg( $formvar, $string_laenge ) );
  61  }
  62  
  63  function html_specialchars($h='') {
  64      //used to replace the htmlspecialchars original php function
  65      //not compatible with many internation chars like turkish, polish
  66      $h = preg_replace('/&(?!((#[0-9]+)|[a-z]+);)/s', '&amp;', $h ); //works correct for "&#8230;" and/or "&ndash;"
  67      //$h = preg_replace('/&(?!#[0-9]+;)/s', '&amp;', $h );
  68      $h = str_replace( '<', '&lt;'  , $h );
  69      $h = str_replace( '>', '&gt;'  , $h );
  70      $h = str_replace( '"', '&quot;', $h );
  71      $h = str_replace( "'", '&#039;', $h );
  72      $h = str_replace( "\\", '&#92;', $h );
  73      return $h;
  74  }
  75      
  76  function html_despecialchars($h='') {
  77      //call off html_specialchars
  78      $h = str_replace( '&amp;' , '&', $h );
  79      $h = str_replace( '&lt;'  , '<', $h );
  80      $h = str_replace( '&gt;'  , '>', $h );
  81      $h = str_replace( '&quot;', '"', $h );
  82      $h = str_replace( '&#039;', "'", $h );
  83      $h = str_replace( '&#92;' , "\\", $h );    
  84      return $h;
  85  }
  86  
  87  function trimhtml($h='') {
  88      return html_specialchars(trim($h));
  89  }
  90  
  91  function list_country($c, $lang='') {
  92      //Create the country list menu for forms with the given value selected
  93      //$c = selected value
  94      if(empty($c)) {
  95          $c = strtoupper($GLOBALS['phpwcms']['default_lang']);
  96      }
  97      $country_list = '';
  98      $country = getCountry($lang);
  99      foreach($country as $key => $value) {
 100          $country_list .= '    <option value="'.html_specialchars($key).'"';
 101          if($key == $c) {
 102              $country_list .= ' selected="selected"';
 103          }
 104          $country_list .= '>'.html_specialchars($value).'</option>' . LF;
 105      }
 106      return $country_list;
 107  }
 108  
 109  function getCountry($lang='', $get='COUNTRY_ARRAY') {
 110      
 111      global $phpwcms;
 112  
 113      if(empty($lang)) {
 114          $lang = isset($_SESSION["wcs_user_lang"]) ? strtolower($_SESSION["wcs_user_lang"]) : $GLOBALS['phpwcms']['default_lang'];
 115      }
 116      $lang = strtolower(substr($lang, 0, 2));
 117      
 118      $country_lang_var = $get . '_' . $lang;
 119      
 120      if(!empty($phpwcms['country'][$country_lang_var])) {
 121  
 122          return $phpwcms['country'][$country_lang_var];
 123      }
 124          
 125      $country_name    = 'country_name_'.aporeplace($lang);
 126      $sql            = 'SHOW COLUMNS FROM '.DB_PREPEND."phpwcms_country WHERE Field='".$country_name."'";
 127      $result            = _dbQuery($sql);
 128      if(!isset($result[0])) {
 129          $country_name = 'country_name';
 130      }
 131      
 132      if($get == 'COUNTRY_NAME') {
 133          
 134          $phpwcms['country'][$country_lang_var] = strtoupper($lang);
 135          
 136          $sql  = 'SELECT '.$country_name.' AS country FROM '.DB_PREPEND."phpwcms_country WHERE ";
 137          $sql .= "country_iso='".aporeplace($phpwcms['country'][$country_lang_var])."' LIMIT 1";
 138          $result    = _dbQuery($sql);
 139          
 140          if(isset($result[0]['country'])) {
 141  
 142              $phpwcms['country'][$country_lang_var] = $result[0]['country'];
 143  
 144          }
 145  
 146      } else {
 147          
 148          $country_lang_var = 'COUNTRY_ARRAY_' . $lang;
 149  
 150          $phpwcms['country'][$country_lang_var] = array();
 151  
 152          $sql    = 'SELECT country_iso, '.$country_name.' AS country FROM '.DB_PREPEND.'phpwcms_country ORDER BY '.$country_name;
 153          $result    = _dbQuery($sql);
 154  
 155          if(isset($result[0])) {
 156      
 157              foreach($result as $row) {
 158      
 159                  $phpwcms['country'][ $country_lang_var ][ $row['country_iso'] ] = $row['country'];
 160      
 161              }
 162          }
 163      }
 164      
 165      return $phpwcms['country'][$country_lang_var];
 166  }
 167  
 168  
 169  function list_profession($c){
 170      //Create the profession list menu for forms 
 171      //with the given value selected
 172      //$c = selected value
 173      if(isEmpty($c)) $c = " n/a";
 174      $sql = mysql_query("SELECT prof_name FROM ".DB_PREPEND."phpwcms_profession ORDER BY prof_name");
 175      while($a = mysql_fetch_assoc($sql)) {
 176          if($a["prof_name"] != $c) {
 177              echo "\t\t\t<option value=\"".$a["prof_name"]."\">".trim($a["prof_name"])."</option>\n";
 178          } else {
 179              echo "\t\t\t<option value=\"".$a["prof_name"]."\" selected>".trim($a["prof_name"])."</option>\n";
 180          }        
 181      }
 182      mysql_free_result($sql);
 183  }
 184  
 185  function is_selected($c, $chkvalue, $xhtml=1, $echoit=1) {
 186      $e = '';
 187      if(strval($c) == strval($chkvalue)) {
 188          $e = (!$xhtml) ? ' selected' : ' selected="selected"' ;
 189      }
 190      if($echoit) {
 191          echo $e;
 192      } else {
 193          return $e;
 194      }
 195  }
 196  
 197  function is_checked($c, $chkvalue, $xhtml=1, $echoit=1) {
 198      $e = '';
 199      if(strval($c) == strval($chkvalue)) {
 200          $e = (!$xhtml) ? ' checked' : ' checked="checked"' ;
 201      }
 202      if($echoit) {
 203          echo $e;
 204      } else {
 205          return $e;
 206      }
 207  }
 208  
 209  function check_checkbox($c) {
 210      //Prüft, ob korrekte Werte via Checkbox übergeben wurden
 211      $c = intval($c);
 212      if($c != 0 AND $c != 1) $c = 0;
 213      return $c;
 214  }
 215  
 216  function which_ext($filename) {
 217      // return file extension
 218      return strtolower(str_replace('.', '', strrchr(trim($filename), '.')));
 219  }
 220  
 221  function cut_ext($dateiname) {
 222      //cuts extension of file
 223      $cutoff = strrpos($dateiname, '.');
 224      return ($cutoff !== false) ? substr($dateiname, 0, $cutoff) : $dateiname;
 225  }
 226  
 227  function fsize($zahl,$spacer='&nbsp;',$short=1) {
 228      //Creates Filesize-Info
 229      //number_format($_FILES["wcsfile"]["size"] / 1024, 0, ',', '.')." kB)
 230      //$short 0 = ultrashort = B, K, M, G, T
 231      //$short 1 = short = B, KB, MB, GB, TB
 232      //$short 2 = long = Byte, KiloByte, MegaByte, GigaByte, TeraByte
 233      $_unit = array(
 234          0 => array(    "B"    =>    "B",        "K"    =>    "K",        "M"    =>    "M",
 235                      "G"    =>    "G",        "T"    =>    "T"
 236                     ),
 237          1 => array(    "B"    =>    "Byte",        "K"    =>    "KB",        "M"    =>    "MB",
 238                      "G"    =>    "GB",        "T"    =>    "TB"
 239                     ),
 240          2 => array(    "B"    =>    "Byte",        "K"    =>    "KiloByte",    "M"    =>    "MegaByte",
 241                      "G"    =>    "GigaByte",    "T"    =>    "TeraByte"
 242                     ) );
 243      $zahl = intval($zahl);
 244      if($zahl < 1024) {
 245          $zahl = number_format($zahl, 0, '.', '.');
 246          $unit = "B";
 247      } elseif($zahl < 1048576) {
 248          $zahl = number_format($zahl/1024, 2, '.', '.');
 249          $unit = "K";
 250      } elseif ($zahl < 1073741824) {
 251          $zahl = number_format($zahl/1048576, 2, '.', '.');
 252          $unit = "M";
 253      } elseif ($zahl < 1099511627776) {
 254          $zahl = number_format($zahl/1073741824, 2, '.', '.');
 255          $unit = "G";
 256      } else {
 257          $zahl = number_format($zahl/1125899906842624, 2, ' ', '.');
 258          $unit = "T";
 259      }
 260  
 261      return $zahl.$spacer.$_unit[$short][$unit];
 262  }
 263  
 264  function fsizelong($zahl,$spacer='&nbsp;') {
 265      return fsize($zahl,$spacer,1);
 266  }
 267  
 268  function extimg($ext) {
 269      //get extension image
 270      $img =    array    (
 271          "exe" =>    "icon_exe.gif",        "com" =>    "icon_exe.gif",
 272          "bat" =>    "icon_exe.gif",        "pdf" =>    "icon_pdf.gif",
 273          "txt" =>    "icon_txt.gif",        "xls" =>    "icon_xls.gif",
 274          "cvs" =>    "icon_xls.gif",        "rtf" =>    "icon_txt.gif",
 275          "htm" =>    "icon_htm.gif",        "html" =>    "icon_htm.gif",
 276          "pix" =>    "icon_pix.gif",        "tif" =>    "icon_pix.gif",
 277          "jpg" =>    "icon_pix.gif",        "jpeg" =>    "icon_pix.gif",
 278          "gif" =>    "icon_pix.gif",        "png" =>    "icon_pix.gif",
 279          "psd" =>    "icon_pix.gif",        "rar" =>    "icon_rar.gif",
 280          "zip" =>    "icon_zip.gif",        "tar" =>    "icon_zip.gif",
 281          "gzip" =>    "icon_zip.gif",        "sit" =>    "icon_sit.gif",
 282          "sea" =>    "icon_sit.gif",        "doc" =>    "icon_doc.gif",
 283          "dot" =>    "icon_doc.gif",        "ai"  =>    "icon_ai.gif",
 284          "ps"  =>    "icon_ps.gif",        "eps" =>    "icon_eps.gif",
 285          "tar" =>    "icon_tar.gif",        "gz"  =>    "icon_gz.gif",
 286          "tgz" =>    "icon_gz.gif",        "aif" =>    "icon_snd.gif",
 287          "aiff" =>    "icon_snd.gif",        "mp3" =>    "icon_snd.gif",
 288          "snd" =>    "icon_snd.gif",        "wav" =>    "icon_snd.gif",
 289          "mid" =>    "icon_snd.gif",        "mov" =>    "icon_vid.gif",
 290          "avi" =>    "icon_vid.gif",        "qt"  =>    "icon_vid.gif",
 291          "mpeg" =>    "icon_vid.gif"                    
 292                  );
 293      return (isset($img[$ext])) ? $img[$ext] : "icon_generic.gif";
 294  }
 295  
 296  function randpassword($length=6) {
 297      //totally random password creation
 298      return generic_string($length);
 299  }
 300  
 301  function generic_string($length, $i=0) {
 302      $gen_string = '';
 303      $p[0] = "abcdefghijklmnopqrstuvwxyz";
 304      $p[1] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
 305      $p[2] = "1234567890";
 306      switch($i) {
 307          case 1:        $chars = $p[0].$p[2];    break;
 308          case 2:     $chars = $p[1].$p[2];    break;
 309          case 3:     $chars = $p[0].$p[1];    break;
 310          case 4:     $chars = $p[0];            break;
 311          case 5:     $chars = $p[1];            break;
 312          case 6:     $chars = $p[2];            break;
 313          default:    $chars = $p[0].$p[2].$p[1];
 314      }
 315      mt_srand((double)microtime()*1000000);
 316      $count = strlen($chars)-1;
 317      for($i = 0; $i < $length; $i++){
 318          $gen_string .= substr($chars, mt_rand(0,$count),1);
 319      }
 320      return $gen_string;
 321  }
 322  
 323  function genlogname() {
 324      $usercount = _dbQuery('SELECT COUNT(*) FROM '.DB_PREPEND."phpwcms_user WHERE usr_login LIKE 'user%'", 'COUNT');
 325      $usercount = $usercount ? $usercount+1 : 1;
 326      return 'user'.$usercount; 
 327  }
 328   
 329  function gib_part($value, $part, $separator) {
 330      //Gibt den Wert an Stelle $part von $value zurück
 331      $value_array = explode($separator, $value);
 332      return $value_array[$part];
 333  }
 334  
 335  function cut_string($string, $endchar = '&#8230;', $length = 20, $trim = 1) {
 336      // alias function for older function
 337      return getCleanSubString($string, $length, $endchar);
 338  }
 339  
 340  function which_folder_active($ist, $soll, $ac="#9BBECA", $nc="#363E57", $nclass="msgreiter") {
 341      if($ist == $soll) {
 342          echo "bgcolor='".$ac."' class='".$nclass."'";
 343      } else {
 344          echo "bgcolor='".$nc."' class='".$nclass."' ";
 345          echo "onMouseOver=\"bgColor='#FF6600'\" onMouseOut=\"bgColor='".$nc."'\"";
 346      }
 347  }
 348  
 349  function FileExtension($filename) {
 350      return substr(strrchr($filename, "."), 1, strlen(strrchr($filename, ".")));
 351  }
 352  
 353  function convert_into($extension) {
 354      //check which extension to give back
 355      $extension = strtolower($extension);
 356      $ext = 'jpg';
 357      if(IMAGICK_ON) {
 358          switch($extension) {
 359              case 'gif':    $ext = 'gif'; break;
 360              case 'png':    $ext = 'png'; break;
 361          }
 362      } else {
 363          switch($extension) {
 364              case 'gif':    $ext = (imagetypes() & IMG_GIF) ? "gif" : "png";
 365                          break;
 366              case 'png':    $ext = 'png'; break;
 367          }
 368      }
 369      return $ext;
 370  }
 371  
 372  function is_ext_true($extension) {
 373      $ext = false;
 374      if(IMAGICK_ON) {
 375          // if ImageMagick for thumbnail creation
 376          switch($extension) {
 377              case "jpg":        $ext="jpg"; break;
 378              case "jpeg":    $ext="jpg"; break;
 379              case "tif":        $ext="jpg"; break;
 380              case "tiff":    $ext="jpg"; break;
 381              case "psd":        $ext="jpg"; break;
 382              case "bmp":        $ext="jpg"; break;
 383              case "pic":        $ext="jpg"; break;
 384              case "eps":        $ext="jpg"; break;
 385              case "ps":        $ext="jpg"; break;
 386              case "ai":        $ext="jpg"; break;
 387              case "ps2":        $ext="jpg"; break;
 388              case "ps3":        $ext="jpg"; break;
 389              case "pn":        $ext="jpg"; break;
 390              case "wmf":        $ext="jpg"; break;
 391              case "gif":        $ext="gif"; break;
 392              case "png":        $ext="png"; break;
 393              case "tga":        $ext="jpg"; break;
 394              case "pdf":        $ext="jpg"; break;
 395              case "pict":    $ext="jpg"; break;
 396              case "jp2":        $ext="jpg"; break;
 397              case "jpc":        $ext="jpg"; break;
 398              case "ico":        $ext="jpg"; break;
 399              case "fax":        $ext="jpg"; break;
 400          }
 401      } else {
 402          // if GD is used
 403          switch($extension) {
 404              case "jpg":        $ext="jpg"; break;
 405              case "jpeg":    $ext="jpg"; break;
 406              case "gif":        $ext=(imagetypes() & IMG_GIF) ? "gif" : "png";
 407                              break;
 408              case "png":        $ext="png"; break;
 409          }
 410      }
 411      if($ext && !empty($GLOBALS['phpwcms']["imgext_disabled"])) {
 412          $GLOBALS['phpwcms']["imgext_disabled"] = str_replace(' ', '', $GLOBALS['phpwcms']["imgext_disabled"]);
 413          $GLOBALS['phpwcms']["imgext_disabled"] = strtolower($GLOBALS['phpwcms']["imgext_disabled"]);
 414          $disabled_ext = explode(',', $GLOBALS['phpwcms']["imgext_disabled"]);
 415          if(in_array($ext, $disabled_ext)) {
 416              $ext = false;
 417          }
 418      }
 419      return $ext;
 420  }
 421  
 422  function make_date($datestring, $dateformat = "d.m.y") {
 423      $unixtime=strtotime($datestring);
 424      return ($unixtime) ? date($dateformat, $unixtime) : $datestring;
 425  }
 426  
 427  function switch_on_off($wert) {
 428      //switches the value off->on and on->off
 429      return intval($wert) ? 0 : 1;
 430  }
 431  
 432  function online_users($dbcon, $spacer="<br />", $wrap="<span class=\"useronline\">|<span>") {
 433      $wrap = explode("|", $wrap);
 434      $x=0; $xo="";
 435      if($o = mysql_query("SELECT logged_user FROM ".DB_PREPEND."phpwcms_userlog WHERE logged_in=1", $dbcon)) {
 436          while($uo = mysql_fetch_row($o)) {
 437              $xo .= ($x) ? $spacer : "";
 438              $xo .= html_specialchars($uo[0]);
 439              $x++;
 440          }
 441          mysql_free_result($o);
 442      }
 443      return ($x) ? $wrap[0].$xo.$wrap[1] : "";
 444  }
 445  
 446  function get_filecat_childcount ($fcatid, $dbcon) {
 447      $sql = "SELECT COUNT(fkey_id) FROM ".DB_PREPEND."phpwcms_filekey WHERE fkey_deleted=0 AND fkey_cid=".intval($fcatid);
 448      if($result = mysql_query($sql, $dbcon)) {
 449          if($row = mysql_fetch_row($result)) $count = $row[0];
 450          mysql_free_result($result);
 451      }
 452      return intval($count);
 453  }
 454  
 455  
 456  function is_valid_email($email) {
 457  
 458      // Split it into sections to make life easier
 459      $email_array = explode('@', $email);
 460      $count = count($email_array);
 461      
 462      // First, we check that there's one @ symbol, and that the lengths are right
 463      if($count != 2) {
 464          return false;
 465      }
 466      if(empty($email_array[0]) || strlen($email_array[0]) > 64) {
 467          return false;
 468      }
 469      if(empty($email_array[1]) || strlen($email_array[1]) > 255) {
 470          return false;
 471      }    
 472      $local_array = explode('.', $email_array[0]);
 473      for ($i = 0; $i < count($local_array); $i++) {
 474          if (!preg_match("/^(([A-Z0-9!#$%&'*+\/\=?^_`{|}~-][A-Z0-9!#$%&'*+\/\=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$/i", $local_array[$i])) {
 475              return false;
 476          }
 477      }  
 478      if (!preg_match("/^\[?[0-9\.]+\]?$/", $email_array[1])) { // Check if domain is IP. If not, it should be valid domain name
 479          $domain_array = explode('.', $email_array[1]);
 480          $count = count($domain_array);
 481          if ($count < 2) {
 482              return false; // Not enough parts to domain
 483          }
 484          for ($i = 0; $i < $count; $i++) {
 485              if (!preg_match("/^(([A-Z0-9][A-Z0-9-]{0,61}[A-Z0-9])|([A-Z0-9]+))$/i", $domain_array[$i])) {
 486                  return false;
 487              }
 488          }
 489          
 490          // check if it is valid TLD
 491          $tld = strtolower($domain_array[ $count-1 ]);
 492          // Updated 2009-09-14
 493          $tld_all = array(
 494              'ac', 
 495              'ad', 
 496              'ae', 
 497              'aero', 
 498              'af', 
 499              'ag', 
 500              'ai', 
 501              'al', 
 502              'am', 
 503              'an', 
 504              'ao', 
 505              'aq', 
 506              'ar', 
 507              'arpa', 
 508              'as', 
 509              'asia', 
 510              'at', 
 511              'au', 
 512              'aw', 
 513              'ax', 
 514              'az', 
 515              'ba', 
 516              'bb', 
 517              'bd', 
 518              'be', 
 519              'bf', 
 520              'bg', 
 521              'bh', 
 522              'bi', 
 523              'biz', 
 524              'bj', 
 525              'bm', 
 526              'bn', 
 527              'bo', 
 528              'br', 
 529              'bs', 
 530              'bt', 
 531              'bv', 
 532              'bw', 
 533              'by', 
 534              'bz', 
 535              'ca', 
 536              'cat', 
 537              'cc', 
 538              'cd', 
 539              'cf', 
 540              'cg', 
 541              'ch', 
 542              'ci', 
 543              'ck', 
 544              'cl', 
 545              'cm', 
 546              'cn', 
 547              'co', 
 548              'com', 
 549              'coop', 
 550              'cr', 
 551              'cu', 
 552              'cv', 
 553              'cx', 
 554              'cy', 
 555              'cz', 
 556              'de', 
 557              'dj', 
 558              'dk', 
 559              'dm', 
 560              'do', 
 561              'dz', 
 562              'ec', 
 563              'edu', 
 564              'ee', 
 565              'eg', 
 566              'er', 
 567              'es', 
 568              'et', 
 569              'eu', 
 570              'fi', 
 571              'fj', 
 572              'fk', 
 573              'fm', 
 574              'fo', 
 575              'fr', 
 576              'ga', 
 577              'gb', 
 578              'gd', 
 579              'ge', 
 580              'gf', 
 581              'gg', 
 582              'gh', 
 583              'gi', 
 584              'gl', 
 585              'gm', 
 586              'gn', 
 587              'gov', 
 588              'gp', 
 589              'gq', 
 590              'gr', 
 591              'gs', 
 592              'gt', 
 593              'gu', 
 594              'gw', 
 595              'gy', 
 596              'hk', 
 597              'hm', 
 598              'hn', 
 599              'hr', 
 600              'ht', 
 601              'hu', 
 602              'id', 
 603              'ie', 
 604              'il', 
 605              'im', 
 606              'in', 
 607              'info', 
 608              'int', 
 609              'io', 
 610              'iq', 
 611              'ir', 
 612              'is', 
 613              'it', 
 614              'je', 
 615              'jm', 
 616              'jo', 
 617              'jobs', 
 618              'jp', 
 619              'ke', 
 620              'kg', 
 621              'kh', 
 622              'ki', 
 623              'km', 
 624              'kn', 
 625              'kp', 
 626              'kr', 
 627              'kw', 
 628              'ky', 
 629              'kz', 
 630              'la', 
 631              'lb', 
 632              'lc', 
 633              'li', 
 634              'lk', 
 635              'lr', 
 636              'ls', 
 637              'lt', 
 638              'lu', 
 639              'lv', 
 640              'ly', 
 641              'ma', 
 642              'mc', 
 643              'md', 
 644              'me', 
 645              'mg', 
 646              'mh', 
 647              'mil', 
 648              'mk', 
 649              'ml', 
 650              'mm', 
 651              'mn', 
 652              'mo', 
 653              'mobi', 
 654              'mp', 
 655              'mq', 
 656              'mr', 
 657              'ms', 
 658              'mt', 
 659              'mu', 
 660              'museum', 
 661              'mv', 
 662              'mw', 
 663              'mx', 
 664              'my', 
 665              'mz', 
 666              'na', 
 667              'name', 
 668              'nc', 
 669              'ne', 
 670              'net', 
 671              'nf', 
 672              'ng', 
 673              'ni', 
 674              'nl', 
 675              'no', 
 676              'np', 
 677              'nr', 
 678              'nu', 
 679              'nz', 
 680              'om', 
 681              'org', 
 682              'pa', 
 683              'pe', 
 684              'pf', 
 685              'pg', 
 686              'ph', 
 687              'pk', 
 688              'pl', 
 689              'pm', 
 690              'pn', 
 691              'pr', 
 692              'pro', 
 693              'ps', 
 694              'pt', 
 695              'pw', 
 696              'py', 
 697              'qa', 
 698              're', 
 699              'ro', 
 700              'rs', 
 701              'ru', 
 702              'rw', 
 703              'sa', 
 704              'sb', 
 705              'sc', 
 706              'sd', 
 707              'se', 
 708              'sg', 
 709              'sh', 
 710              'si', 
 711              'sj', 
 712              'sk', 
 713              'sl', 
 714              'sm', 
 715              'sn', 
 716              'so', 
 717              'sr', 
 718              'st', 
 719              'su', 
 720              'sv', 
 721              'sy', 
 722              'sz', 
 723              'tc', 
 724              'td', 
 725              'tel', 
 726              'tf', 
 727              'tg', 
 728              'th', 
 729              'tj', 
 730              'tk', 
 731              'tl', 
 732              'tm', 
 733              'tn', 
 734              'to', 
 735              'tp', 
 736              'tr', 
 737              'travel', 
 738              'tt', 
 739              'tv', 
 740              'tw', 
 741              'tz', 
 742              'ua', 
 743              'ug', 
 744              'uk', 
 745              'us', 
 746              'uy', 
 747              'uz', 
 748              'va', 
 749              'vc', 
 750              've', 
 751              'vg', 
 752              'vi', 
 753              'vn', 
 754              'vu', 
 755              'wf', 
 756              'ws', 
 757              'ye', 
 758              'yt', 
 759              'yu', 
 760              'za', 
 761              'zm', 
 762              'zw', 
 763          );
 764  
 765          if(!in_array($tld, $tld_all)) {
 766              return false;
 767          }
 768      }
 769      
 770      return true;
 771  }
 772  
 773  function MailVal($Addr, $Level, $Timeout = 15000) {
 774      // just simple alias function
 775      return is_valid_email($Addr) ? 0 : 1;
 776  }
 777  
 778  function read_textfile($filename, $mode='rb') {
 779      if(is_file($filename)) {
 780          $fd = @fopen($filename, $mode);
 781          $text = fread($fd, filesize($filename));
 782          fclose($fd);
 783          return $text;                
 784      } else {
 785          return false;
 786      }
 787  }
 788  
 789  function write_textfile($filename, $text, $mode='w+b') {
 790      if($fp = @fopen($filename, $mode)) {
 791          if(empty($text)) $text = "\n";
 792          fwrite($fp, $text);
 793          fclose($fp);
 794          return true;
 795      } else {
 796          return false;
 797      }
 798  }
 799  
 800  function check_cache($file, $cache_timeout=0) {
 801  
 802      if(is_file($file)) {    // file exists
 803  
 804          $filetime    = filemtime($file);
 805          $fileage    = time() - $filetime;
 806          
 807          if($cache_timeout > $fileage) {
 808              return 'VALID';        // file is up-to-date
 809          } else {
 810              return 'EXPIRED';    // file is too old and expired
 811          }
 812      
 813      } else {
 814  
 815          return 'MISSING';        // file not present
 816  
 817      }
 818  }
 819  
 820  //added: 09-20-2003
 821  function add_keywords_to_search ($list_of_keywords, $keywords, $spacer=" ", $start_spacer=1) {
 822      //adds available keywords to the values used by search engine in file section
 823      //returns a string
 824      $kw_string = "";
 825      if(sizeof($list_of_keywords) && $keywords) {
 826          $kw = explode(":", $keywords);
 827          if(sizeof($kw)) {
 828              foreach($kw as $value) {
 829                  list($kw_cat, $kw_id) = explode("_", $value);
 830                  $kw_id = intval($kw_id);
 831                  if($kw_string) {
 832                      $kw_string .= $spacer;
 833                  }
 834                  if(isset($list_of_keywords[$kw_id])) {
 835                      $kw_string .= $list_of_keywords[$kw_id];
 836                  }
 837                  
 838              }
 839          }
 840      }
 841      return (($start_spacer) ? $spacer : "") . $kw_string;
 842  }
 843  
 844  function get_list_of_file_keywords() {
 845      //reads possible keywords defined by admin and returns
 846      //array with values if exists
 847      //else it returns false
 848      if($result = mysql_query("SELECT * FROM ".DB_PREPEND."phpwcms_filekey")) {
 849          while($row = mysql_fetch_assoc($result)) {
 850              $file_key[intval($row["fkey_id"])] = html_specialchars($row["fkey_name"]);
 851          }
 852          mysql_free_result($result);
 853      }
 854      return (!empty($file_key) && count($file_key)) ? $file_key : false;
 855  }
 856  
 857  function get_int_or_empty($value, $emptyreturn='""') {
 858      //is used to return configuration values
 859      //that's why the default empty return value is ""
 860      $value = intval($value);
 861      return ($value) ? $value : $emptyreturn;
 862  }
 863  
 864  function get_pix_or_percent($val) {
 865      //is used to return configuration width/height values
 866      //whether based on pixel or percent
 867      //that's why the default empty return value is ""
 868      //returns a string
 869      $val = trim($val);
 870      $intval = intval($val);
 871      if(strlen($val) > 1 && strlen($val)-1 == strrpos($val, "%") && $intval) {
 872          $val = (($intval > 100) ? "100" : $intval)."%";
 873      } else {
 874          $val = ($intval) ? $intval : "";
 875      }
 876      return $val;
 877  }
 878  
 879  function check_URL($url) {
 880      //checks if URL is valid
 881      $fp = @fopen($url, "r");
 882      if(!$fp) {
 883          $url_status = 0;
 884      } else {
 885          $url_status = 1;
 886          fclose($fp);
 887      }
 888      return $url_status;
 889  }
 890  
 891  function validate_email($email) {
 892      // checks if the Email is well formatted
 893      return preg_match("/[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/", $email); 
 894  }
 895  
 896  function validate_url($url) {
 897      // checks if the URL is well formatted
 898      return preg_match("/(((ht|f)tps*:\/\/)*)((([a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3}))|(([0-9]{1,3}\.){3}([0-9]{1,3})))((\/|\?)[a-z0-9~#%&'_\+=:\?\.-]*)*)$/", $url); 
 899  }
 900  
 901  function convert_url($text) {
 902      // converts URLs in Texts to link
 903      $text = eregi_replace("((ht|f)tp(s*)://www\.|www\.)([a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})((/|\?)[a-z0-9~#%&\\/'_\+=:\?\.-]*)*)", "http\\3://www.\\4", $text); 
 904      $text = eregi_replace("((ht|f)tp(s*)://)((([a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3}))|(([0-9]{1,3}\.){3}([0-9]{1,3})))((/|\?)[a-z0-9~#%&'_\+=:\?\.-]*)*)", "\\0", $text); 
 905      return $text; 
 906  }
 907  
 908  function link_url($text) {
 909      // converts URLs in Texts to link
 910      $text = eregi_replace("((ht|f)tp(s*)://www\.|www\.)([a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})((/|\?)[a-z0-9~#%&\\/'_\+=:\?\.-]*)*)", "http\\3://www.\\4", $text); 
 911      $text = eregi_replace("((ht|f)tp(s*)://)((([a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3}))|(([0-9]{1,3}\.){3}([0-9]{1,3})))((/|\?)[a-z0-9~#%&'_\+=:\?\.-]*)*)", "<a href=\"\\0\">\\0</a>", $text); 
 912      return $text; 
 913  }
 914  
 915  function convert_email($text) {
 916      // converts Email addresses in Texts to mailto link
 917      return eregi_replace("([_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3}))", "mailto:\\0", $text); 
 918  }
 919  
 920  function link_email($text) {
 921      // converts Email addresses in Texts to mailto link
 922      return eregi_replace("([_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3}))", "<a href='mailto:\\0'>\\0</a>", $text); 
 923  }
 924  
 925  function convert_all_links($text) {
 926      // combines convertMail and convertURL
 927      $text = link_url($text);
 928      $text = link_email($text);
 929      return $text;
 930  }
 931  
 932  function convert_url_email($text) {
 933      // combines convertMail and convertURL
 934      $text = convert_email($text);
 935      $text = convert_url($text);
 936      return $text;
 937  }
 938  
 939  function validate_url_email($text) {
 940      // combined url email validation
 941      if(validate_email($text) || validate_url($text)) {
 942          return 1;
 943      } else {
 944          return 0;
 945      }
 946  }
 947  
 948  function remove_multiple_whitespaces($text) {
 949      // removes all multiple whitespaces from string
 950      return preg_replace("/(\s)+/"," ",$text);
 951  }
 952  
 953  function cut_redirect($text) {
 954      // formats the redirect string
 955      // returns only the first 2 parts if availabe like
 956      // "part1 part2 part3" -> "part1 part2" 
 957      // if only 1 part is returned trim the string
 958      return trim(preg_replace("/((.*?)\s(.*?))\s(.*)/","$1",$text));
 959  }
 960  
 961  function format_redirect($text) {
 962      // combines remove_multiple_whitespaces and cut_redirect
 963      return cut_redirect(remove_multiple_whitespaces($text));
 964  }
 965  
 966  function gd_image_check($file) {
 967      // when GD thumbnail creation is enabled
 968      // then check if image can be used by GD image function
 969      // GIF, JPG, PNG
 970      $status = 1;
 971      if(!IMAGICK_ON) {
 972          $image_check = getimagesize($file);
 973          $status = (!$image_check) ? 0 : 1;
 974          if($status && $image_check["channels"] < 4 && ($image_check[2] == 1 || $image_check[2] == 2 || $image_check[2] == 3)) {
 975              $status = 1;
 976          } else { 
 977              $status = 0;
 978          }
 979      }    
 980      return $status;
 981  }
 982  
 983  function encode($in_str, $charset) {
 984     $out_str = $in_str;
 985     if ($out_str && $charset) {
 986  
 987         // define start delimimter, end delimiter and spacer
 988         $end = "?=";
 989         $start = "=?" . $charset . "?B?";
 990         $spacer = $end . "\r\n " . $start;
 991  
 992         // determine length of encoded text within chunks
 993         // and ensure length is even
 994         $length = 75 - strlen($start) - strlen($end);
 995         $length = floor($length/2) * 2;
 996  
 997         // encode the string and split it into chunks 
 998         // with spacers after each chunk
 999         $out_str = base64_encode($out_str);
1000         $out_str = chunk_split($out_str, $length, $spacer);
1001  
1002         // remove trailing spacer and 
1003         // add start and end delimiters
1004         $spacer = preg_quote($spacer);
1005         $out_str = preg_replace("/" . $spacer . "$/", "", $out_str);
1006         $out_str = $start . $out_str . $end;
1007     }
1008     return $out_str;
1009  }
1010  
1011  function js_singlequote($t='') {
1012      // make singe quotes js compatible
1013      $t = str_replace("\\", "\\\\", $t );
1014      $t = str_replace("&#92;", "\\\\", $t );
1015      $t = str_replace("'", '&#39;', $t);
1016      //$t = str_replace("&#039;", "\\'", $t);
1017      $t = str_replace('"', '&quot;', $t );
1018      //$t = str_replace('&quot;', '\"', $t );
1019      //$t = str_replace('&#58;', ':', $t ); //send by pappnase
1020      return $t;
1021  }
1022  
1023  function get_tmpl_files($dir='', $ext='', $sort=true) {
1024      //browse a dir and return all template files
1025      $c = '\.html|\.htm|\.php|\.inc|\.tmpl'; //$c = '\.html|\.htm|\.txt|\.php|\.inc|\.tmpl';
1026      if($ext) {
1027          $ext = explode(',', $ext);
1028          if(count($ext)) {
1029              $c = '';
1030              foreach($ext as $value) {
1031                  if($c) $c .= '|';
1032                  $c .= '\.'.$value;
1033              }
1034          }
1035      }
1036      $regexp = '/('.$c.')$/';
1037      $fa = array(); //file array
1038      if(is_dir($dir)) {
1039          $ph = opendir($dir);
1040          while($pf = readdir($ph)) {
1041                 if( $pf != '.' && $pf != '..' && !is_dir($dir.'/'.$pf) && preg_match($regexp, strtolower($pf)) ) {
1042                  $fa[] = $pf; //add $pf to file array for current dir
1043              }
1044          }
1045          closedir($ph);
1046          
1047          if(count($fa) && $sort === true) {
1048              sort($fa);
1049          }
1050      }
1051      return $fa;
1052  }
1053  
1054  function get_tmpl_section($s='',$t='') {
1055      // try to return the matching section of template
1056      // within HTML comments like <!--SECTION_START//-->...<!--SECTION_END//-->
1057      return (preg_match("/<!--".$s."_START\/\/-->(.*?)<!--".$s."_END\/\/-->/si", $t, $g)) ? $g[1] : '';
1058  }
1059  
1060  function replace_tmpl_section($s='',$t='',$r='') {
1061      // try to delete the matching section of template
1062      // within HTML comments like <!--SECTION_START//-->...<!--SECTION_END//-->
1063      return preg_replace("/<!--".$s."_START\/\/-->(.*?)<!--".$s."_END\/\/-->/si", $r, $t);
1064  }
1065  
1066  // -------------------------------------------------------------
1067  
1068  function importedFile_toString($filename='') {
1069  
1070      $file = array();
1071      
1072      if(isset($_FILES[$filename]) && !$_FILES[$filename]['error']) {
1073          
1074          $file['name'] = $_FILES[$filename]['name'];
1075          $file['data'] = file_get_contents($_FILES[$filename]['tmp_name']);
1076  
1077      } else {
1078          
1079          $file = false;
1080      
1081      }
1082      
1083      return $file;
1084  }
1085  
1086  // -------------------------------------------------------------
1087  
1088  function get_order_sort($order=0, $resort=0) {
1089      // for getting right article structure sorting INT
1090      // $o[0] = $acat_order; $o[1] = $acat_ordersort;
1091      $o        = array(3);
1092      $order    = intval($order);
1093      switch($order) {
1094          case  0: $o[0] =  0; $o[1] = 0; $o[2] = ' article_sort ASC';        break;
1095          case  1: $o[0] =  0; $o[1] = 1; $o[2] = ' article_sort DESC';        break;
1096          case  2: $o[0] =  2; $o[1] = 0; $o[2] = ' article_created ASC';        break;
1097          case  3: $o[0] =  2; $o[1] = 1; $o[2] = ' article_created DESC';    break;
1098          case  4: $o[0] =  4; $o[1] = 0; $o[2] = ' article_tstamp ASC';        break;
1099          case  5: $o[0] =  4; $o[1] = 1; $o[2] = ' article_tstamp DESC';        break;
1100          case  6: $o[0] =  6; $o[1] = 0; $o[2] = ' article_begin ASC';        break;
1101          case  7: $o[0] =  6; $o[1] = 1; $o[2] = ' article_begin DESC';        break;
1102          case  8: $o[0] =  8; $o[1] = 0; $o[2] = ' article_title ASC';        break;
1103          case  9: $o[0] =  8; $o[1] = 1; $o[2] = ' article_title DESC';        break;
1104          case 10: $o[0] = 10; $o[1] = 0; $o[2] = ' article_end ASC';            break;
1105          case 11: $o[0] = 10; $o[1] = 1; $o[2] = ' article_end DESC';        break;
1106      }
1107      $o[2] = ' article_priorize DESC,'.$o[2];
1108      return $o;
1109  }
1110  
1111  // -------------------------------------------------------------
1112  
1113  function getRefererURL() {
1114      if(strtolower(substr($GLOBALS['phpwcms']['site'],0,5)) != 'https') {
1115          $url = 'http://';
1116      } else {
1117          $url = 'https://';
1118      }
1119      $url .= $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
1120      return $url;
1121  }
1122  
1123  // -------------------------------------------------------------
1124  
1125  function build_QueryString() {
1126      // used to build a query string based on given parameters
1127      // there is no limitation in length
1128      // first Parameter is the delimtere char
1129      // build_QueryString('&amp;', 'k=1', 'b=5')
1130      $numargs = func_num_args();
1131      $query = array();
1132      $delimeter = '';
1133      if ($numargs) {
1134          $delimeter = func_get_arg(0);
1135          for ($i = 1; $i < $numargs; $i++) {
1136              $query[] = func_get_arg($i);
1137          }
1138      }
1139      return implode($delimeter, $query);
1140  }
1141  
1142  // -------------------------------------------------------------
1143  
1144  function getAltTitle($string='', $altAndTitle=0, $echo=0) {
1145      $attribute = trim($string);
1146      switch(intval($altAndTitle)) {    
1147          case 0:    // alt and title attribute
1148                  $attribute = 'alt="'.$attribute.'" title="'.$attribute.'"';
1149                  break;
1150          case 1:    // alt only
1151                  $attribute = 'alt="'.$attribute.'"';
1152                  break;
1153          case 2:    // alt only
1154                  $attribute = 'title="'.$attribute.'"';
1155                  break;
1156      }
1157      if($echo != 0) {
1158          echo $attribute;
1159      } else {
1160          return $attribute;
1161      }
1162  }
1163  
1164  // -------------------------------------------------------------
1165  
1166  function sendEmail($data = array(    'recipient'=>'','toName'=>'','subject'=>'','isHTML'=>0,'html'=>'','text'=>'',
1167                                      'attach'=>array(),'from'=>'','fromName'=>'','sender'=>'','stringAttach'=>array())  ) {
1168      // used to send a standardized email message
1169      
1170      global $phpwcms;
1171      
1172      $mailInfo        = array(0 => false, 1 => '');
1173      
1174      $sendTo            = array();
1175      $from            = empty($data['from']) || !is_valid_email($data['from'])         ? $phpwcms['SMTP_FROM_EMAIL']     : $data['from'];
1176      $sender            = empty($data['sender']) || !is_valid_email($data['sender'])     ? $from                         : $data['sender'];
1177      $fromName        = empty($data['fromName'])                                        ? ''                             : cleanUpForEmailHeader($data['fromName']);
1178      $toName            = empty($data['toName'])                                        ? ''                            : cleanUpForEmailHeader($data['toName']);
1179      $subject        = empty($data['subject'])                                        ? 'Email sent by phpwcms'        : cleanUpForEmailHeader($data['subject']);
1180      
1181      if(empty($data['html'])) {
1182          $data['html']    = '';
1183          $data['isHTML']    = 0;
1184      } elseif(empty($data['isHTML'])) {
1185          $data['isHTML'] = 0;
1186      } else {
1187          $data['isHTML'] = 1;
1188      }
1189      if(empty($data['text'])) {
1190          $data['text']    = '';
1191      }
1192      
1193      if(!is_array($data['recipient'])) {
1194          $recipient = str_replace(' ', '', trim($data['recipient']));
1195          $recipient = str_replace(',', ';', $recipient);
1196          $recipient = str_replace(' ', '', $recipient);
1197          $recipient = explode(';', $recipient);        
1198      } else {
1199          $recipient = $data['recipient'];
1200      }
1201      
1202      if(is_array($recipient) && count($recipient)) {
1203          foreach($recipient as $value) {
1204              if(is_valid_email($value)) {
1205                  $sendTo[] = $value;
1206              }
1207          }
1208      }
1209      
1210      if(count($sendTo)) {
1211      
1212          include_once (PHPWCMS_ROOT.'/include/inc_ext/phpmailer/class.phpmailer.php');
1213      
1214          $mail = new PHPMailer();
1215          $mail->Mailer             = $phpwcms['SMTP_MAILER'];
1216          $mail->Host             = $phpwcms['SMTP_HOST'];
1217          $mail->Port             = $phpwcms['SMTP_PORT'];
1218          if($phpwcms['SMTP_AUTH']) {
1219              $mail->SMTPAuth     = 1;
1220              $mail->Username     = $phpwcms['SMTP_USER'];
1221              $mail->Password     = $phpwcms['SMTP_PASS'];
1222          }
1223          $mail->CharSet             = $phpwcms["charset"];
1224          
1225          $mail->IsHTML($data['isHTML']);
1226          $mail->Subject            = $data['subject'];
1227          if($data['isHTML']) {
1228              if($data['text'] != '') {
1229                  $mail->AltBody    = $data['text'];
1230              }
1231              $mail->Body         = $data['html'];
1232          } else {
1233              $mail->Body         = $data['text'];
1234          }
1235          
1236          if(!$mail->SetLanguage($phpwcms['default_lang'])) {
1237              $mail->SetLanguage('en');
1238          }
1239          
1240          $mail->From         = $from;
1241          $mail->FromName        = $fromName;
1242          $mail->Sender         = $sender;
1243  
1244          $mail->AddAddress($sendTo[0], $toName);
1245          unset($sendTo[0]);
1246          if(is_array($sendTo) && count($sendTo)) {
1247              foreach($sendTo as $value) {
1248                  $mail->AddBCC($value);
1249              }
1250          }
1251          
1252          if(isset($data['attach']) && is_array($data['attach']) && count($data['attach'])) {
1253              foreach($data['attach'] as $attach_file) {
1254                  $mail->AddAttachment($attach_file);
1255              }
1256          }
1257          
1258          if(isset($data['stringAttach']) && is_array($data['stringAttach']) && count($data['stringAttach'])) {
1259              $attach_counter = 1;
1260              foreach($data['stringAttach'] as $attach_string) {
1261                  if(is_array($attach_string) && !empty($attach_string['data'])) {
1262                      $attach_string['filename']    = empty($attach_string['filename']) ? 'attachment_'.$attach_counter : $attach_string['filename'];
1263                      $attach_string['mime']        = empty($attach_string['mime']) ? 'application/octet-stream' : $attach_string['mime'];
1264                      $attach_string['encoding']    = empty($attach_string['encoding']) ? 'base64' : $attach_string['encoding'];
1265                      $mail->AddStringAttachment($attach_string['data'], $attach_string['filename'], $attach_string['encoding'], $attach_string['mime']);
1266                      $attach_counter++;
1267                  }
1268              }
1269          }
1270      
1271          if(!$mail->Send()) {
1272              $mailInfo[0]  = false;
1273              $mailInfo[1]  = $mail->ErrorInfo;
1274          } else {
1275              $mailInfo[0]  = true;
1276          }
1277          unset($mail);
1278          
1279      } else {
1280          $mailInfo[0]  = false;
1281          $mailInfo[1]  = 0; //means no recipient
1282      }
1283  
1284      return $mailInfo;
1285  }
1286  
1287  // -------------------------------------------------------------
1288  
1289  function getFormTrackingValue() {
1290      //creates a new form tracking entry in database
1291      //returns a <input type="hidden">
1292      $ip           = getRemoteIP();
1293      $hash         = md5($ip.$GLOBALS['phpwcms']["db_pass"].date('G'));
1294      $entry_id     = time();    
1295      if(!empty($GLOBALS['phpwcms']["form_tracking"])) {
1296          $sql  = "INSERT INTO ".DB_PREPEND."phpwcms_formtracking SET ";
1297          $sql .= "formtracking_hash = '".$hash."', ";
1298          $sql .= "formtracking_ip = '".aporeplace($ip)."'";
1299          if($entry_created = mysql_query($sql, $GLOBALS['db'])) {
1300              $entry_id = mysql_insert_id($GLOBALS['db']);
1301          }
1302      }
1303      return '<input type="hidden" name="'.$hash.'" value="'.$entry_id.'" />';
1304  }
1305  
1306  function checkFormTrackingValue() {
1307      //compare given tracking value against db tracking entry
1308      $ip    = getRemoteIP();
1309      $hash1  = md5($ip.$GLOBALS['phpwcms']["db_pass"].date('G'));
1310      $hash2  = md5($ip.$GLOBALS['phpwcms']["db_pass"].date('G', time()-3600)); //max form delay of 1 hour
1311      $valid = false;
1312      if(isset($_POST[$hash1])) {
1313          // form method POST
1314          $entry_id = intval($_POST[$hash1]);
1315          $valid = true;
1316          unset($_POST[$hash1]);
1317      } elseif(isset($_POST[$hash2])) {
1318          // form method POST 1 hour ago
1319          $entry_id = intval($_POST[$hash2]);
1320          $valid = true;
1321          unset($_POST[$hash2]);
1322      } else {
1323          // hm, no hash means - ERROR
1324          $valid = false;
1325      }
1326      return $valid;
1327  }
1328  
1329  // -------------------------------------------------------------
1330  
1331  function dumpVar($var, $commented=false) {
1332      //just a simple funcction returning formatted print_r()
1333      switch($commented) {
1334          case 1:        echo "\n<!--\n";
1335                      print_r($var);
1336                      echo "\n//-->\n";
1337                      return NULL;
1338                      break;
1339          case 2:        return '<pre>'.html_entities(print_r($var, true)).'</pre>';
1340                      break;
1341          default:     echo '<pre>';
1342                      echo html_entities(print_r($var, true));
1343                      echo '</pre>';
1344                      return NULL;
1345      }
1346  }
1347  
1348  
1349  // -------------------------------------------------------------
1350  
1351  // workaround functions for PHP < 4.3
1352  
1353  if(!function_exists('file_get_contents')) {
1354  	function file_get_contents($file) {
1355          $f = fopen($file,'r');
1356          if (!$f) return '';
1357          $t = '';
1358          while ($s = fread($f,100000)) $t .= $s;
1359          fclose($f);
1360          return $t;
1361      }
1362  }
1363  
1364  if(!function_exists('html_entity_decode')) {
1365  	function html_entity_decode($string, $test='', $charset='') {
1366          $trans_tbl = get_html_translation_table(HTML_ENTITIES);
1367          $trans_tbl = array_flip($trans_tbl);
1368          return strtr($string, $trans_tbl);
1369      }
1370  }
1371  
1372  function cleanUpSpecialHtmlEntities($string='') {
1373      if(isset($GLOBALS['SPECIAL_ENTITIES_TABLES'])) {
1374          $string = str_replace($GLOBALS['SPECIAL_ENTITIES_TABLES']['latin1_encode'], $GLOBALS['SPECIAL_ENTITIES_TABLES']['latin1_decode'], $string);
1375          $string = str_replace($GLOBALS['SPECIAL_ENTITIES_TABLES']['symbol_encode'], $GLOBALS['SPECIAL_ENTITIES_TABLES']['symbol_decode'], $string);
1376          $string = str_replace($GLOBALS['SPECIAL_ENTITIES_TABLES']['specialchars_encode'], $GLOBALS['SPECIAL_ENTITIES_TABLES']['specialchars_decode'], $string);
1377      }
1378      return $string;
1379  }
1380  
1381  function encode_SpecialHtmlEntities($string='', $mode='ALL') {
1382      global $SPECIAL_ENTITIES_TABLES;
1383      switch($mode) {
1384      
1385          case 'LATIN':
1386              $string = str_replace($SPECIAL_ENTITIES_TABLES['latin1_decode'], $SPECIAL_ENTITIES_TABLES['latin1_encode'], $string);
1387              break;
1388              
1389          case 'SYMBOL':
1390              $string = str_replace($SPECIAL_ENTITIES_TABLES['symbol_decode'], $SPECIAL_ENTITIES_TABLES['symbol_encode'], $string);
1391              break;
1392              
1393          case 'LATIN SYMBOL':
1394          case 'SYMBOL LATIN':
1395              $string = str_replace($SPECIAL_ENTITIES_TABLES['latin1_decode'], $SPECIAL_ENTITIES_TABLES['latin1_encode'], $string);
1396              $string = str_replace($SPECIAL_ENTITIES_TABLES['symbol_decode'], $SPECIAL_ENTITIES_TABLES['symbol_encode'], $string);
1397              break;
1398              
1399          case 'SPECIALCHARS':
1400              $string = str_replace($SPECIAL_ENTITIES_TABLES['specialchars_decode'], $SPECIAL_ENTITIES_TABLES['specialchars_encode'], $string);
1401              break;
1402              
1403          case 'LATIN SPECIALCHARS':
1404          case 'SPECIALCHARS LATIN':
1405              $string = str_replace($SPECIAL_ENTITIES_TABLES['latin1_decode'], $SPECIAL_ENTITIES_TABLES['latin1_encode'], $string);
1406              $string = str_replace($SPECIAL_ENTITIES_TABLES['specialchars_decode'], $SPECIAL_ENTITIES_TABLES['specialchars_encode'], $string);
1407              break;
1408              
1409          case 'SYMBOL SPECIALCHARS':
1410          case 'SPECIALCHARS SYMBOL':
1411              $string = str_replace($SPECIAL_ENTITIES_TABLES['symbol_decode'], $SPECIAL_ENTITIES_TABLES['symbol_encode'], $string);
1412              $string = str_replace($SPECIAL_ENTITIES_TABLES['specialchars_decode'], $SPECIAL_ENTITIES_TABLES['specialchars_encode'], $string);
1413              break;
1414      
1415          default:
1416              $string = str_replace($SPECIAL_ENTITIES_TABLES['latin1_decode'], $SPECIAL_ENTITIES_TABLES['latin1_encode'], $string);
1417              $string = str_replace($SPECIAL_ENTITIES_TABLES['symbol_decode'], $SPECIAL_ENTITIES_TABLES['symbol_encode'], $string);
1418              $string = str_replace($SPECIAL_ENTITIES_TABLES['specialchars_decode'], $SPECIAL_ENTITIES_TABLES['specialchars_encode'], $string);
1419  
1420      }
1421      return $string;
1422  }
1423  
1424  function cleanUpFormMailerPostValue($string = '') {
1425      if(strpos("\n", $string) !== false) {
1426          return '';
1427      }
1428      $string = clean_slweg($string);
1429      $string = cleanUpSpecialHtmlEntities($string);
1430      return $string;
1431  }
1432  
1433  function cleanUpForEmailHeader($text='') {
1434      list($text) = explode("\n", $text);
1435      list($text) = explode("%0D", $text);
1436      list($text) = explode("%0d", $text);
1437      list($text) = explode("\r", $text);
1438      list($text) = explode("%0A", $text);
1439      list($text) = explode("%0a", $text);
1440      $spam        = array('/bcc:/i', '/cc:/i', '/to:/i', '/from:/i', '/mime-version:/i', '/reply-to:/i');
1441      $text         = preg_replace($spam, '', $text);
1442      return trim($text);
1443  }
1444  
1445  function getCleanSubString($cutString='', $maxLength, $moreChar='', $cutMode='char', $sanitize=NULL) {
1446      // used to cut a string by words or chars
1447      if(empty($maxLength) || $maxLength < 0) return $cutString;
1448      
1449      if($cutMode == 'word') {
1450      
1451          $words        = preg_split("/[\s]+/", $cutString, -1, PREG_SPLIT_NO_EMPTY);
1452          $cutString    = '';
1453          for($i = 0; $i < $maxLength; $i++) {
1454              if(!empty($words[$i])) {
1455                  $cutString .= $words[$i].' ';
1456              }
1457          }
1458          $cutString = trim($cutString);
1459          if(count($words) > $maxLength && $moreChar) {
1460              $cutString .= $moreChar;
1461          }
1462  
1463      } else {
1464  
1465          $curString = trim($cutString);
1466          if($curString == '') {
1467          
1468              return '';
1469          
1470          } elseif($maxLength >= (MB_SAFE ? mb_strlen($curString) : strlen($curString))) {
1471          
1472              return $curString;
1473          
1474          }
1475          
1476          preg_match_all('/&[^;]+;|./', $curString, $match);
1477          if(is_array($match[0]) && count($match[0]) > $maxLength) {
1478  
1479              $match[0]   = array_slice($match[0], 0, $maxLength);
1480              $cutString  = trim(implode('', $match[0]));
1481              $cutString .= $moreChar;
1482  
1483          }
1484      }
1485      /*
1486      if($sanitize !== NULL) {
1487          $cutString = sanitize($cutString, array(), array(), array('img', 'br', 'hr', 'input'), true);
1488      }
1489      */
1490      return $cutString;
1491  }
1492  
1493  function headerAvoidPageCaching() {
1494      header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
1495      header("Last-Modified: " . gmdate("D, d M Y H:i:s") ." GMT");
1496      header("Cache-Control: no-cache");
1497      header("Pragma: no-cache");
1498      header("Cache-Control: post-check=0, pre-check=0", FALSE);
1499  }
1500  
1501  function getFileInformation($fileID) {
1502      
1503      if(empty($fileID)) return false;
1504  
1505      $f = '';
1506      if(is_array($fileID)) {
1507      
1508          if(count($fileID) == 0) return false;
1509          
1510          $x        = 0;
1511          foreach($fileID as $value) {
1512              if($x) {
1513                  $f .= ' OR ';
1514              }
1515              $f .= 'f_id='.intval($value);
1516              $x++;
1517          }
1518  
1519  
1520      } elseif(intval($fileID)) {
1521      
1522          $f = 'f_id='.intval($fileID);
1523      
1524      } else {
1525      
1526          return false;
1527      
1528      }
1529      
1530      $sql = "SELECT * FROM ".DB_PREPEND."phpwcms_file WHERE f_public=1 AND f_aktiv=1 AND f_kid=1 AND f_trash=0 AND (".$f.")";
1531      
1532      return _dbQuery($sql);
1533      
1534  }
1535  
1536  function getJavaScriptSourceLink($src, $prefix='  ') {
1537      return ($src) ? $prefix.'<script type="text/javascript" src="'.$src.'"></script>' : '';
1538  }
1539  
1540  function convertStringToArray($string='', $seperator=',', $mode='UNIQUE', $rmvDblWSp=true) {
1541      // clean up a seperator seperated string and return as array
1542      if(trim($string) == '') return array();
1543      // replace all duplicate white chars by single space
1544      if($rmvDblWSp) $string = preg_replace('/\s\s+/', ' ', $string);
1545      $string = explode($seperator, $string);
1546      $string = array_map('trim', $string);
1547      $string = array_diff($string, array('',NULL,false));
1548      if($mode=='UNIQUE') {
1549          $string = array_unique($string);
1550      }
1551      return $string;
1552  }
1553  
1554  function decode_entities($text) {
1555      $text = @html_entity_decode($text, ENT_QUOTES, PHPWCMS_CHARSET);
1556      if(strpos($text, '&') === false) return $text;
1557      $text = preg_replace_callback('/&#x([0-9a-f]+);/i', 'convertHexNumericToChar', $text);
1558      $text = preg_replace_callback('/&#([0-9]+);/', 'convertNumericToChar', $text);
1559      return $text;
1560  }
1561  function convertHexNumericToChar($matches) {
1562      return convertDecChar(hexdec($matches[1]));
1563  }
1564  function convertNumericToChar($matches) {
1565      return convertDecChar($matches[1]);
1566  }
1567  function convertDecChar($decChar) {
1568      if($decChar < 128) {
1569          return chr($decChar);
1570      } elseif($decChar < 2048) {
1571          return chr(($decChar>>6)+192).chr(($decChar&63)+128);
1572      } elseif($decChar < 65536) {
1573          return chr(($decChar>>12)+224).chr((($decChar>>6)&63)+128).chr(($decChar&63)+128);
1574      } elseif($decChar < 2097152) {
1575          return chr($decChar>>18+240).chr((($decChar>>12)&63)+128).chr(($decChar>>6)&63+128).chr($decChar&63+128);
1576      }
1577      return $decChar;
1578  }
1579  
1580  function is_html($string='') {
1581      $length_1 = strlen($string);
1582      $length_2 = strlen(strip_tags($string));
1583      if($length_1 != $length_2) {
1584          return true;
1585      }
1586      $length_2 = strlen(decode_entities($string));
1587      if($length_1 != $length_2) {
1588          return true;
1589      }    
1590      return false;
1591  }
1592  
1593  function stripped_cache_content($page='') {
1594      // clean up html page
1595      $page = preg_replace('@<script[^>]*?>.*?</script>@si', '', $page);
1596      $page = str_replace('><', '> <', $page);
1597      $page = strip_tags($page);
1598      $page = decode_entities($page);
1599      $page = preg_replace('/\s+/s', ' ', $page);
1600      return $page;
1601  }
1602  
1603  function optimizeForSearch() {
1604      // used to build a string optimized for search
1605      $numargs    = func_num_args();
1606      $text        = '';
1607      if($numargs) {
1608          for ($i = 0; $i < $numargs; $i++) {
1609              $text .= ' ' . func_get_arg($i);
1610          }
1611          
1612          $text    = stripped_cache_content($text);
1613          $text    = cleanUpSpecialHtmlEntities($text);
1614          $text    = decode_entities($text);
1615          $text    = str_replace(array('!', '"', "'", '.', '#', ';', '~', '+', '*', '%', '&', '$', '§', ':', '@', ',', '|'), ' ', $text);
1616          $text    = preg_replace('/\[.*?\]/', '', $text);
1617          $text    = preg_replace('/\{.*?\}/', '', $text);
1618          $text    = strtoupper($text);
1619          $text    = implode(' ', convertStringToArray($text, ' ', 'UNIQUE', false) );
1620          
1621      }
1622      return $text;
1623  }
1624  
1625  function return_bytes_shorten($val, $round=2, $return_bytes=0) {
1626      $last = strtolower($val{strlen(trim($val))-1});
1627      if(empty($return_bytes)) {
1628          $space    = '';
1629          $byte    = '';
1630      } else {
1631          $space    = $return_bytes;
1632          $byte    = 'B';
1633      }
1634      if($last == 'k' || $last == 'm' || $last == 'g' || $last == 't') {
1635          $val = trim($val);
1636          if($byte) $val .= $space.'Byte';
1637          return $val;
1638      }
1639      $val = ceil($val);
1640      if($val >= (1024 * 1024 * 1024 * 1024)) {
1641          //T
1642          $val  = round($val / (1024 * 1024 * 1024 * 1024), $round);
1643          $val .= $space.'T'.$byte;
1644      } elseif($val >= (1024 * 1024 * 1024)) {
1645          //G
1646          $val  = round($val / (1024 * 1024 * 1024), $round);
1647          $val .= $space.'G'.$byte;
1648      } elseif($val >= (1024 * 1024)) {
1649          //M
1650          $val  = round($val / (1024 * 1024), $round);
1651          $val .= $space.'M'.$byte;
1652      } elseif($val >= 1024) {
1653          //K
1654          $val  = round($val / 1024, $round);
1655          $val .= $space.'K'.$byte;
1656      } elseif($val < 1024) {
1657          //Byte but as 0.xxx KB
1658          $val  = round($val / 1024, $round+1);
1659          $val .= $space.'K'.$byte;
1660      }
1661      return $val;
1662  }
1663  
1664  function return_bytes($val) {
1665      // taken from: http://de3.php.net/manual/en/function.ini-get.php
1666      $val    = trim($val);
1667      $last    = strtolower($val{strlen($val)-1});
1668      $val    = floatval($val);
1669      switch($last) {
1670          case 't':    $val *= 1024;
1671          case 'g':    $val *= 1024;
1672          case 'm':    $val *= 1024;
1673          case 'k':    $val *= 1024;
1674     }
1675     return ceil($val);
1676  }
1677  
1678  function return_upload_errormsg($value) {
1679      $err = '';
1680      switch ($value) {
1681          case 0:
1682              break;
1683          case 1:
1684              $err = "The uploaded file exceeds the upload_max_filesize directive (".@ini_get("upload_max_filesize").") in php.ini.";
1685              break;
1686          case 2:
1687              $err = "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.";
1688              break;
1689          case 3:
1690              $err = "The uploaded file was only partially uploaded.";
1691              break;
1692          case 4:
1693              $err = "No file was uploaded.";
1694              break;
1695          case 6:
1696              $err = "Missing a temporary folder.";
1697              break;
1698          case 7:
1699              $err = "Failed to write file to disk";
1700              break;
1701          default:
1702              $err = "Unknown file upload error";
1703      }
1704      return $err;
1705  }
1706  
1707  function csvFileToArray($csvfile, $delimiter=';', $heading=false, $enclosure='"', $linelength=1000) {
1708      //import CSV file and convert to array
1709      
1710      if(!is_file($csvfile)) return false;
1711      
1712      $first    = 0;
1713      $datas    = array();
1714      
1715      $phpver    = version_compare('4.3.0', phpversion(), '<');
1716      if($phpver) {
1717          $oldini = ini_get('auto_detect_line_endings');
1718          @ini_set('auto_detect_line_endings', '1');
1719      }
1720      
1721      $handle    = fopen($csvfile, 'rb');
1722  
1723      while( ($data = fgetcsv($handle, $linelength, $delimiter, $enclosure)) !== false ) {
1724  
1725          // continue in case there is header row
1726          if($heading && !$first) {
1727              foreach($data as $key => $value) {
1728                  $value = trim($value);
1729                  $datas[0][$key] = $value ? $value : 'Column'.$key;
1730              }
1731              $first++;
1732              continue;
1733          }
1734          if(trim(implode('', $data)) == '') {
1735              continue;
1736          }
1737          $datas[$first] = $data;            
1738          $first++;
1739  
1740      }
1741  
1742      fclose($handle);
1743      
1744      if ($phpver) {
1745          @ini_set('auto_detect_line_endings', $oldini);
1746      }
1747      
1748      return $datas;
1749  }
1750  
1751  function shortHash($string='', $_Hash_function='md5') {
1752  
1753      return rtrim( base64_encode( pack('H*', $_Hash_function( $string ) ) ), '=' );
1754  
1755  }
1756  
1757  function replaceGlobalRT($string='') {
1758      $string = str_replace(array('{SITE}', '{PHPWCMS_URL}'), PHPWCMS_URL, $string);
1759      $string = str_replace('{PHPWCMS_TEMPLATE}', TEMPLATE_PATH, $string);
1760      $string = str_replace('{IP}', getRemoteIP(), $string);
1761      //$string = preg_replace_callback('/\{(DATE|GMDATE):(.*?)\}/', 'formatRTDate', $string);
1762      $string = renderRTDate($string);
1763      return $string;
1764  }
1765  function renderRTDate($string='') {
1766      return preg_replace_callback('/\{(DATE|GMDATE):(.*?)\}/', 'formatRTDate', $string);
1767  }
1768  function formatRTDate($matches) {
1769      // very cool function to render date or gmdate
1770      // - {DATE:DATE_FORMAT}, {GMDATE:DATE_FORMAT},
1771      // - {DATE:DATE_FORMAT SET:TIMESTAMP}, {GMDATE:DATE_FORMAT SET:TIMESTAMP}
1772      $type = strtolower($matches[1]);
1773      $matches = explode(' SET:', $matches[2]);
1774      if(empty($matches[1])) {
1775          return $type($matches[0]);
1776      }
1777      $matches[1] = trim($matches[1]);
1778      if(is_numeric($matches[1])) {
1779          $matches[1] = intval($matches[1]);
1780          return $type($matches[0], $matches[1]);
1781      }
1782      return $type($matches[0], strtotime($matches[1]));
1783  }
1784  
1785  function makeCharsetConversion($string='', $in_charset='utf-8', $out_charset='utf-8', $entityEncode=false) {
1786  
1787      global $phpwcms;
1788  
1789      $in_charset        = strtolower($in_charset);
1790      $out_charset    = strtolower($out_charset);
1791      if(empty($string) || $in_charset == $out_charset || empty($in_charset) || empty($out_charset)) {
1792          return $string;
1793      }
1794      $phpCharsetSuppport = returnCorrectCharset($in_charset);
1795      if($phpCharsetSuppport) {
1796          $string = doHtmlEntityPHPCleanUp($string, $phpCharsetSuppport);
1797      }
1798  
1799      if($entityEncode) {
1800          $convertInOut = $in_charset.$out_charset.'EntitiesOn';
1801          $entityEncode = true;
1802      } else {
1803          $convertInOut = $in_charset.$out_charset.'EntitiesOff';
1804          $entityEncode = false;
1805      }
1806      
1807      if(!isset($phpwcms['convert_charsets'])) {
1808          $phpwcms['convert_charsets'] = array();
1809      }
1810      if(!isset($phpwcms['convert_charsets'][$convertInOut])) {
1811          require_once  (PHPWCMS_ROOT.'/include/inc_ext/ConvertCharset/ConvertCharset.class.php');
1812          $phpwcms['convert_charsets'][$convertInOut] = new ConvertCharset($in_charset, $out_charset, $entityEncode);
1813      }
1814      
1815      $NewEncoding =& $phpwcms['convert_charsets'][$convertInOut];
1816      return $NewEncoding->Convert($string);
1817  
1818  }
1819  
1820  function doHtmlEntityPHPCleanUp($string, $charset) {
1821  
1822      $string = html_entities($string);
1823      return decode_entities($string);
1824  
1825  }
1826  
1827  function returnCorrectCharset($in_charset='') {
1828  
1829      $in_charset = strtolower($in_charset);
1830      switch($in_charset) {
1831      
1832          case 'iso-8859-1':
1833          case 'iso8859-1':        $in_charset = 'iso-8859-1';
1834                                  break;
1835                                  
1836          case 'iso-8859-15':
1837          case 'iso8859-15':        $in_charset = 'iso-8859-15';
1838                                  break;
1839                                  
1840          case 'utf-8':            $in_charset = 'utf-8';
1841                                  break;
1842          
1843          case 'cp866':
1844          case 'ibm866':
1845          case '866':                $in_charset = version_compare(phpversion(), '4.3.2', '<') ? false : 'cp866';
1846                                  break;
1847          
1848          case 'cp1251':
1849          case 'windows-1251':
1850          case 'win-1251':
1851          case '1251':            $in_charset = version_compare(phpversion(), '4.3.2', '<') ? false : 'windows-1251';
1852                                  break;
1853              
1854          case 'cp1252':
1855          case 'windows-1252':
1856          case 'win-1252':
1857          case '1252':            $in_charset = 'windows-1252';
1858                                  break;
1859              
1860          case 'koi8-r':
1861          case 'koi8-ru':
1862          case 'koi8r':            $in_charset = version_compare(phpversion(), '4.3.2', '<') ? false : 'koi8-r';
1863                                  break;
1864                                  
1865          case 'big5':
1866          case '950':                $in_charset = 'big5';
1867                                  break;
1868                                  
1869          case 'gb2312':
1870          case '936':                $in_charset = 'gb2312';
1871                                  break;
1872                                  
1873          case 'big5-hkscs':        $in_charset = 'big5-hkscs';
1874                                  break;
1875                                  
1876          case 'shift_jis':
1877          case 'sjis':
1878          case '932':                $in_charset = 'shift_jis';
1879                                  break;
1880                                  
1881          case 'euc-jp':
1882          case 'eucjp':            $in_charset = 'euc-jp';
1883                                  break;
1884          
1885          default:                $in_charset = false;
1886      
1887      }
1888      
1889      return $in_charset;
1890  
1891  }
1892  
1893  function returnSubdirListAsArray($dir='') {
1894      // browse a given path and return all sub directories
1895      if(empty($dir) || !is_dir($dir)) {
1896          return false;
1897      }
1898      $subdir = array();
1899      $ph = opendir($dir);
1900      while($pf = readdir($ph)) {
1901          if(is_dir($dir.'/'.$pf) && strpos($pf, '.') !== 0) { //$pf != '.' && $pf != '..' && 
1902              $subdir[] = $pf;
1903          }
1904      }
1905      closedir($ph);
1906      return $subdir;
1907  }
1908  
1909  
1910  function returnFileListAsArray($dir='', $extfilter='') {
1911      // browse a given path and return all contained files
1912      if(empty($dir) || !is_dir($dir)) {
1913          return false;
1914      }
1915      
1916      $files        = array();
1917      $ph            = opendir($dir);
1918      $extfilter    = strtolower(trim($extfilter));
1919      $extfilter    = $extfilter ? convertStringToArray($extfilter) : array();
1920      $dofilter    = count($extfilter) ? true : false;
1921      
1922      while($pf = readdir($ph)) {
1923          if(is_file($dir.'/'.$pf) && strpos($pf, '.') !== 0) { //$pf != '.' && $pf != '..' &&
1924              $ext = which_ext($pf);
1925              if($dofilter) {
1926                  if(!in_array($ext, $extfilter)) {
1927                      continue;
1928                  }
1929              }
1930              $files[$pf] = array(    'filename'    => $pf,
1931                                      'filesize'    => filesize($dir.'/'.$pf), 
1932                                      'filetime'    => filemtime($dir.'/'.$pf),
1933                                      'ext'        => $ext
1934                                  );
1935          }
1936      }
1937      closedir($ph);
1938      return $files;
1939  }
1940  
1941  function parse_ini_str($Str, $ProcessSections=true, $SplitInNameValue=false) {
1942      /*
1943      for parsing a string formatted like INI file
1944      [Files]
1945      x=File1
1946      y=File2
1947      */
1948      $Section = NULL;
1949      $Data = array();
1950      if ($Temp = strtok($Str,"\r\n")) {
1951          do {
1952              switch ($Temp{0}) {
1953                  
1954                  case ';':
1955                  
1956                  case '#':    break;
1957                  
1958                  case '[':    if (!$ProcessSections) break;
1959                              $Pos = strpos($Temp,'[');
1960                              $Section = substr($Temp,$Pos+1,strpos($Temp,']',$Pos)-1);
1961                              if($Section) $Data[$Section] = array();
1962                              break;
1963                  
1964                  default:    $Pos = strpos($Temp,'=');
1965                              if ($Pos === FALSE) break;
1966                              if(!$SplitInNameValue) {
1967                                  $key = trim(substr($Temp,0,$Pos));
1968                                  $val = trim(substr($Temp,$Pos+1),' "');
1969                                  if ($ProcessSections && $Section) {
1970                                      $Data[$Section][$key] = $val;
1971                                  } else {
1972                                      $Data[$key] = $val;
1973                                  }
1974                              } else {
1975                                  $Value = array();
1976                                  $Value["NAME"] = trim(substr($Temp,0,$Pos));
1977                                  $Value["VALUE"] = trim(substr($Temp,$Pos+1),' "');
1978                                  if ($ProcessSections && $Section) {
1979                                      $Data[$Section][] = $Value;
1980                                  } else {
1981                                      $Data[] = $Value;
1982                                  }
1983                              }
1984                              break;
1985              }
1986          } while ($Temp = strtok("\r\n"));
1987      }
1988      return $Data;
1989  }
1990  
1991  function getCookieDomain() {
1992      $domain = parse_url(PHPWCMS_URL);
1993      $domain = strtolower($domain['host']);
1994      if(strpos($domain, 'www') === 0) {
1995          $domain = substr($domain, 3);
1996      }
1997      return $domain;
1998  }
1999  
2000  function _mkdir($target) {
2001      // taken from WordPress
2002      if (file_exists($target)) {    // from php.net/mkdir user contributed notes
2003          return (!@is_dir($target)) ? false : true;
2004      }
2005      umask(0);
2006      if(@mkdir($target)) {    // Attempting to create the directory may clutter up our display.
2007          $stat = @stat(dirname($target));
2008          $dir_perms = $stat['mode'] & 0007777;  // Get the permission bits.
2009          @chmod($target, $dir_perms);
2010          return true;
2011      } elseif(is_dir(dirname($target)))    {
2012          return false;
2013      }
2014      if (_mkdir(dirname($target))) {    // If the above failed, attempt to create the parent node, then try again.
2015          return _mkdir($target);
2016      }
2017      return false;
2018  }
2019  
2020  function saveUploadedFile($file, $target, $exttype='', $imgtype='', $rename=0, $maxsize=0) {
2021      // imgtype can be all exif_imagetype supported by your PHP install
2022      // see http://www.php.net/exif_imagetype
2023      $file_status = array(
2024          'status'    => false,     'error'        => '',        'name'        => '',
2025          'tmp_name'    => '',        'size'        => 0,        'path'        => '',
2026          'ext'        => '',        'rename'    => '',        'maxsize'    => intval($maxsize),
2027          'error_num'    => 0,        'type'        => '' );
2028          
2029      if(!isset($_FILES[$file]) || !is_uploaded_file($_FILES[$file]['tmp_name'])) {
2030          $file_status['error'] = 'Upload not defined';
2031          return $file_status;
2032      }
2033  
2034      $file_status['name']        = trim($_FILES[$file]['name']);
2035      $file_status['ext']            = which_ext($file_status['name']);
2036      $file_status['tmp_name']    = $_FILES[$file]['tmp_name'];
2037      $file_status['size']        = $_FILES[$file]['size'];
2038      $file_status['type']        = empty($_FILES[$file]['type']) ? '' : $_FILES[$file]['type'];
2039      $file_status['path']        = $target;
2040      $file_status['rename']        = $file_status['name'];
2041      $file_status['maxsize']        = empty($file_status['maxsize']) ? $GLOBALS['phpwcms']['file_maxsize'] : $file_status['maxsize'];
2042      
2043      if(intval($file_status['size']) > $file_status['maxsize']) {
2044          $file_status['error'] = 'File is too large';
2045          $file_status['error_num'] = 400;
2046          return $file_status;
2047      }
2048  
2049      if(empty($target)) {
2050          $file_status['error'] = 'Target directory not defined';
2051          $file_status['error_num'] = 412;
2052          return $file_status;
2053      }
2054      if(!@_mkdir($target)) {
2055          $file_status['error'] = 'The target directory "'.$target.'" can not be found or generated';
2056          $file_status['error_num'] = 412;
2057          return $file_status;
2058      }
2059      if($_FILES[$file]['error']) {
2060          $file_status['error'] = $_FILES[$file]['error'];
2061          $file_status['error_num'] = 409;
2062          return $file_status;
2063      }
2064      
2065      if($imgtype) {
2066          $imgtype = convertStringToArray(strtolower($imgtype));
2067          
2068          if(count($imgtype)) {
2069              
2070              $data = @getimagesize($_FILES[$file]['tmp_name']);
2071              
2072              $exif_imagetype = array(
2073                      1=>'gif',    2=>'jpeg',    2=>'jpg',    3=>'png',    4=>'swf',    5=>'psd',
2074                      6=>'bmp',    7=>'tif',    8=>'tiff',    9=>'jpc',    10=>'jp2',    11=>'jpx',
2075                      12=>'jb2',    13=>'swc',    14=>'iff',    15=>'wbmp',    16=>'xbm'  );
2076              
2077              if(!$data && !$exttype) {
2078                  
2079                  $file_status['error']  = 'Format'.($file_status['ext'] ? ' *.'.$file_status['ext'] : '').' not supported (';
2080                  $allowed = array();
2081                  foreach($imgtype as $value) {
2082                      $allowed[] = '*.'.$exif_imagetype[$value];
2083                  }
2084                  $file_status['error'] .= implode(', ', $allowed).')';
2085                  $file_status['error_num'] = 415;
2086                  @unlink($_FILES[$file]['tmp_name']);
2087                  return $file_status;
2088              
2089              } elseif($data) {
2090              
2091                  if(empty($exif_imagetype[$data[2]]) || !in_array($data[2], $imgtype)) {
2092                      $file_status['error'] = 'File type ('.$data[2].') is not supported for this upload ('.implode(', ', $imgtype).' only)';
2093                      $file_status['error_num'] = 415;
2094                      @unlink($_FILES[$file]['tmp_name']);
2095                      return $file_status;
2096                  }
2097                  
2098                  $file_status['image'] = $data;
2099                  $exttype = '';
2100  
2101              }
2102          }
2103      }
2104  
2105      if($exttype) {
2106          $exttype = convertStringToArray(strtolower($exttype));
2107          if(!in_array($file_status['ext'], $exttype)) {
2108              $file_status['error'] = 'File type *.'.$file_status['ext'].' is not supported for this upload (*.'.implode(', *.', $exttype).' only)';
2109              $file_status['error_num'] = 415;
2110              @unlink($_FILES[$file]['tmp_name']);
2111              return $file_status;
2112          }        
2113      }
2114      if(!is_writable($target)) {
2115          $file_status['error'] = 'Target directory <b>'.str_replace(PHPWCMS_ROOT, '', $target).'</b> is not writable';
2116          $file_status['error_num'] = 412;
2117          @unlink($_FILES[$file]['tmp_name']);
2118          return $file_status;    
2119      }    
2120      $rename    = convertStringToArray($rename);
2121      if(count($rename)) {
2122      
2123          $_temp_name    = cut_ext($file_status['rename']);
2124  
2125          foreach($rename as $value) {
2126              switch($value) {
2127                  case 1:        $_temp_name = str_replace(array(':','/',"\\",' '), array('-','-','-','_'), remove_accents($_temp_name) );
2128                              $_temp_name = preg_replace('/[^0-9a-z_\-\.]/i', '', $_temp_name);
2129                              break;
2130                  case 2:        $_temp_name = time().'_'.$_temp_name;
2131                              break;
2132                  case 3:        $_temp_name = date('Ymd-His').'_'.$_temp_name;
2133                              break;
2134                  case 4:        $_temp_name = date('Ymd').'_'.$_temp_name;
2135                              break;
2136                  case 5:        $_temp_name = generic_string(6).'_'.$_temp_name;
2137                              break;
2138                  case 6:        $_temp_name = md5( $_temp_name . ( $file_status['ext'] ? '.' . $file_status['ext'] : '' ) );
2139                              break;
2140                  case 7:        $_temp_name = shortHash( $_temp_name . ( $file_status['ext'] ? '.' . $file_status['ext'] : '' ) );
2141                              break;
2142              }
2143          }
2144          
2145          $file_status['rename'] = $_temp_name . ( $file_status['ext'] ? '.' . $file_status['ext'] : '' );
2146          
2147      }
2148      @umask(0);
2149      if(!@move_uploaded_file($_FILES[$file]['tmp_name'], $target.$file_status['rename'])) {
2150          if(!copy($_FILES[$file]['tmp_name'], $target.$file_status['rename'])) {
2151              $file_status['error'] = 'Saving uploaded file <b>'.html_entities($file_status['name']).'</b> to <b>'.html_entities(str_replace(PHPWCMS_ROOT, '', $target.$file_status['rename'])).'</b> failed';
2152              $file_status['error_num'] = 412;
2153              @unlink($_FILES[$file]['tmp_name']);
2154              return $file_status;
2155          }
2156      }
2157      @chmod($target.$file_status['rename'], 0644);
2158      
2159      $file_status['status']    = true;
2160      return $file_status;
2161      
2162  }
2163  
2164  function get_alnum_dashes($string, $remove_accents = false, $replace_space='-') {
2165      if($remove_accents) {
2166          $string = remove_accents($string);
2167      }
2168      $string = str_replace(' ', $replace_space, $string);
2169      return preg_replace('/[^a-z0-9\-_]/i', '', $string);
2170  }
2171  
2172  // Thanks to: http://quickwired.com/smallprojects/php_xss_filter_function.php
2173  function xss_clean($val) {
2174      // remove all non-printable characters. CR(0a) and LF(0b) and TAB(9) are allowed
2175      // this prevents some character re-spacing such as <java\0script>
2176      // note that you have to handle splits with \n, \r, and \t later since they *are* allowed in some inputs
2177      $val = preg_replace('/([\x00-\x08][\x0b-\x0c][\x0e-\x20])/', '', $val);
2178      
2179      // straight replacements, the user should never need these since they're normal characters
2180      // this prevents like <IMG SRC=&#X40&#X61&#X76&#X61&#X73&#X63&#X72&#X69&#X70&#X74&#X3A&#X61&#X6C&#X65&#X72&#X74&#X28&#X27&#X58&#X53&#X53&#X27&#X29>
2181      $search = 'abcdefghijklmnopqrstuvwxyz';
2182      $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2183      $search .= '1234567890!@#$%^&*()';
2184      $search .= '~`";:?+/={}[]-_|\'\\';
2185      for ($i = 0; $i < strlen($search); $i++) {
2186          // ;? matches the ;, which is optional
2187          // 0{0,7} matches any padded zeros, which are optional and go up to 8 chars
2188          
2189          // &#x0040 @ search for the hex values
2190          $val = preg_replace('/(&#[x|X]0{0,8}'.dechex(ord($search[$i])).';?)/i', $search[$i], $val); // with a ;
2191          // &#00064 @ 0{0,7} matches '0' zero to seven times
2192          $val = preg_replace('/(&#0{0,8}'.ord($search[$i]).';?)/', $search[$i], $val); // with a ;
2193      }
2194      
2195      // now the only remaining whitespace attacks are \t, \n, and \r
2196      $ra1 = array(    'javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'style', 
2197                      'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base'
2198                  );
2199      $ra2 = array(    'onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut',
2200                      'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 
2201                      'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 
2202                      'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 
2203                      'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 
2204                      'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 
2205                      'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 
2206                      'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 
2207                      'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 
2208                      'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload'
2209                  );
2210      $ra = array_merge($ra1, $ra2);
2211      
2212      $found = true; // keep replacing as long as the previous round replaced something
2213      while ($found == true) {
2214          $val_before = $val;
2215          for ($i = 0; $i < count($ra); $i++) {
2216              $pattern = '/';
2217              for ($j = 0; $j < strlen($ra[$i]); $j++) {
2218                  if ($j > 0) {
2219                      $pattern .= '(';
2220                      $pattern .= '(&#[x|X]0{0,8}([9][a][b]);?)?';
2221                      $pattern .= '|(&#0{0,8}([9][10][13]);?)?';
2222                      $pattern .= ')?';
2223                  }
2224                  $pattern .= $ra[$i][$j];
2225              }
2226              $pattern .= '/i';
2227              $replacement = substr($ra[$i], 0, 2).'<x>'.substr($ra[$i], 2); // add in <> to nerf the tag
2228              $val = preg_replace($pattern, $replacement, $val); // filter out the hex tags
2229              if ($val_before == $val) {
2230                  // no replacements were made, so exit the loop
2231                  $found = false;
2232              }
2233          }
2234      }
2235      return $val;
2236  }
2237  
2238  function sanitize_multiple_emails($string) {
2239      $string = preg_replace('/\s|\,]/', ';', $string);
2240      $string = convertStringToArray($string, ';');
2241      $string = implode(';', $string);
2242      return $string;
2243  }
2244  
2245  function checkLogin($mode='REDIRECT') {
2246  
2247      $sql  = "UPDATE ".DB_PREPEND."phpwcms_userlog SET ";
2248      $sql .= "logged_in = 0, logged_change = '".time()."' ";
2249      $sql .= "WHERE logged_in = 1 AND ( ".time()." - logged_change ) > ".intval($GLOBALS['phpwcms']["max_time"]);
2250      _dbQuery($sql, 'UPDATE');
2251      
2252      if(!empty($_SESSION["wcs_user"])) {
2253          $sql  = "SELECT COUNT(*) FROM ".DB_PREPEND."phpwcms_userlog ";
2254          $sql .= "WHERE logged_user='".aporeplace($_SESSION["wcs_user"])."' AND ";
2255          $sql .= "logged_in=1";
2256          if(!empty($phpwcms['Login_IPcheck'])) {
2257              $sql .= " AND logged_ip='".aporeplace(getRemoteIP())."'";
2258          }
2259          
2260          $check = _dbCount($sql);
2261          
2262          if($check == 0) {
2263              unset($_SESSION["wcs_user"]);
2264          } else {
2265              $sql  = "UPDATE ".DB_PREPEND."phpwcms_userlog SET ";
2266              $sql .= "logged_change=".time()." WHERE ";
2267              $sql .= "logged_user='".aporeplace($_SESSION["wcs_user"])."' AND logged_in=1";
2268              _dbQuery($sql, 'UPDATE');
2269          }
2270      }
2271      if(empty($_SESSION["wcs_user"])) {
2272          @session_destroy();
2273          $ref_url = '';
2274          if(!empty($_SERVER['QUERY_STRING'])) {
2275              $ref_url = '?ref='.rawurlencode(PHPWCMS_URL.'phpwcms.php?'.xss_clean($_SERVER['QUERY_STRING']));
2276          }
2277          if($mode == 'REDIRECT') {
2278              
2279              // check again if user was logged in and this is a valid redirect request
2280              $sql  = 'SELECT COUNT(*)  FROM '.DB_PREPEND.'phpwcms_userlog WHERE ';
2281              $sql .= "logged_ip='".aporeplace(getRemoteIP())."' AND ";
2282              $sql .= '( '.time().' - logged_change ) < 3600';
2283              $ref_url    = _dbCount($sql) > 0 ? get_login_file().$ref_url : '';
2284              
2285              headerRedirect(PHPWCMS_URL . $ref_url);
2286          
2287          } else {
2288              return false;
2289          }
2290      }
2291  
2292      return true;
2293  }
2294  
2295  /**
2296   * Convert 2 to x line breaks of plain text into correct <p> and <br>
2297   */
2298  function plaintext_htmlencode($text='', $encode_function='html_specialchars', $render_bbcode=true) {
2299      $text = trim($text);
2300      if($text) {
2301          $text = '[p]' . preg_replace('/\s{0,}\n\s{0,}\n\s{0,}/s', '[/p][p]', $text) . '[/p]';
2302          $text = preg_replace('/\s{0,}\n\s{0,}/s', '[br]', $text);
2303          $text = $encode_function($text);
2304          $text = str_replace(array('[/p][p]', '[p]', '[/p]', '[br]'), array("</p>\n<p>", '<p>', '</p>', "<br />\n"), $text);
2305          if($render_bbcode) {
2306              return render_bbcode_basics($text);
2307          }
2308      }
2309      return $text;
2310  }
2311  
2312  /**
2313   * Convert line break to <br>
2314   */
2315  function br_htmlencode($text='', $encode_function='html_specialchars') {
2316      if($text) {
2317          $text = $encode_function($text);
2318          $text = nl2br($text);
2319      }
2320      return $text;
2321  }
2322  
2323  /**
2324   * Render simple BBCode
2325   **/
2326  function render_bbcode_basics($text='', $mode='basic') {
2327  
2328      if($text === '') {
2329          return $text;
2330      }
2331  
2332      $text = render_bbcode_url($text);
2333      
2334      if($mode == 'basic') {
2335      
2336          $search        = array('[i]', '[/i]', '[u]', '[/u]', '[s]', '[/s]', '[b]', '[/b]', '[em]', '[/em]', '[br]');
2337          $replace    = array('<i>', '</i>', '<u>', '</u>', '<s>', '</s>', '<b>', '</b>', '<em>', '</em>', '<br />');
2338      
2339          return str_replace($search, $replace, $text);
2340          
2341      }
2342  
2343      $search        = array();
2344      $replace    = array();
2345  
2346      $search[0]        = '/\[i\](.*?)\[\/i\]/is';            $replace[0]        = '<i>$1</i>';
2347      $search[1]        = '/\[u\](.*?)\[\/u\]/is';            $replace[1]        = '<u>$1</u>';
2348      $search[2]        = '/\[s\](.*?)\[\/s\]/is';            $replace[2]        = '<strike>$1</strike>';
2349      $search[3]        = '/\[b\](.*?)\[\/b\]/is';            $replace[3]        = '<strong>$1</strong>';
2350      $search[4]        = '/\[br\]/i';                        $replace[4]        = '<br />';
2351      $search[5]        = '/\[em\](.*?)\[\/em\]/is';        $replace[5]        = '<em>$1</em>';
2352      $search[6]        = '/\[code\](.*?)\[\/code\]/is';    $replace[6]        = '<code>$1</code>';
2353      $search[7]        = '/\[cite\](.*?)\[\/cite\]/is';    $replace[7]        = '<cite>$1</cite>';
2354      $search[8]        = '/\[li\](.*?)\[\/li\]/is';        $replace[8]        = '<li>$1</li>';
2355      $search[9]        = '/\[dt\](.*?)\[\/dt\]/is';        $replace[9]        = '<dt>$1</dt>';
2356      $search[10]        = '/\[dd\](.*?)\[\/dd\]/is';        $replace[10]    = '<dd>$1</dd>';
2357      $search[11]        = '/\[ul\](.*?)\[\/ul\]/is';        $replace[11]    = '<ul>$1</ul>';
2358      $search[12]        = '/\[ol\](.*?)\[\/ol\]/is';        $replace[12]    = '<ol>$1</ol>';
2359      $search[13]        = '/\[dl\](.*?)\[\/dl\]/is';        $replace[13]    = '<dl>$1</dl>';
2360      $search[14]        = '/\[h1\](.*?)\[\/h1\]/is';        $replace[14]    = '<h1>$1</h1>';
2361      $search[15]        = '/\[h2\](.*?)\[\/h2\]/is';        $replace[15]    = '<h2>$1</h2>';
2362      $search[16]        = '/\[h3\](.*?)\[\/h3\]/is';        $replace[16]    = '<h3>$1</h3>';
2363      $search[17]        = '/\[h4\](.*?)\[\/h4\]/is';        $replace[17]    = '<h4>$1</h4>';
2364      $search[18]        = '/\[h5\](.*?)\[\/h5\]/is';        $replace[18]    = '<h5>$1</h5>';
2365      $search[19]        = '/\[h6\](.*?)\[\/h6\]/is';        $replace[19]    = '<h6>$1</h6>';
2366      
2367      $search[20]        = '/\[blockquote\](.*?)\[\/blockquote\]/is';
2368      $replace[20]    = '<blockquote>$1</blockquote>';
2369      
2370      return preg_replace($search, $replace, $text);
2371      
2372  }
2373  
2374  function render_bbcode_url($text) {
2375  
2376      if($text === '') {
2377          return $text;
2378      }
2379      $text = preg_replace_callback( array('/\[url=([^ ]+)(.*)\](.*)\[\/url\]/', '/\[a=([^ ]+)(.*)\](.*)\[\/a\]/'), 'get_bbcode_ahref', $text );
2380      return  preg_replace_callback( '/\[(http|https|ftp):\/\/([^ ]+)(.*)\]/', 'get_link_ahref', $text );
2381  }
2382  
2383  function get_bbcode_ahref($match) {
2384      $href    = empty($match[1]) ? '#' : xss_clean($match[1]);
2385      $target    = trim($match[2]) == '' ? '' : ' target="'.trim($match[2]).'"';
2386      $text    = empty($match[3]) ? $href : $match[3];
2387      return '<a href="'.$href.'"'.$target.'>'.$text.'</a>';
2388  }
2389  
2390  function get_link_ahref($match) {
2391      $href    = empty($match[2]) ? '#' : xss_clean($match[2]);
2392      $text    = empty($match[3]) ? $href : trim($match[3]);
2393      return '<a href="'.$match[1].'://'.$href.'" target="_blank">'.$text.'</a>';
2394  }
2395  
2396  /**
2397   * Convert short file size (100M) to bytes
2398   */
2399  function getBytes($size) {
2400      
2401      if(is_numeric($size)) {
2402          
2403          return $size;
2404          
2405      } elseif($size) {
2406      
2407          $_unit = array(
2408      
2409              'B'            => 1,
2410              'K'            => 1024,
2411              'M'            => 1048576,
2412              'G'            => 1073741824,
2413              'T'            => 1099511627776,
2414              
2415              'KB'        => 1024,
2416              'MB'        => 1048576,
2417              'GB'        => 1073741824,
2418              'TB'        => 1099511627776,
2419              
2420              'BYTE'        => 1,
2421              'KILOBYTE'    => 1024,
2422              'MEGABYTE'    => 1048576,
2423              'GIGABYTE'    => 1073741824,
2424              'TERABYTE'    => 1099511627776
2425          
2426          );
2427          
2428          $size = trim($size);
2429          
2430          foreach($_unit as $key => $value) {
2431          
2432              if( preg_match('/.*?'.$key.'$/i', $size) ) {
2433              
2434                  $num = trim( preg_replace('/(.*?)'.$key.'$/i', '$1', $size) );
2435                  
2436                  return ceil($num * $value);
2437              
2438              }
2439          }
2440      }
2441  
2442      return $size == false ? 0 : floatval($size);
2443  
2444  }
2445  
2446  /**
2447   * Try to calculate the memory necessary to
2448   * handle the image in RAM to avoid
2449   * errors based on memory limit.
2450   */  
2451  function getRealImageSize(& $imginfo) {
2452  
2453      $size = 0;
2454  
2455      // check image width and height
2456      if(!empty($imginfo[0]) && !empty($imginfo[1])) {
2457          
2458          $size = $imginfo[0] * $imginfo[1];
2459  
2460      }
2461      // handle possible alpha channel for PNG and TIF
2462      $alpha = ($imginfo[2] == 3 || $imginfo[2] == 7 || $imginfo[2] == 6) ? 1 : 0;
2463      if($size && !empty($imginfo['channels'])) {
2464          
2465          // channel - in general this is 3 (RGB) or 4 (CMYK)
2466          $size = $size * ( $imginfo['channels'] + $alpha );
2467          
2468      } elseif($size && !empty($imginfo['bits'])) {
2469      
2470          // bits - general value is 8Bit, but can be higher too
2471          $size = $size * ( log($imginfo['bits'], 2) + $alpha );
2472      
2473      } elseif($size) {
2474          
2475          // use a default of 4 like for CMYK
2476          // should meet general usage
2477          $size = $size * ( 4 + $alpha );
2478      
2479      }
2480  
2481      return $size;
2482  
2483  }
2484  
2485  function is_intval($str) {
2486       return (bool)preg_match( '/^[\-+]?[0-9]+$/', $str );
2487  }
2488  
2489  function attribute_name_clean($name='') {
2490      $name = trim(remove_accents($name));
2491      $name = str_replace(
2492                  array(' ','/','\\','#','+',':','.'), 
2493                  array('_','-', '-','_','-','-','-'), 
2494                  $name
2495              );
2496      $name = preg_replace('/[^a-zA-Z0-9\-_]/', '', $name);
2497      $name = preg_replace('/^\d+/', '', $name);
2498      return $name;
2499  }
2500  
2501  /**
2502   * Try alternative way to test for bool value
2503   *
2504   * @param mixed
2505   * @param bool
2506   */
2507  function boolval($BOOL, $STRICT=false) {
2508  
2509      if(is_string($BOOL)) {
2510          $BOOL = strtoupper($BOOL);
2511      }
2512      
2513      // no strict test, check only against false bool
2514      if( !$STRICT && in_array($BOOL, array(false, 0, NULL, 'FALSE', 'NO', 'N', 'OFF', '0'), true) ) {
2515  
2516          return false;
2517  
2518      // strict, check against true bool
2519      } elseif($STRICT && in_array($BOOL, array(true, 1, 'TRUE', 'YES', 'Y', 'ON', '1'), true) ) {
2520  
2521          return true;
2522  
2523      }
2524  
2525      // let PHP decide
2526      return $BOOL ? true : false;
2527  }
2528  
2529  // sanitize a text for nice URL/alias or whatever
2530  function uri_sanitize($text) {
2531      
2532      $text = pre_remove_accents($text);
2533      $text = get_alnum_dashes($text, true);
2534      $text = trim($text);
2535      if($text != '') {
2536          $text = trim( preg_replace('/\-\-+/', '-', $text), '-' );
2537          $text = trim( preg_replace('/__+/', '_', $text), '_' );
2538      }
2539      
2540      return $text;
2541  }
2542  
2543  ?>


Generated: Tue Nov 16 22:51:00 2010 Cross-referenced by PHPXref 0.7