PageRenderTime 59ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/source/application/business/Utils.php

http://sharebooks.googlecode.com/
PHP | 1006 lines | 683 code | 110 blank | 213 comment | 157 complexity | 5a744e25535befe02e208575d104bca3 MD5 | raw file
Possible License(s): LGPL-2.1
  1. <?php
  2. class Utils
  3. {
  4. function checkEmailValid($email)
  5. {
  6. //$patterns = "/(.+)@(.+)\.(.+)/";
  7. $patterns = '/^(.+)'.
  8. '[@]'.
  9. '([^-~!@#$%^&*()_+={\\[\\]}:;"\'<,>.?\/\\|\\\\]' .
  10. '[-a-z0-9]{0,62}' .
  11. '[^-~!@#$%^&*()_+={\\[\\]}:;"\'<,>.?\/\\|\\\\])'.
  12. '\.'.
  13. '([a-z]{2}'.
  14. '|com|net|edu|org'.
  15. '|gov|mil|int|biz'.
  16. '|pro|info|arpa|aero'.
  17. '|coop|name|museum)$/ix';
  18. $patterns='/^([a-zA-Z0-9])+([\.a-zA-Z0-9_-])*@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-]+)*\.([a-zA-Z]{2,6})$/';
  19. if (preg_match($patterns,$email, $matches) == 1)
  20. return true;
  21. return false;
  22. }
  23. /**
  24. * convert an input date to a mySQL date
  25. *
  26. * @param string $date
  27. * @param string $input_format
  28. * @return mySQL date string
  29. */
  30. static function convertToMySQLDate($date, $input_format = "%d/%m/%Y")
  31. {
  32. $arr = explode(" ", $input_format, 2);
  33. $out_format = "%Y-%m-%d";
  34. // if $date do not contain time, the format should be removed time
  35. if (count(explode(" ", $date, 2)) == 1)
  36. {
  37. $input_format = $arr[0];
  38. }
  39. if (count($arr) == 2)
  40. {
  41. $out_format = $out_format." ".$arr[1];
  42. }
  43. $date_arr = TVC_DateTime::parseDate($date,$input_format);
  44. if ($date_arr)
  45. {
  46. return TVC_DateTime::formatDate($date_arr, $out_format);
  47. }
  48. return false;
  49. }
  50. function convertMySQLDateToOtherFormat($date, $out_format = "%d/%m/%Y")
  51. {
  52. $arr = explode(" ", $out_format, 2);
  53. $input_format = "%Y-%m-%d";
  54. if (count($arr) == 2)
  55. {
  56. $input_format = $input_format." ".$arr[1];
  57. }
  58. $date_arr = TVC_DateTime::parseDate($date, $input_format);
  59. if ($date_arr)
  60. {
  61. return TVC_DateTime::formatDate($date_arr, $out_format);
  62. }
  63. return false;
  64. }
  65. /**
  66. * convert a date ('Y-m-d H:i:s') from a time zone to other time zone
  67. *
  68. * @param string $date is a date in string format
  69. * @return string $convert_date is a date in string format has been converted to new time zone
  70. */
  71. public static function convertToOtherTimeZone($date, $from_time_zone, $to_time_zone)
  72. {
  73. if (strtolower($from_time_zone) == strtolower($to_time_zone)) {
  74. return $date;
  75. }
  76. $fromTimeZone = timezone_open($from_time_zone);
  77. $toTimeZone = timezone_open($to_time_zone);
  78. $convertDate = date_create($date, $fromTimeZone);
  79. date_timezone_set($convertDate, $toTimeZone);
  80. if ($convertDate)
  81. {
  82. return date_format($convertDate, 'Y-m-d H:i:s');
  83. }
  84. else
  85. {
  86. return $date;
  87. }
  88. }
  89. /**
  90. * subtract a date from number day
  91. *
  92. * @param string $date
  93. * @param int $numday number of day that you want to subtract
  94. * @param string $input_format
  95. * @return string date after subtract
  96. */
  97. function subtractDate($date, $numday = 1, $input_format = "%d/%m/%Y")
  98. {
  99. $date_arr = TVC_DateTime::parseDate($date,$input_format);
  100. $date_int = mktime(0,0,0,$date_arr['month'], $date_arr['day'], $date_arr['year']);
  101. $date_int = $date_int - $numday * 86400;
  102. $input_format = str_replace('%','',$input_format);
  103. return date($input_format, $date_int);
  104. }
  105. /**
  106. * add one or many day to a date
  107. *
  108. * @param string $date
  109. * @param int $numday number of day that you want to add
  110. * @param string $input_format
  111. * @return unknown
  112. */
  113. function addDate($date, $numday = 1, $input_format = "%d/%m/%Y")
  114. {
  115. $date_arr = TVC_DateTime::parseDate($date,$input_format);
  116. $date_int = mktime(0,0,0,$date_arr['month'], $date_arr['day'], $date_arr['year']);
  117. $date_int = $date_int + $numday * 86400;
  118. $input_format = str_replace('%','',$input_format);
  119. return date($input_format, $date_int);
  120. }
  121. /**
  122. * compare 2 date
  123. * @param day1 format as mysql date
  124. * @param day2
  125. * @return:
  126. * 0 : equal
  127. * 1 : day1 greater than day2
  128. * 2 : day2 greater than day1
  129. */
  130. static function compareDate($day1, $day2, $input_format = '%d/%m/%Y')
  131. {
  132. $day1_arr = TVC_DateTime::parseDate($day1,$input_format);
  133. $day2_arr = TVC_DateTime::parseDate($day2,$input_format);
  134. $day1 = mktime(0,0,0,$day1_arr['month'],$day1_arr['day'],$day1_arr['year']);
  135. $day2 = mktime(0,0,0,$day2_arr['month'],$day2_arr['day'],$day2_arr['year']);
  136. if ($day1 == $day2)
  137. {
  138. return 0;
  139. }
  140. elseif ($day1 > $day2)
  141. {
  142. return 1;
  143. }
  144. return 2;
  145. }
  146. /**
  147. * check date is valid
  148. *
  149. * @param string $date
  150. * @param $format
  151. * @return unknown
  152. */
  153. static function isValidDate($date,$input_format = "%d/%m/%Y")
  154. {
  155. $date_arr = TVC_DateTime::parseDate($date, $input_format);
  156. if ($date_arr)
  157. {
  158. return checkdate($date_arr['month'], $date_arr['day'], $date_arr['year']);
  159. }
  160. return false;
  161. }
  162. /**
  163. * check time is valid
  164. *
  165. * @param string $time
  166. * @param $format
  167. * @return unknown
  168. */
  169. static function isValidTime($time, $input_format = "%H:%i:%s")
  170. {
  171. if ($input_format == "%H:%i:%s" || $input_format == "%H:%i")
  172. {
  173. $arr = explode(':', $time);
  174. $count = count($arr);
  175. if ($count != 2 && $count != 3)
  176. {
  177. return false;
  178. }
  179. list($hour, $minute) = $arr;
  180. if ($count == 3)
  181. {
  182. $second = $arr[2];
  183. }
  184. if ( !(isset($hour) && $hour >= 0 && $hour <= 23) )
  185. {
  186. return false;
  187. }
  188. if ( !(isset($minute) && $minute >= 0 && $minute <= 59) )
  189. {
  190. return false;
  191. }
  192. if ( isset($second) && !($second >= 0 && $second <= 59) )
  193. {
  194. return false;
  195. }
  196. return true;
  197. }
  198. return false;
  199. }
  200. /**
  201. * check datetime is valid
  202. *
  203. * @param string $datetime
  204. * @param $format
  205. * @return unknown
  206. */
  207. static function isValidDateTime($datetime, $input_format = "%d/%m/%Y %H:%i:%s")
  208. {
  209. $date_parts = explode(" ", $datetime, 2);
  210. $date = $date_parts[0];
  211. $format_parts = explode(" ", $input_format, 2);
  212. $date_format = $format_parts[0];
  213. if (count($format_parts) > 1)
  214. {
  215. $time_format = $format_parts[1];
  216. }
  217. if (count($date_parts) == 1)
  218. {
  219. return self::isValidDate($date, $date_format);
  220. }
  221. else if (count($date_parts) == 2)
  222. {
  223. $time = $date_parts[1];
  224. if (!self::isValidDate($date, $date_format))
  225. {
  226. return false;
  227. }
  228. if (isset($time_format))
  229. {
  230. return self::isValidTime($time, $time_format);
  231. }
  232. else
  233. {
  234. return self::isValidTime($time);
  235. }
  236. }
  237. }
  238. /**
  239. * check timezone is valid
  240. *
  241. * @param string $time_zone
  242. * @return bool true if the timezone is valid, else return false
  243. */
  244. static function isValidTimeZone($time_zone)
  245. {
  246. $tz = timezone_open($time_zone);
  247. if (!$tz)
  248. {
  249. return false;
  250. }
  251. return true;
  252. }
  253. /**
  254. * check whether or not current value is a positive whole integer
  255. * @param string $value
  256. * @return boolean
  257. */
  258. static function isPositiveInteger($value)
  259. {
  260. return is_numeric($value) ? ( (intval($value) == $value) && ($value >= 0) ) : false;
  261. }
  262. /**
  263. * check whether or not current value is a whole integer
  264. * @param string $value
  265. * @return boolean
  266. */
  267. static function isInteger($value)
  268. {
  269. return preg_match("/^[-+]?\b\d+\b$/", $value);
  270. }
  271. /**
  272. * formats a floating point number string in decimal notation, supports signed floats,
  273. * also supports non-standard formatting e.g. 0.2e+2 for 20
  274. * e.g. '1.6E+6' to '1600000', '-4.566e-12' to '-0.000000000004566', '+34e+10' to '340000000000'
  275. * @param string $float_str
  276. */
  277. static function floatToString($float_str)
  278. {
  279. // make sure its a standard php float string (i.e. change 0.2e+2 to 20)
  280. // php will automatically format floats decimally if they are within a certain range
  281. $float_str = (string)((float)($float_str));
  282. // if there is an E in the float string
  283. if(($pos = strpos(strtolower($float_str), 'e')) !== false)
  284. {
  285. // get either side of the E, e.g. 1.6E+6 => exp E+6, num 1.6
  286. $exp = substr($float_str, $pos+1);
  287. $num = substr($float_str, 0, $pos);
  288. // strip off num sign, if there is one, and leave it off if its + (not required)
  289. if((($num_sign = $num[0]) === '+') || ($num_sign === '-')) $num = substr($num, 1);
  290. else $num_sign = '';
  291. if($num_sign === '+') $num_sign = '';
  292. // strip off exponential sign ('+' or '-' as in 'E+6') if there is one, otherwise throw error, e.g. E+6 => '+'
  293. if((($exp_sign = $exp[0]) === '+') || ($exp_sign === '-')) $exp = substr($exp, 1);
  294. else trigger_error("Could not convert exponential notation to decimal notation: invalid float string '$float_str'", E_USER_ERROR);
  295. // 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
  296. $right_dec_places = (($dec_pos = strpos($num, '.')) === false) ? 0 : strlen(substr($num, $dec_pos+1));
  297. // 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
  298. $left_dec_places = ($dec_pos === false) ? strlen($num) : strlen(substr($num, 0, $dec_pos));
  299. // work out number of zeros from exp, exp sign and dec places, e.g. exp 6, exp sign +, dec places 1 => num zeros 5
  300. if($exp_sign === '+') $num_zeros = $exp - $right_dec_places;
  301. else $num_zeros = $exp - $left_dec_places;
  302. // build a string with $num_zeros zeros, e.g. '0' 5 times => '00000'
  303. $zeros = str_pad('', $num_zeros, '0');
  304. // strip decimal from num, e.g. 1.6 => 16
  305. if($dec_pos !== false) $num = str_replace('.', '', $num);
  306. // if positive exponent, return like 1600000
  307. if($exp_sign === '+') return $num_sign.$num.$zeros;
  308. // if negative exponent, return like 0.0000016
  309. else return $num_sign.'0.'.$zeros.$num;
  310. }
  311. // otherwise, assume already in decimal notation and return
  312. else return $float_str;
  313. }
  314. /**
  315. * compare two float with specified number of digits after dot character (.)
  316. *
  317. * @param float $a float1
  318. * @param float $b float2
  319. * @param integer $decimals number of digits after dot character (.)
  320. */
  321. static function isFloatEqual($a, $b, $decimals = 0)
  322. {
  323. if (!is_int($decimals) || $decimals < 0){
  324. $decimals = 10;
  325. }
  326. return sprintf('%01.'.$decimals.'f',$a)==sprintf('%01.'.$decimals.'f',$b);
  327. }
  328. /**
  329. * compare two string which are applied multilanguage format
  330. *
  331. * @param String $souce_str source string
  332. * @param String $des_str destination string
  333. * @param array $arr_lang eg: 'en', 'fr','vn'
  334. */
  335. static function isI18nStringEquals($source_str, $des_str, $arr_lang = null)
  336. {
  337. if(!$arr_lang)
  338. {
  339. $arr_lang = TVC_Config::get('I18N','AUTHORIZED_LANGUAGES');
  340. }
  341. $lang_num = count($arr_lang);
  342. $preg_arr = array();
  343. if($source_str != "" && $des_str !="")
  344. {
  345. for($i = 0; $i < $lang_num; $i++)
  346. {
  347. $preg_arr = '/<'.$arr_lang[$i].'>([^<]*)<\/'.$arr_lang[$i].'>/';
  348. // get data from destination string
  349. preg_match($preg_arr, $des_str, $des_matches);
  350. // get data from source string
  351. preg_match($preg_arr, $source_str, $source_matches);
  352. if(count($source_matches) > 0 && count($des_matches) > 0) {
  353. str_replace(array('&lt;','&gt;'), array('<','>'), $des_matches[1]);
  354. str_replace(array('&lt;','&gt;'), array('<','>'), $source_matches[1]);
  355. if(strcasecmp($source_matches[1], $des_matches[1]) == 0 )
  356. {
  357. return true;
  358. }
  359. }
  360. }
  361. }
  362. return false;
  363. }
  364. /**
  365. * check string satisfy multilanguage format(eg. <en>xxxx</en><fr>yyyyy</fr>)
  366. *
  367. * @param string $str_source string is checked
  368. * @param array $arr_lang array language
  369. */
  370. static function isI18nStringFormat($source_str, $arr_lang = null)
  371. {
  372. if(!$arr_lang)
  373. {
  374. $arr_lang = TVC_Config::get('I18N','AUTHORIZED_LANGUAGES');
  375. }
  376. $lang_num = count($arr_lang);
  377. $str_src = $source_str;
  378. $preg_arr = array();
  379. if($str_src != "")
  380. {
  381. for($i = 0; $i < $lang_num; $i++)
  382. {
  383. $preg_arr = '/<'.$arr_lang[$i].'>([^<]*)<\/'.$arr_lang[$i].'>/';
  384. // get data from source string
  385. preg_match($preg_arr, $str_src, $source_matches);
  386. if(count($source_matches) > 0) {
  387. $str_src = str_replace($source_matches[0], '', $str_src);
  388. }
  389. if($i == $lang_num - 1)
  390. {
  391. if(strlen(trim($str_src))>0)
  392. {
  393. return false;
  394. }
  395. }
  396. }
  397. }
  398. return true;
  399. }
  400. /**
  401. * Purpose: Extract a specific language translation from a tag encoded language chain<br>
  402. * Input:<br>
  403. * - string: input language chain in format
  404. * "<en>english</en><fr>anglais</fr>"
  405. * - language_code : the language code to extract, if none specified, we will take
  406. * the one of TVC_Multilanguage
  407. * - use_default_on_fail : boolean. If TRUE, we will try to extract the default
  408. * language translation in case of failure. Otherwise, we just return an
  409. * empty string on failure.
  410. * @author Cl?確ent Nodet <clement dot nodet at gmail dot com>
  411. * @param string
  412. * @param string
  413. * @return string|void
  414. * @uses smarty_make_timestamp()
  415. */
  416. public static function getI18n($string, $language_code = '', $use_default_on_fail = TRUE)
  417. {
  418. if ($language_code == '')
  419. {
  420. $language_code = TVC_Multilanguage::getLanguage();
  421. }
  422. // Try to find the chain in the string
  423. if (preg_match('/<'.$language_code.'>([^<]*)<\/'.$language_code.'>/',$string,$matches) > 0)
  424. {
  425. return str_replace(array('&lt;','&gt;'),array('<','>'),$matches[1]);
  426. }
  427. else
  428. {
  429. // We couldn't find it, do we need to try again with the default language?
  430. if ($use_default_on_fail and $language_code != TVC_Config::get('I18N','DEFAULT_LANGUAGE'))
  431. {
  432. return Utils::getI18n($string,TVC_Config::get('I18N','DEFAULT_LANGUAGE'),FALSE);
  433. }
  434. else
  435. {
  436. return '';
  437. }
  438. }
  439. }
  440. /**
  441. * check max length of string which is applied i18n format
  442. * the function will check the length of string between each start tag and end tag(eg. <en>xxxx</en>...)
  443. * if a string have length > max_length, the alert message box will display
  444. * @param string $source_str: string is checked
  445. * @param integer $max_length: max length of string
  446. * @param array $arr_lang: array of languages
  447. * @return boolean true if length of string less than or equal max length
  448. */
  449. static function isValidLengthI18nString($source_str, $max_length, $arr_lang = null)
  450. {
  451. if(!$arr_lang)
  452. {
  453. $arr_lang = TVC_Config::get('I18N','AUTHORIZED_LANGUAGES');
  454. }
  455. $lang_num = count($arr_lang);
  456. for ($i = 0; $i < $lang_num; $i ++)
  457. {
  458. $pattern = '/<'.$arr_lang[$i].'>([^<]*)<\/'.$arr_lang[$i].'>/';
  459. preg_match($pattern, $source_str, $source_matches);
  460. if (count($source_matches) > 0)
  461. {
  462. if (strlen(trim($source_matches[1])) > $max_length)
  463. {
  464. return false;
  465. }
  466. }
  467. }
  468. return true;
  469. }
  470. /**
  471. * Check empty multilanguge string(eg.<en>string</string)...
  472. *
  473. * @param string $source_str
  474. * @param array $arr_lang
  475. */
  476. static function isEmptyI18nString($source_str, $arr_lang = null)
  477. {
  478. if(!$arr_lang)
  479. {
  480. $arr_lang = TVC_Config::get('I18N','AUTHORIZED_LANGUAGES');
  481. }
  482. $lang_num = count($arr_lang);
  483. for ($i = 0; $i < $lang_num; $i ++)
  484. {
  485. $pattern = '/<'.$arr_lang[$i].'>([^<]*)<\/'.$arr_lang[$i].'>/';
  486. preg_match($pattern, $source_str, $source_matches);
  487. /*var_dump($source_matches);
  488. die;*/
  489. if (count($source_matches) > 0)
  490. {
  491. if (strlen(trim($source_matches[1])) == 0)
  492. {
  493. return false;
  494. }
  495. }
  496. }
  497. return true;
  498. }
  499. public function downloadFile($file_name, $dir = "")
  500. {
  501. if(!file_exists($dir.$file_name))
  502. {
  503. exit("File is not available");
  504. }
  505. // set headers
  506. header("Pragma: public");
  507. header("Expires: 0");
  508. header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
  509. header("Cache-Control: private");
  510. header("Content-Description: File Transfer");
  511. header("Content-Disposition: attachment; filename=\"".basename("$file_name")."\"");
  512. header("Content-Transfer-Encoding: binary");
  513. header("Content-Length: " . @filesize("$dir.$file_name"));
  514. @readfile("$dir.file_name");
  515. die();
  516. }
  517. static function displayResizeImage($image_file, $max_width, $max_height, $path, $img_url, $addslases = 0)
  518. {
  519. if($image_file && file_exists($path."/".$image_file))
  520. {
  521. $img_info = getimagesize($path."/".$image_file);
  522. $width = $img_info[0];
  523. $height = $img_info[1];
  524. $width_ratio = $max_width/$width;
  525. $height_ratio = $max_height/$height;
  526. $ratio = ($width_ratio < $height_ratio) ? $width_ratio : $height_ratio;
  527. $ratio = ($ratio < 1) ? $ratio : 1;
  528. if($addslases != 0)
  529. {
  530. echo addslashes("<img src='$img_url/$image_file' width='".intval($width*$ratio)."' height='".intval($height*$ratio)."' style='padding-top:2px'/>");
  531. }
  532. else
  533. {
  534. echo "<img src='$img_url/$image_file' width='".intval($width*$ratio)."' height='".intval($height*$ratio)."' style='padding-top:2px'/>";
  535. }
  536. }
  537. }
  538. static function displayVisualImage($image, $addslases = 0)
  539. {
  540. if(!Parameter::$params['VISUAL_IMAGE_MAX_WIDTH'] || !Parameter::$params['VISUAL_IMAGE_MAX_HEIGHT'])
  541. {
  542. Parameter::loadAllParameters();
  543. }
  544. $width = Parameter::$params['VISUAL_IMAGE_MAX_WIDTH'];
  545. $height = Parameter::$params['VISUAL_IMAGE_MAX_HEIGHT'];
  546. Utils::displayResizeImage($image, $width, $height, Format::getFolderImage(), STATIC_COMPONENT_URL_FILE."/".Format::IMAGE_URL, $addslases);
  547. }
  548. static function displayTechnicalDatalImage($image, $addslases = 0)
  549. {
  550. $width = Parameter::IMAGE_MAX_WIDTH;
  551. $height = Parameter::IMAGE_MAX_HEIGHT;
  552. Utils::displayResizeImage($image, $width, $height, TechnicalDataImage::getFolderImage(), STATIC_COMPONENT_URL_FILE."/".TechnicalDataImage::IMAGE_URL, $addslases);
  553. }
  554. public static function getCurrentTimeSlot($constraint = "now")
  555. {
  556. $cur_time = strtotime($constraint);
  557. $cur_m = ((date('i', $cur_time) < 30) ? "00" : "30");
  558. $cur_ymd = date('Y-m-d H', $cur_time);
  559. $cur_datetime = $cur_ymd . ":" . $cur_m . ":00";
  560. return $cur_datetime;
  561. }
  562. /*
  563. ============================
  564. QuickCaptcha 1.0 - A bot-thwarting text-in-image web tool.
  565. Copyright (c) 2006 Web 1 Marketing, Inc.
  566. This program is free software; you can redistribute it and/or
  567. modify it under the terms of the GNU General Public License
  568. as published by the Free Software Foundation; either version 2
  569. of the License, or (at your option) any later version.
  570. This program is distributed in the hope that it will be useful,
  571. but WITHOUT ANY WARRANTY; without even the implied warranty of
  572. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  573. GNU General Public License for more details.
  574. ============================
  575. See settings.php for common settings. You shouldn't need to change
  576. anything in this file.
  577. ============================
  578. */
  579. public function generateCAPTCHA($length=6)
  580. {
  581. $acceptedChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ123456789';
  582. // A value between 0 and 100 describing how much color overlap
  583. // there is between text and other objects. Lower is more
  584. // secure against bots, but also harder to read.
  585. $contrast = 20;
  586. // Various obfuscation techniques.
  587. $num_polygons = 2; // Number of triangles to draw. 0 = none
  588. $num_ellipses = 6; // Number of ellipses to draw. 0 = none
  589. $num_lines = 10; // Number of lines to draw. 0 = none
  590. $num_dots = 50; // Number of dots to draw. 0 = none
  591. $min_thickness = 2; // Minimum thickness in pixels of lines
  592. $max_thickness = 8; // Maximum thickness in pixles of lines
  593. $min_radius = 1; // Minimum radius in pixels of ellipses
  594. $max_radius = 15; // Maximum radius in pixels of ellipses
  595. // How opaque should the obscuring objects be. 0 is opaque, 127
  596. // is transparent.
  597. $object_alpha = 75;
  598. // Keep #'s reasonable.
  599. $min_thickness = max(1,$min_thickness);
  600. $max_thickness = min(20,$max_thickness);
  601. // Make radii into height/width
  602. $min_radius *= 2;
  603. $max_radius *= 2;
  604. // Renormalize contrast
  605. $contrast = 255 * ($contrast / 100.0);
  606. $o_contrast = 1.3 * $contrast;
  607. $width = 11 * imagefontwidth (5);
  608. $height = 2.5 * imagefontheight (5);
  609. $image = imagecreatetruecolor ($width, $height);
  610. imagealphablending($image, true);
  611. $black = imagecolorallocatealpha($image,0,0,0,0);
  612. // Build the validation string
  613. $max = strlen($acceptedChars)-1;
  614. $password = NULL;
  615. for($i=0; $i < $length; $i++) {
  616. $cnum[$i] = $acceptedChars{mt_rand(0, $max)};
  617. $password .= $cnum[$i];
  618. }
  619. // Add string to image
  620. $rotated = imagecreatetruecolor (70, 70);
  621. $x = 0;
  622. for ($i = 0; $i < $length; $i++) {
  623. $buffer = imagecreatetruecolor (20, 20);
  624. $buffer2 = imagecreatetruecolor (40, 40);
  625. // Get a random color
  626. $red = mt_rand(0,255);
  627. $green = mt_rand(0,255);
  628. $blue = 255 - sqrt($red * $red + $green * $green);
  629. $color = imagecolorallocate ($buffer, $red, $green, $blue);
  630. // Create character
  631. imagestring($buffer, 5, 0, 0, $cnum[$i], $color);
  632. // Resize character
  633. imagecopyresized ($buffer2, $buffer, 0, 0, 0, 0, 15 + mt_rand(0,12), 25 + mt_rand(0,12), 20, 20);
  634. // Rotate characters a little
  635. //$rotated = imagerotate($buffer2, mt_rand(-25, 25),imagecolorallocatealpha($buffer2,0,0,0,0));
  636. $rotated = $buffer2;
  637. imagecolortransparent ($rotated, imagecolorallocatealpha($rotated,0,0,0,0));
  638. // Move characters around a little
  639. $y = mt_rand(1, 3);
  640. $x += mt_rand(2, 6);
  641. imagecopymerge ($image, $rotated, $x, $y, 0, 0, 40, 40, 100);
  642. $x += 11;
  643. imagedestroy ($buffer);
  644. imagedestroy ($buffer2);
  645. }
  646. // Draw polygons
  647. if ($num_polygons > 0) for ($i = 0; $i < $num_polygons; $i++) {
  648. $vertices = array (
  649. mt_rand(-0.25*$width,$width*1.25),mt_rand(-0.25*$width,$width*1.25),
  650. mt_rand(-0.25*$width,$width*1.25),mt_rand(-0.25*$width,$width*1.25),
  651. mt_rand(-0.25*$width,$width*1.25),mt_rand(-0.25*$width,$width*1.25)
  652. );
  653. $color = imagecolorallocatealpha ($image, mt_rand(0,$o_contrast), mt_rand(0,$o_contrast), mt_rand(0,$o_contrast), $object_alpha);
  654. imagefilledpolygon($image, $vertices, 3, $color);
  655. }
  656. // Draw random circles
  657. if ($num_ellipses > 0) for ($i = 0; $i < $num_ellipses; $i++) {
  658. $x1 = mt_rand(0,$width);
  659. $y1 = mt_rand(0,$height);
  660. $color = imagecolorallocatealpha ($image, mt_rand(0,$o_contrast), mt_rand(0,$o_contrast), mt_rand(0,$o_contrast), $object_alpha);
  661. // $color = imagecolorallocate($image, mt_rand(0,$o_contrast), mt_rand(0,$o_contrast), mt_rand(0,$o_contrast));
  662. imagefilledellipse($image, $x1, $y1, mt_rand($min_radius,$max_radius), mt_rand($min_radius,$max_radius), $color);
  663. }
  664. // Draw random lines
  665. if ($num_lines > 0) for ($i = 0; $i < $num_lines; $i++) {
  666. $x1 = mt_rand(-$width*0.25,$width*1.25);
  667. $y1 = mt_rand(-$height*0.25,$height*1.25);
  668. $x2 = mt_rand(-$width*0.25,$width*1.25);
  669. $y2 = mt_rand(-$height*0.25,$height*1.25);
  670. $color = imagecolorallocatealpha ($image, mt_rand(0,$o_contrast), mt_rand(0,$o_contrast), mt_rand(0,$o_contrast), $object_alpha);
  671. imagesetthickness ($image, mt_rand($min_thickness,$max_thickness));
  672. imageline($image, $x1, $y1, $x2, $y2 , $color);
  673. }
  674. // Draw random dots
  675. if ($num_dots > 0) for ($i = 0; $i < $num_dots; $i++) {
  676. $x1 = mt_rand(0,$width);
  677. $y1 = mt_rand(0,$height);
  678. $color = imagecolorallocatealpha ($image, mt_rand(0,$o_contrast), mt_rand(0,$o_contrast), mt_rand(0,$o_contrast),$object_alpha);
  679. imagesetpixel($image, $x1, $y1, $color);
  680. }
  681. $_SESSION['captcha'] = $password;
  682. header('Content-type: image/png');
  683. imagepng($image);
  684. imagedestroy($image);
  685. }
  686. public function validateCaptcha($captcha_post)
  687. {
  688. $error = "";
  689. if(!isset($captcha_post) || $captcha_post == "" || $captcha_post==null)
  690. {
  691. $error = '_MSG_CODE_VERIFICATION_IS_EMPTY';
  692. }
  693. else if($captcha_post != $_SESSION['captcha'])
  694. {
  695. $error = '_MSG_CODE_VERIFICATION_NOT_MATCH';
  696. }
  697. return $error;
  698. }
  699. public function generateNews()
  700. {
  701. $language = TVC_MultiLanguage::getLanguage();
  702. $dom = new DOMDocument;
  703. if($language=='vi')
  704. {
  705. $content = @file_get_contents(NEWS_VI_SOURCE);
  706. $max_news_get = MAX_NEWS_VI_GET;
  707. }
  708. else
  709. {
  710. $content = @file_get_contents(NEWS_EN_SOURCE);
  711. $max_news_get = MAX_NEWS_EN_GET;
  712. }
  713. if($content)
  714. {
  715. $dom->loadXML($content);
  716. $s = simplexml_import_dom($dom);
  717. for($i=0;$i<$max_news_get;$i++)
  718. {
  719. $title = $s->channel->item[$i]->title;
  720. $link = $s->channel->item[$i]->link;
  721. echo "<p class='button rss_image'><a href='$link'><span>$title</span></a></p>";
  722. }
  723. }
  724. else
  725. {
  726. return false;
  727. }
  728. return true;
  729. }
  730. public function encodeFileName($file_name)
  731. {
  732. $f_arr = array();
  733. $f_arr = explode("/",$file_name);
  734. if(count($f_arr)>1)
  735. { $s = "";
  736. for($i=0;$i<count($f_arr)-1;$i++)
  737. {
  738. $s .= ";".$f_arr[$i];
  739. }
  740. return "f/". md5($f_arr[count($f_arr)-1]).(($s!="")?"/s/$s":"");
  741. }
  742. else
  743. {
  744. return "f/". md5($file_name);
  745. }
  746. }
  747. public function encodeId($id)
  748. {
  749. $id_arr = array();
  750. $id_arr = explode("/",$id);
  751. if(count($id_arr)>1)
  752. { $s = "";
  753. for($i=0;$i<count($id_arr)-1;$i++)
  754. {
  755. $s .= ";".$id_arr[$i];
  756. }
  757. return "id/". md5($id_arr[count($id_arr)-1]).(($s!="")?"/id/$s":"");
  758. }
  759. else
  760. {
  761. return "id/". md5($id);
  762. }
  763. }
  764. /**
  765. * set multilanguge on main domain
  766. * @param $language
  767. * @return unknown_type
  768. */
  769. public function setI18nOnMaindomain($language)
  770. {
  771. setcookie("language", $language, time() + 3600*24*30, "/", DOMAIN);
  772. }
  773. /**
  774. * unset multilanguage on sub domain
  775. * @return unknown_type
  776. */
  777. public function resetI18nOnSubdomain()
  778. {
  779. // unset cookies on sub domain
  780. setcookie("language", "", time() - 3600*24*30, "/", ADMIN_DOMAIN);
  781. setcookie("language", "", time() - 3600*24*30, "/", MASTER_DOMAIN);
  782. setcookie("language", "", time() - 3600*24*30, "/", PUBLIC_DOMAIN);
  783. setcookie("language", "", time() - 3600*24*30, "/", HOME_DOMAIN);
  784. }
  785. public function resetAccessAuthentical()
  786. {
  787. if(isset($_COOKIE['from_other_site']))
  788. {
  789. setcookie("from_other_site", "", time() - 3600*24*30, "/", DOMAIN);
  790. }
  791. if(isset($_COOKIE['from_public_site']))
  792. {
  793. setcookie("from_public_site", "", time() - 3600*24*30, "/", DOMAIN);
  794. }
  795. }
  796. public static function mmsort($result, $subkey, $isUseI18n = true)
  797. {
  798. $array = array();
  799. $notInclude = array('__table', '_database', '_DB_DataObject_version', 'N', '_database_dsn_md5', '_DB_resultid');
  800. $j = 0;
  801. while($result->fetch()) {
  802. foreach($result as $i => $val) {
  803. if(strlen($val) > 0 && !in_array($i, $notInclude)) {
  804. if($i == $subkey)
  805. $array[$j][$i] = $isUseI18n ? Utils::getI18n($val) : $val;
  806. else $array[$j][$i] = $val;
  807. }
  808. }
  809. $j++;
  810. }
  811. return Utils::subval_sort($array, $subkey);
  812. }
  813. public static function subval_sort($a,$subkey)
  814. {
  815. if(!is_array($a) || count($a) == 0) {
  816. return array();
  817. }
  818. foreach($a as $k=>$v) {
  819. $b[$k] = strtolower($v[$subkey]);
  820. }
  821. asort($b);
  822. foreach($b as $key=>$val) {
  823. $c[$key] = $a[$key];
  824. }
  825. return $c;
  826. }
  827. //Utils::setIniLang()
  828. public function setIniLang($section = false)
  829. {
  830. $template_dir = realpath(TVC_Config::get('FS','TEMPLATE_DIR'));
  831. $misc_ini_file = $template_dir . "/misc.ini";
  832. $ini_array = parse_ini($misc_ini_file);
  833. $section = !$section ? TVC_MultiLanguage::getLanguage() : $section;
  834. if( isset( $ini_array[ $section ] ) ) {
  835. foreach($ini_array[ $section ] as $constant => $value) {
  836. if(!defined($constant)) {
  837. define($constant, $value);
  838. }
  839. }
  840. }
  841. }
  842. function dateRangeArray($start, $end, $format = 'Y-m-d') {
  843. $range = array();
  844. if (is_string($start) === true) $start = strtotime($start);
  845. if (is_string($end) === true ) $end = strtotime($end);
  846. do {
  847. $range[] = date($format, $start);
  848. $start = strtotime("+ 1 day", $start);
  849. } while($start <= $end);
  850. return $range;
  851. }
  852. }
  853. function parse_ini ( $filepath ) {
  854. $ini = file( $filepath );
  855. if ( count( $ini ) == 0 ) { return array(); }
  856. $sections = array();
  857. $values = array();
  858. $globals = array();
  859. $i = 0;
  860. foreach( $ini as $line ){
  861. $line = trim( $line );
  862. // Comments
  863. if ( $line == '' || $line{0} == ';' || preg_match("|(^\/\/)|U", $line) ) { continue; }
  864. // Sections
  865. if ( $line{0} == '[' ) {
  866. $sections[] = substr( $line, 1, -1 );
  867. $i++;
  868. continue;
  869. }
  870. // Key-value pair
  871. list( $key, $value ) = explode( '=', $line, 2 );
  872. $key = trim( $key );
  873. $value = trim( $value );
  874. if ( $i == 0 ) {
  875. // Array values
  876. if ( substr( $line, -1, 2 ) == '[]' ) {
  877. $globals[ $key ][] = $value;
  878. } else {
  879. $globals[ $key ] = $value;
  880. }
  881. } else {
  882. // Array values
  883. if ( substr( $line, -1, 2 ) == '[]' ) {
  884. $values[ $i - 1 ][ $key ][] = $value;
  885. } else {
  886. $values[ $i - 1 ][ $key ] = $value;
  887. }
  888. }
  889. }
  890. for( $j=0; $j<$i; $j++ ) {
  891. $result[ $sections[ $j ] ] = $values[ $j ];
  892. }
  893. return $result + $globals;
  894. }