[ Index ]

PHP Cross Reference of phpwcms V1.4.3 _r380 (23.11.09)

title

Body

[close]

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

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


Generated: Wed Dec 30 05:55:15 2009 Cross-referenced by PHPXref 0.7