/source/application/business/Utils.php
PHP | 1006 lines | 683 code | 110 blank | 213 comment | 157 complexity | 5a744e25535befe02e208575d104bca3 MD5 | raw file
Possible License(s): LGPL-2.1
- <?php
- class Utils
- {
- function checkEmailValid($email)
- {
- //$patterns = "/(.+)@(.+)\.(.+)/";
- $patterns = '/^(.+)'.
- '[@]'.
- '([^-~!@#$%^&*()_+={\\[\\]}:;"\'<,>.?\/\\|\\\\]' .
- '[-a-z0-9]{0,62}' .
- '[^-~!@#$%^&*()_+={\\[\\]}:;"\'<,>.?\/\\|\\\\])'.
- '\.'.
- '([a-z]{2}'.
- '|com|net|edu|org'.
- '|gov|mil|int|biz'.
- '|pro|info|arpa|aero'.
- '|coop|name|museum)$/ix';
- $patterns='/^([a-zA-Z0-9])+([\.a-zA-Z0-9_-])*@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-]+)*\.([a-zA-Z]{2,6})$/';
- if (preg_match($patterns,$email, $matches) == 1)
- return true;
- return false;
- }
-
- /**
- * convert an input date to a mySQL date
- *
- * @param string $date
- * @param string $input_format
- * @return mySQL date string
- */
- static function convertToMySQLDate($date, $input_format = "%d/%m/%Y")
- {
- $arr = explode(" ", $input_format, 2);
- $out_format = "%Y-%m-%d";
- // if $date do not contain time, the format should be removed time
- if (count(explode(" ", $date, 2)) == 1)
- {
- $input_format = $arr[0];
- }
- if (count($arr) == 2)
- {
- $out_format = $out_format." ".$arr[1];
- }
- $date_arr = TVC_DateTime::parseDate($date,$input_format);
- if ($date_arr)
- {
- return TVC_DateTime::formatDate($date_arr, $out_format);
- }
- return false;
- }
- function convertMySQLDateToOtherFormat($date, $out_format = "%d/%m/%Y")
- {
- $arr = explode(" ", $out_format, 2);
- $input_format = "%Y-%m-%d";
- if (count($arr) == 2)
- {
- $input_format = $input_format." ".$arr[1];
- }
- $date_arr = TVC_DateTime::parseDate($date, $input_format);
- if ($date_arr)
- {
- return TVC_DateTime::formatDate($date_arr, $out_format);
- }
- return false;
- }
- /**
- * convert a date ('Y-m-d H:i:s') from a time zone to other time zone
- *
- * @param string $date is a date in string format
- * @return string $convert_date is a date in string format has been converted to new time zone
- */
- public static function convertToOtherTimeZone($date, $from_time_zone, $to_time_zone)
- {
- if (strtolower($from_time_zone) == strtolower($to_time_zone)) {
- return $date;
- }
- $fromTimeZone = timezone_open($from_time_zone);
- $toTimeZone = timezone_open($to_time_zone);
- $convertDate = date_create($date, $fromTimeZone);
- date_timezone_set($convertDate, $toTimeZone);
- if ($convertDate)
- {
- return date_format($convertDate, 'Y-m-d H:i:s');
- }
- else
- {
- return $date;
- }
- }
- /**
- * subtract a date from number day
- *
- * @param string $date
- * @param int $numday number of day that you want to subtract
- * @param string $input_format
- * @return string date after subtract
- */
- function subtractDate($date, $numday = 1, $input_format = "%d/%m/%Y")
- {
- $date_arr = TVC_DateTime::parseDate($date,$input_format);
- $date_int = mktime(0,0,0,$date_arr['month'], $date_arr['day'], $date_arr['year']);
- $date_int = $date_int - $numday * 86400;
- $input_format = str_replace('%','',$input_format);
- return date($input_format, $date_int);
- }
- /**
- * add one or many day to a date
- *
- * @param string $date
- * @param int $numday number of day that you want to add
- * @param string $input_format
- * @return unknown
- */
- function addDate($date, $numday = 1, $input_format = "%d/%m/%Y")
- {
- $date_arr = TVC_DateTime::parseDate($date,$input_format);
- $date_int = mktime(0,0,0,$date_arr['month'], $date_arr['day'], $date_arr['year']);
- $date_int = $date_int + $numday * 86400;
- $input_format = str_replace('%','',$input_format);
- return date($input_format, $date_int);
- }
- /**
- * compare 2 date
- * @param day1 format as mysql date
- * @param day2
- * @return:
- * 0 : equal
- * 1 : day1 greater than day2
- * 2 : day2 greater than day1
- */
- static function compareDate($day1, $day2, $input_format = '%d/%m/%Y')
- {
- $day1_arr = TVC_DateTime::parseDate($day1,$input_format);
- $day2_arr = TVC_DateTime::parseDate($day2,$input_format);
- $day1 = mktime(0,0,0,$day1_arr['month'],$day1_arr['day'],$day1_arr['year']);
- $day2 = mktime(0,0,0,$day2_arr['month'],$day2_arr['day'],$day2_arr['year']);
- if ($day1 == $day2)
- {
- return 0;
- }
- elseif ($day1 > $day2)
- {
- return 1;
- }
- return 2;
- }
- /**
- * check date is valid
- *
- * @param string $date
- * @param $format
- * @return unknown
- */
- static function isValidDate($date,$input_format = "%d/%m/%Y")
- {
- $date_arr = TVC_DateTime::parseDate($date, $input_format);
- if ($date_arr)
- {
- return checkdate($date_arr['month'], $date_arr['day'], $date_arr['year']);
- }
- return false;
- }
- /**
- * check time is valid
- *
- * @param string $time
- * @param $format
- * @return unknown
- */
- static function isValidTime($time, $input_format = "%H:%i:%s")
- {
- if ($input_format == "%H:%i:%s" || $input_format == "%H:%i")
- {
- $arr = explode(':', $time);
- $count = count($arr);
- if ($count != 2 && $count != 3)
- {
- return false;
- }
- list($hour, $minute) = $arr;
- if ($count == 3)
- {
- $second = $arr[2];
- }
- if ( !(isset($hour) && $hour >= 0 && $hour <= 23) )
- {
- return false;
- }
- if ( !(isset($minute) && $minute >= 0 && $minute <= 59) )
- {
- return false;
- }
- if ( isset($second) && !($second >= 0 && $second <= 59) )
- {
- return false;
- }
- return true;
- }
- return false;
- }
- /**
- * check datetime is valid
- *
- * @param string $datetime
- * @param $format
- * @return unknown
- */
- static function isValidDateTime($datetime, $input_format = "%d/%m/%Y %H:%i:%s")
- {
- $date_parts = explode(" ", $datetime, 2);
- $date = $date_parts[0];
- $format_parts = explode(" ", $input_format, 2);
- $date_format = $format_parts[0];
- if (count($format_parts) > 1)
- {
- $time_format = $format_parts[1];
- }
- if (count($date_parts) == 1)
- {
- return self::isValidDate($date, $date_format);
- }
- else if (count($date_parts) == 2)
- {
- $time = $date_parts[1];
- if (!self::isValidDate($date, $date_format))
- {
- return false;
- }
- if (isset($time_format))
- {
- return self::isValidTime($time, $time_format);
- }
- else
- {
- return self::isValidTime($time);
- }
- }
- }
- /**
- * check timezone is valid
- *
- * @param string $time_zone
- * @return bool true if the timezone is valid, else return false
- */
- static function isValidTimeZone($time_zone)
- {
- $tz = timezone_open($time_zone);
- if (!$tz)
- {
- return false;
- }
- return true;
- }
- /**
- * check whether or not current value is a positive whole integer
- * @param string $value
- * @return boolean
- */
- static function isPositiveInteger($value)
- {
- return is_numeric($value) ? ( (intval($value) == $value) && ($value >= 0) ) : false;
- }
- /**
- * check whether or not current value is a whole integer
- * @param string $value
- * @return boolean
- */
- static function isInteger($value)
- {
- return preg_match("/^[-+]?\b\d+\b$/", $value);
- }
- /**
- * formats a floating point number string in decimal notation, supports signed floats,
- * also supports non-standard formatting e.g. 0.2e+2 for 20
- * e.g. '1.6E+6' to '1600000', '-4.566e-12' to '-0.000000000004566', '+34e+10' to '340000000000'
- * @param string $float_str
- */
- static function floatToString($float_str)
- {
- // make sure its a standard php float string (i.e. change 0.2e+2 to 20)
- // php will automatically format floats decimally if they are within a certain range
- $float_str = (string)((float)($float_str));
- // if there is an E in the float string
- if(($pos = strpos(strtolower($float_str), 'e')) !== false)
- {
- // get either side of the E, e.g. 1.6E+6 => exp E+6, num 1.6
- $exp = substr($float_str, $pos+1);
- $num = substr($float_str, 0, $pos);
- // strip off num sign, if there is one, and leave it off if its + (not required)
- if((($num_sign = $num[0]) === '+') || ($num_sign === '-')) $num = substr($num, 1);
- else $num_sign = '';
- if($num_sign === '+') $num_sign = '';
- // strip off exponential sign ('+' or '-' as in 'E+6') if there is one, otherwise throw error, e.g. E+6 => '+'
- if((($exp_sign = $exp[0]) === '+') || ($exp_sign === '-')) $exp = substr($exp, 1);
- else trigger_error("Could not convert exponential notation to decimal notation: invalid float string '$float_str'", E_USER_ERROR);
- // get the number of decimal places to the right of the decimal point (or 0 if there is no dec point), e.g., 1.6 => 1
- $right_dec_places = (($dec_pos = strpos($num, '.')) === false) ? 0 : strlen(substr($num, $dec_pos+1));
- // get the number of decimal places to the left of the decimal point (or the length of the entire num if there is no dec point), e.g. 1.6 => 1
- $left_dec_places = ($dec_pos === false) ? strlen($num) : strlen(substr($num, 0, $dec_pos));
- // work out number of zeros from exp, exp sign and dec places, e.g. exp 6, exp sign +, dec places 1 => num zeros 5
- if($exp_sign === '+') $num_zeros = $exp - $right_dec_places;
- else $num_zeros = $exp - $left_dec_places;
- // build a string with $num_zeros zeros, e.g. '0' 5 times => '00000'
- $zeros = str_pad('', $num_zeros, '0');
- // strip decimal from num, e.g. 1.6 => 16
- if($dec_pos !== false) $num = str_replace('.', '', $num);
- // if positive exponent, return like 1600000
- if($exp_sign === '+') return $num_sign.$num.$zeros;
- // if negative exponent, return like 0.0000016
- else return $num_sign.'0.'.$zeros.$num;
- }
- // otherwise, assume already in decimal notation and return
- else return $float_str;
- }
- /**
- * compare two float with specified number of digits after dot character (.)
- *
- * @param float $a float1
- * @param float $b float2
- * @param integer $decimals number of digits after dot character (.)
- */
- static function isFloatEqual($a, $b, $decimals = 0)
- {
- if (!is_int($decimals) || $decimals < 0){
- $decimals = 10;
- }
- return sprintf('%01.'.$decimals.'f',$a)==sprintf('%01.'.$decimals.'f',$b);
- }
- /**
- * compare two string which are applied multilanguage format
- *
- * @param String $souce_str source string
- * @param String $des_str destination string
- * @param array $arr_lang eg: 'en', 'fr','vn'
- */
- static function isI18nStringEquals($source_str, $des_str, $arr_lang = null)
- {
- if(!$arr_lang)
- {
- $arr_lang = TVC_Config::get('I18N','AUTHORIZED_LANGUAGES');
- }
- $lang_num = count($arr_lang);
- $preg_arr = array();
- if($source_str != "" && $des_str !="")
- {
- for($i = 0; $i < $lang_num; $i++)
- {
- $preg_arr = '/<'.$arr_lang[$i].'>([^<]*)<\/'.$arr_lang[$i].'>/';
- // get data from destination string
- preg_match($preg_arr, $des_str, $des_matches);
- // get data from source string
- preg_match($preg_arr, $source_str, $source_matches);
- if(count($source_matches) > 0 && count($des_matches) > 0) {
- str_replace(array('<','>'), array('<','>'), $des_matches[1]);
- str_replace(array('<','>'), array('<','>'), $source_matches[1]);
- if(strcasecmp($source_matches[1], $des_matches[1]) == 0 )
- {
- return true;
- }
- }
- }
- }
- return false;
- }
- /**
- * check string satisfy multilanguage format(eg. <en>xxxx</en><fr>yyyyy</fr>)
- *
- * @param string $str_source string is checked
- * @param array $arr_lang array language
- */
- static function isI18nStringFormat($source_str, $arr_lang = null)
- {
- if(!$arr_lang)
- {
- $arr_lang = TVC_Config::get('I18N','AUTHORIZED_LANGUAGES');
- }
- $lang_num = count($arr_lang);
- $str_src = $source_str;
- $preg_arr = array();
- if($str_src != "")
- {
- for($i = 0; $i < $lang_num; $i++)
- {
- $preg_arr = '/<'.$arr_lang[$i].'>([^<]*)<\/'.$arr_lang[$i].'>/';
- // get data from source string
- preg_match($preg_arr, $str_src, $source_matches);
- if(count($source_matches) > 0) {
- $str_src = str_replace($source_matches[0], '', $str_src);
- }
- if($i == $lang_num - 1)
- {
- if(strlen(trim($str_src))>0)
- {
- return false;
- }
- }
- }
- }
- return true;
- }
- /**
- * Purpose: Extract a specific language translation from a tag encoded language chain<br>
- * Input:<br>
- * - string: input language chain in format
- * "<en>english</en><fr>anglais</fr>"
- * - language_code : the language code to extract, if none specified, we will take
- * the one of TVC_Multilanguage
- * - use_default_on_fail : boolean. If TRUE, we will try to extract the default
- * language translation in case of failure. Otherwise, we just return an
- * empty string on failure.
- * @author Cl?確ent Nodet <clement dot nodet at gmail dot com>
- * @param string
- * @param string
- * @return string|void
- * @uses smarty_make_timestamp()
- */
- public static function getI18n($string, $language_code = '', $use_default_on_fail = TRUE)
- {
- if ($language_code == '')
- {
- $language_code = TVC_Multilanguage::getLanguage();
- }
- // Try to find the chain in the string
- if (preg_match('/<'.$language_code.'>([^<]*)<\/'.$language_code.'>/',$string,$matches) > 0)
- {
- return str_replace(array('<','>'),array('<','>'),$matches[1]);
- }
- else
- {
- // We couldn't find it, do we need to try again with the default language?
- if ($use_default_on_fail and $language_code != TVC_Config::get('I18N','DEFAULT_LANGUAGE'))
- {
- return Utils::getI18n($string,TVC_Config::get('I18N','DEFAULT_LANGUAGE'),FALSE);
- }
- else
- {
- return '';
- }
- }
- }
- /**
- * check max length of string which is applied i18n format
- * the function will check the length of string between each start tag and end tag(eg. <en>xxxx</en>...)
- * if a string have length > max_length, the alert message box will display
- * @param string $source_str: string is checked
- * @param integer $max_length: max length of string
- * @param array $arr_lang: array of languages
- * @return boolean true if length of string less than or equal max length
- */
- static function isValidLengthI18nString($source_str, $max_length, $arr_lang = null)
- {
- if(!$arr_lang)
- {
- $arr_lang = TVC_Config::get('I18N','AUTHORIZED_LANGUAGES');
- }
- $lang_num = count($arr_lang);
- for ($i = 0; $i < $lang_num; $i ++)
- {
- $pattern = '/<'.$arr_lang[$i].'>([^<]*)<\/'.$arr_lang[$i].'>/';
- preg_match($pattern, $source_str, $source_matches);
- if (count($source_matches) > 0)
- {
- if (strlen(trim($source_matches[1])) > $max_length)
- {
- return false;
- }
- }
- }
- return true;
- }
- /**
- * Check empty multilanguge string(eg.<en>string</string)...
- *
- * @param string $source_str
- * @param array $arr_lang
- */
- static function isEmptyI18nString($source_str, $arr_lang = null)
- {
- if(!$arr_lang)
- {
- $arr_lang = TVC_Config::get('I18N','AUTHORIZED_LANGUAGES');
- }
- $lang_num = count($arr_lang);
- for ($i = 0; $i < $lang_num; $i ++)
- {
- $pattern = '/<'.$arr_lang[$i].'>([^<]*)<\/'.$arr_lang[$i].'>/';
- preg_match($pattern, $source_str, $source_matches);
- /*var_dump($source_matches);
- die;*/
- if (count($source_matches) > 0)
- {
- if (strlen(trim($source_matches[1])) == 0)
- {
- return false;
- }
- }
- }
- return true;
- }
- public function downloadFile($file_name, $dir = "")
- {
- if(!file_exists($dir.$file_name))
- {
- exit("File is not available");
- }
-
- // set headers
- header("Pragma: public");
- header("Expires: 0");
- header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
- header("Cache-Control: private");
- header("Content-Description: File Transfer");
- header("Content-Disposition: attachment; filename=\"".basename("$file_name")."\"");
- header("Content-Transfer-Encoding: binary");
- header("Content-Length: " . @filesize("$dir.$file_name"));
- @readfile("$dir.file_name");
- die();
- }
- static function displayResizeImage($image_file, $max_width, $max_height, $path, $img_url, $addslases = 0)
- {
- if($image_file && file_exists($path."/".$image_file))
- {
- $img_info = getimagesize($path."/".$image_file);
- $width = $img_info[0];
- $height = $img_info[1];
- $width_ratio = $max_width/$width;
- $height_ratio = $max_height/$height;
- $ratio = ($width_ratio < $height_ratio) ? $width_ratio : $height_ratio;
- $ratio = ($ratio < 1) ? $ratio : 1;
- if($addslases != 0)
- {
- echo addslashes("<img src='$img_url/$image_file' width='".intval($width*$ratio)."' height='".intval($height*$ratio)."' style='padding-top:2px'/>");
- }
- else
- {
- echo "<img src='$img_url/$image_file' width='".intval($width*$ratio)."' height='".intval($height*$ratio)."' style='padding-top:2px'/>";
- }
- }
- }
- static function displayVisualImage($image, $addslases = 0)
- {
- if(!Parameter::$params['VISUAL_IMAGE_MAX_WIDTH'] || !Parameter::$params['VISUAL_IMAGE_MAX_HEIGHT'])
- {
- Parameter::loadAllParameters();
- }
- $width = Parameter::$params['VISUAL_IMAGE_MAX_WIDTH'];
- $height = Parameter::$params['VISUAL_IMAGE_MAX_HEIGHT'];
- Utils::displayResizeImage($image, $width, $height, Format::getFolderImage(), STATIC_COMPONENT_URL_FILE."/".Format::IMAGE_URL, $addslases);
- }
- static function displayTechnicalDatalImage($image, $addslases = 0)
- {
- $width = Parameter::IMAGE_MAX_WIDTH;
- $height = Parameter::IMAGE_MAX_HEIGHT;
- Utils::displayResizeImage($image, $width, $height, TechnicalDataImage::getFolderImage(), STATIC_COMPONENT_URL_FILE."/".TechnicalDataImage::IMAGE_URL, $addslases);
- }
- public static function getCurrentTimeSlot($constraint = "now")
- {
- $cur_time = strtotime($constraint);
- $cur_m = ((date('i', $cur_time) < 30) ? "00" : "30");
- $cur_ymd = date('Y-m-d H', $cur_time);
- $cur_datetime = $cur_ymd . ":" . $cur_m . ":00";
- return $cur_datetime;
- }
- /*
- ============================
- QuickCaptcha 1.0 - A bot-thwarting text-in-image web tool.
- Copyright (c) 2006 Web 1 Marketing, Inc.
- This program is free software; you can redistribute it and/or
- modify it under the terms of the GNU General Public License
- as published by the Free Software Foundation; either version 2
- of the License, or (at your option) any later version.
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
- ============================
- See settings.php for common settings. You shouldn't need to change
- anything in this file.
- ============================
- */
- public function generateCAPTCHA($length=6)
- {
- $acceptedChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ123456789';
- // A value between 0 and 100 describing how much color overlap
- // there is between text and other objects. Lower is more
- // secure against bots, but also harder to read.
- $contrast = 20;
- // Various obfuscation techniques.
- $num_polygons = 2; // Number of triangles to draw. 0 = none
- $num_ellipses = 6; // Number of ellipses to draw. 0 = none
- $num_lines = 10; // Number of lines to draw. 0 = none
- $num_dots = 50; // Number of dots to draw. 0 = none
- $min_thickness = 2; // Minimum thickness in pixels of lines
- $max_thickness = 8; // Maximum thickness in pixles of lines
- $min_radius = 1; // Minimum radius in pixels of ellipses
- $max_radius = 15; // Maximum radius in pixels of ellipses
- // How opaque should the obscuring objects be. 0 is opaque, 127
- // is transparent.
- $object_alpha = 75;
- // Keep #'s reasonable.
- $min_thickness = max(1,$min_thickness);
- $max_thickness = min(20,$max_thickness);
- // Make radii into height/width
- $min_radius *= 2;
- $max_radius *= 2;
- // Renormalize contrast
- $contrast = 255 * ($contrast / 100.0);
- $o_contrast = 1.3 * $contrast;
- $width = 11 * imagefontwidth (5);
- $height = 2.5 * imagefontheight (5);
- $image = imagecreatetruecolor ($width, $height);
- imagealphablending($image, true);
- $black = imagecolorallocatealpha($image,0,0,0,0);
- // Build the validation string
- $max = strlen($acceptedChars)-1;
- $password = NULL;
- for($i=0; $i < $length; $i++) {
- $cnum[$i] = $acceptedChars{mt_rand(0, $max)};
- $password .= $cnum[$i];
- }
- // Add string to image
- $rotated = imagecreatetruecolor (70, 70);
- $x = 0;
- for ($i = 0; $i < $length; $i++) {
- $buffer = imagecreatetruecolor (20, 20);
- $buffer2 = imagecreatetruecolor (40, 40);
- // Get a random color
- $red = mt_rand(0,255);
- $green = mt_rand(0,255);
- $blue = 255 - sqrt($red * $red + $green * $green);
- $color = imagecolorallocate ($buffer, $red, $green, $blue);
- // Create character
- imagestring($buffer, 5, 0, 0, $cnum[$i], $color);
- // Resize character
- imagecopyresized ($buffer2, $buffer, 0, 0, 0, 0, 15 + mt_rand(0,12), 25 + mt_rand(0,12), 20, 20);
- // Rotate characters a little
- //$rotated = imagerotate($buffer2, mt_rand(-25, 25),imagecolorallocatealpha($buffer2,0,0,0,0));
- $rotated = $buffer2;
- imagecolortransparent ($rotated, imagecolorallocatealpha($rotated,0,0,0,0));
- // Move characters around a little
- $y = mt_rand(1, 3);
- $x += mt_rand(2, 6);
- imagecopymerge ($image, $rotated, $x, $y, 0, 0, 40, 40, 100);
- $x += 11;
- imagedestroy ($buffer);
- imagedestroy ($buffer2);
- }
- // Draw polygons
- if ($num_polygons > 0) for ($i = 0; $i < $num_polygons; $i++) {
- $vertices = array (
- mt_rand(-0.25*$width,$width*1.25),mt_rand(-0.25*$width,$width*1.25),
- mt_rand(-0.25*$width,$width*1.25),mt_rand(-0.25*$width,$width*1.25),
- mt_rand(-0.25*$width,$width*1.25),mt_rand(-0.25*$width,$width*1.25)
- );
- $color = imagecolorallocatealpha ($image, mt_rand(0,$o_contrast), mt_rand(0,$o_contrast), mt_rand(0,$o_contrast), $object_alpha);
- imagefilledpolygon($image, $vertices, 3, $color);
- }
- // Draw random circles
- if ($num_ellipses > 0) for ($i = 0; $i < $num_ellipses; $i++) {
- $x1 = mt_rand(0,$width);
- $y1 = mt_rand(0,$height);
- $color = imagecolorallocatealpha ($image, mt_rand(0,$o_contrast), mt_rand(0,$o_contrast), mt_rand(0,$o_contrast), $object_alpha);
- // $color = imagecolorallocate($image, mt_rand(0,$o_contrast), mt_rand(0,$o_contrast), mt_rand(0,$o_contrast));
- imagefilledellipse($image, $x1, $y1, mt_rand($min_radius,$max_radius), mt_rand($min_radius,$max_radius), $color);
- }
- // Draw random lines
- if ($num_lines > 0) for ($i = 0; $i < $num_lines; $i++) {
- $x1 = mt_rand(-$width*0.25,$width*1.25);
- $y1 = mt_rand(-$height*0.25,$height*1.25);
- $x2 = mt_rand(-$width*0.25,$width*1.25);
- $y2 = mt_rand(-$height*0.25,$height*1.25);
- $color = imagecolorallocatealpha ($image, mt_rand(0,$o_contrast), mt_rand(0,$o_contrast), mt_rand(0,$o_contrast), $object_alpha);
- imagesetthickness ($image, mt_rand($min_thickness,$max_thickness));
- imageline($image, $x1, $y1, $x2, $y2 , $color);
- }
- // Draw random dots
- if ($num_dots > 0) for ($i = 0; $i < $num_dots; $i++) {
- $x1 = mt_rand(0,$width);
- $y1 = mt_rand(0,$height);
- $color = imagecolorallocatealpha ($image, mt_rand(0,$o_contrast), mt_rand(0,$o_contrast), mt_rand(0,$o_contrast),$object_alpha);
- imagesetpixel($image, $x1, $y1, $color);
- }
- $_SESSION['captcha'] = $password;
- header('Content-type: image/png');
- imagepng($image);
- imagedestroy($image);
- }
- public function validateCaptcha($captcha_post)
- {
- $error = "";
- if(!isset($captcha_post) || $captcha_post == "" || $captcha_post==null)
- {
- $error = '_MSG_CODE_VERIFICATION_IS_EMPTY';
- }
- else if($captcha_post != $_SESSION['captcha'])
- {
- $error = '_MSG_CODE_VERIFICATION_NOT_MATCH';
- }
- return $error;
- }
- public function generateNews()
- {
- $language = TVC_MultiLanguage::getLanguage();
- $dom = new DOMDocument;
- if($language=='vi')
- {
- $content = @file_get_contents(NEWS_VI_SOURCE);
- $max_news_get = MAX_NEWS_VI_GET;
- }
- else
- {
- $content = @file_get_contents(NEWS_EN_SOURCE);
- $max_news_get = MAX_NEWS_EN_GET;
- }
- if($content)
- {
- $dom->loadXML($content);
- $s = simplexml_import_dom($dom);
- for($i=0;$i<$max_news_get;$i++)
- {
- $title = $s->channel->item[$i]->title;
- $link = $s->channel->item[$i]->link;
- echo "<p class='button rss_image'><a href='$link'><span>$title</span></a></p>";
- }
- }
- else
- {
- return false;
- }
- return true;
- }
- public function encodeFileName($file_name)
- {
- $f_arr = array();
- $f_arr = explode("/",$file_name);
- if(count($f_arr)>1)
- { $s = "";
- for($i=0;$i<count($f_arr)-1;$i++)
- {
- $s .= ";".$f_arr[$i];
- }
- return "f/". md5($f_arr[count($f_arr)-1]).(($s!="")?"/s/$s":"");
- }
- else
- {
- return "f/". md5($file_name);
- }
- }
-
- public function encodeId($id)
- {
- $id_arr = array();
- $id_arr = explode("/",$id);
- if(count($id_arr)>1)
- { $s = "";
- for($i=0;$i<count($id_arr)-1;$i++)
- {
- $s .= ";".$id_arr[$i];
- }
- return "id/". md5($id_arr[count($id_arr)-1]).(($s!="")?"/id/$s":"");
- }
- else
- {
- return "id/". md5($id);
- }
- }
- /**
- * set multilanguge on main domain
- * @param $language
- * @return unknown_type
- */
- public function setI18nOnMaindomain($language)
- {
- setcookie("language", $language, time() + 3600*24*30, "/", DOMAIN);
- }
- /**
- * unset multilanguage on sub domain
- * @return unknown_type
- */
- public function resetI18nOnSubdomain()
- {
- // unset cookies on sub domain
- setcookie("language", "", time() - 3600*24*30, "/", ADMIN_DOMAIN);
- setcookie("language", "", time() - 3600*24*30, "/", MASTER_DOMAIN);
- setcookie("language", "", time() - 3600*24*30, "/", PUBLIC_DOMAIN);
- setcookie("language", "", time() - 3600*24*30, "/", HOME_DOMAIN);
- }
- public function resetAccessAuthentical()
- {
- if(isset($_COOKIE['from_other_site']))
- {
- setcookie("from_other_site", "", time() - 3600*24*30, "/", DOMAIN);
- }
- if(isset($_COOKIE['from_public_site']))
- {
- setcookie("from_public_site", "", time() - 3600*24*30, "/", DOMAIN);
- }
- }
- public static function mmsort($result, $subkey, $isUseI18n = true)
- {
- $array = array();
- $notInclude = array('__table', '_database', '_DB_DataObject_version', 'N', '_database_dsn_md5', '_DB_resultid');
- $j = 0;
- while($result->fetch()) {
- foreach($result as $i => $val) {
- if(strlen($val) > 0 && !in_array($i, $notInclude)) {
- if($i == $subkey)
- $array[$j][$i] = $isUseI18n ? Utils::getI18n($val) : $val;
- else $array[$j][$i] = $val;
- }
- }
- $j++;
- }
- return Utils::subval_sort($array, $subkey);
- }
- public static function subval_sort($a,$subkey)
- {
- if(!is_array($a) || count($a) == 0) {
- return array();
- }
- foreach($a as $k=>$v) {
- $b[$k] = strtolower($v[$subkey]);
- }
- asort($b);
- foreach($b as $key=>$val) {
- $c[$key] = $a[$key];
- }
- return $c;
- }
- //Utils::setIniLang()
- public function setIniLang($section = false)
- {
- $template_dir = realpath(TVC_Config::get('FS','TEMPLATE_DIR'));
- $misc_ini_file = $template_dir . "/misc.ini";
- $ini_array = parse_ini($misc_ini_file);
- $section = !$section ? TVC_MultiLanguage::getLanguage() : $section;
- if( isset( $ini_array[ $section ] ) ) {
- foreach($ini_array[ $section ] as $constant => $value) {
- if(!defined($constant)) {
- define($constant, $value);
- }
- }
- }
- }
- function dateRangeArray($start, $end, $format = 'Y-m-d') {
- $range = array();
- if (is_string($start) === true) $start = strtotime($start);
- if (is_string($end) === true ) $end = strtotime($end);
- do {
- $range[] = date($format, $start);
- $start = strtotime("+ 1 day", $start);
- } while($start <= $end);
- return $range;
- }
- }
- function parse_ini ( $filepath ) {
- $ini = file( $filepath );
- if ( count( $ini ) == 0 ) { return array(); }
- $sections = array();
- $values = array();
- $globals = array();
- $i = 0;
- foreach( $ini as $line ){
- $line = trim( $line );
- // Comments
- if ( $line == '' || $line{0} == ';' || preg_match("|(^\/\/)|U", $line) ) { continue; }
- // Sections
- if ( $line{0} == '[' ) {
- $sections[] = substr( $line, 1, -1 );
- $i++;
- continue;
- }
- // Key-value pair
- list( $key, $value ) = explode( '=', $line, 2 );
- $key = trim( $key );
- $value = trim( $value );
- if ( $i == 0 ) {
- // Array values
- if ( substr( $line, -1, 2 ) == '[]' ) {
- $globals[ $key ][] = $value;
- } else {
- $globals[ $key ] = $value;
- }
- } else {
- // Array values
- if ( substr( $line, -1, 2 ) == '[]' ) {
- $values[ $i - 1 ][ $key ][] = $value;
- } else {
- $values[ $i - 1 ][ $key ] = $value;
- }
- }
- }
- for( $j=0; $j<$i; $j++ ) {
- $result[ $sections[ $j ] ] = $values[ $j ];
- }
- return $result + $globals;
- }