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