PageRenderTime 31ms CodeModel.GetById 15ms RepoModel.GetById 1ms app.codeStats 0ms

/includes/functions.php

https://bitbucket.org/emagid/cognizant2
PHP | 959 lines | 853 code | 33 blank | 73 comment | 22 complexity | ab29c51781f9a1409e65309770b93a6d MD5 | raw file
Possible License(s): LGPL-2.1, MPL-2.0-no-copyleft-exception
  1. <?php
  2. /**Format date and time functions*/
  3. function db_to_time($datetime = ""){
  4. $unixdatetime = strtotime($datetime);
  5. $date_time = strftime("%m-%d-%Y | %I:%M %p", $unixdatetime);
  6. return strftime($date_time, '0 ');
  7. }//close db_to_time
  8. function db_to_date($datetime = ""){
  9. $unixdatetime = strtotime($datetime);
  10. return strftime("%B %d, %Y", $unixdatetime);
  11. }//close db_to_time
  12. function time_to_db($time=""){
  13. if($time == ""){$time = time();}
  14. $mysql_datetime = strftime("%Y-%m-%d %H:%M:%S", $time);
  15. return $mysql_datetime;
  16. }//close time to db
  17. function date_to_db($time=""){
  18. if($time == ""){$time = time();}
  19. $mysql_date = strftime("%Y-%m-%d", $time);
  20. return $mysql_date;
  21. }//close date to db
  22. /**
  23. * Function to calculate the same day one month in the future.
  24. *
  25. * This is necessary because some months don't have 29, 30, or 31 days. If the
  26. * next month doesn't have as many days as this month, the anniversary will be
  27. * moved up to the last day of the next month.
  28. *
  29. * @param $start_date (optional)
  30. * UNIX timestamp of the date from which you'd like to start. If not given,
  31. * will default to current time.
  32. *
  33. * @return $timestamp
  34. * UNIX timestamp of the same day or last day of next month.
  35. */
  36. function jjg_calculate_next_month($start_date = FALSE) {
  37. if ($start_date) {
  38. $now = $start_date; // Use supplied start date.
  39. } else {
  40. $now = time(); // Use current time.
  41. }
  42. // Get the current month (as integer).
  43. $current_month = date('n', $now);
  44. // If the we're in Dec (12), set current month to Jan (1), add 1 to year.
  45. if ($current_month == 12) {
  46. $next_month = 1;
  47. $plus_one_month = mktime(0, 0, 0, 1, date('d', $now), date('Y', $now) + 1);
  48. }
  49. // Otherwise, add a month to the next month and calculate the date.
  50. else {
  51. $next_month = $current_month + 1;
  52. $plus_one_month = mktime(0, 0, 0, date('m', $now) + 1, date('d', $now), date('Y', $now));
  53. }
  54. $i = 1;
  55. // Go back a day at a time until we get the last day next month.
  56. while (date('n', $plus_one_month) != $next_month) {
  57. $plus_one_month = mktime(0, 0, 0, date('m', $now) + 1, date('d', $now) - $i, date('Y', $now));
  58. $i++;
  59. }
  60. return $plus_one_month;
  61. }
  62. /**
  63. * Function to calculate the same day one year in the future.
  64. *
  65. * @param $start_date (optional)
  66. * UNIX timestamp of the date from which you'd like to start. If not given,
  67. * will default to current time.
  68. *
  69. * @return $timestamp
  70. * UNIX timestamp of the same day or last day of next month.
  71. */
  72. function jjg_calculate_next_year($start_date = FALSE) {
  73. if ($start_date) {
  74. $now = $start_date; // Use supplied start date.
  75. } else {
  76. $now = time(); // Use current time.
  77. }
  78. $month = date('m', $now);
  79. $day = date('d', $now);
  80. $year = date('Y', $now) + 1;
  81. $plus_one_year = strtotime("$year-$month-$day"); // Use ISO 8601 standard.
  82. return $plus_one_year;
  83. }
  84. /**
  85. * Password hash with crypt
  86. * @param string $info
  87. * @param string $encdata
  88. */
  89. function hasher($info, $encdata = false) {
  90. $strength = "08";
  91. //check password
  92. //if encrypted data (the password in database) is passed, check it against input password ($info)
  93. if ($encdata) {
  94. if (substr($encdata, 0, 60) == crypt($info, "$2a$".$strength."$".substr($encdata, 60))) {
  95. return true;
  96. }else {
  97. return false;
  98. }
  99. }else{
  100. //create new hashed password
  101. //make a salt and hash it with input password, and add salt to end
  102. $salt = "";
  103. for ($i = 0; $i < 22; $i++) {
  104. $salt .= substr("./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", mt_rand(0, 63), 1);
  105. }
  106. //return 82 char string (60 char hash & 22 char salt)
  107. return crypt($info, "$2a$".$strength."$".$salt).$salt;
  108. }
  109. }
  110. /**
  111. * limited output to desired num of words
  112. * @param string $content
  113. * @param number/int $num_words
  114. */
  115. function limited_the_content($content, $num_words = 200){
  116. $stripped_content = strip_tags($content);
  117. $words = explode(' ', $stripped_content);
  118. if(count($words) < $num_words){
  119. echo $stripped_content;
  120. }else{
  121. $words = array_slice($words, 0, $num_words);
  122. //echo implode(' ', $words) . '...';
  123. echo implode(' ', $words);
  124. }//end if
  125. }
  126. /**
  127. * output human readabel status
  128. * @param string/number $status
  129. */
  130. function get_status($status){
  131. switch ($status) {
  132. case 1:
  133. return "activated";
  134. break;
  135. case 0:
  136. return "deactivated";
  137. break;
  138. case 2:
  139. return "quick link";
  140. break;
  141. default:
  142. # code...
  143. break;
  144. }
  145. }
  146. /**
  147. * add a element to the beginning of the array
  148. * @param array $myarray
  149. * @param *** $value
  150. * @param number/int... $position
  151. */
  152. function array_insert($myarray,$value,$position=0){
  153. $fore=($position==0)?array():array_splice($myarray,0,$position);
  154. $fore[]=$value;
  155. $ret=array_merge($fore,$myarray);
  156. return $ret;
  157. }
  158. /////////////////////Get countries and US states
  159. function get_states(){
  160. $states = array(
  161. 'AL' => 'Alabama',
  162. 'AK' => 'Alaska',
  163. 'AZ' => 'Arizona',
  164. 'AR' => 'Arkansas',
  165. 'CA' => 'California',
  166. 'CO' => 'Colorado',
  167. 'CT' => 'Connecticut',
  168. 'DE' => 'Delaware',
  169. 'FL' => 'Florida',
  170. 'GA' => 'Georgia',
  171. 'HI' => 'Hawaii',
  172. 'ID' => 'Idaho',
  173. 'IL' => 'Illinois',
  174. 'IN' => 'Indiana',
  175. 'IA' => 'Iowa',
  176. 'KS' => 'Kansas',
  177. 'KY' => 'Kentucky',
  178. 'LA' => 'Louisiana',
  179. 'ME' => 'Maine',
  180. 'MD' => 'Maryland',
  181. 'MA' => 'Massachusetts',
  182. 'MI' => 'Michigan',
  183. 'MN' => 'Minnesota',
  184. 'MS' => 'Mississippi',
  185. 'MO' => 'Missouri',
  186. 'MT' => 'Montana',
  187. 'NE' => 'Nebraska',
  188. 'NV' => 'Nevada',
  189. 'NH' => 'New Hampshire',
  190. 'NJ' => 'New Jersey',
  191. 'NM' => 'New Mexico',
  192. 'NY' => 'New York',
  193. 'NC' => 'North Carolina',
  194. 'ND' => 'North Dakota',
  195. 'OH' => 'Ohio',
  196. 'OK' => 'Oklahoma',
  197. 'OR' => 'Oregon',
  198. 'PA' => 'Pennsylvania',
  199. 'RI' => 'Rhode Island',
  200. 'SC' => 'South Carolina',
  201. 'SD' => 'South Dakota',
  202. 'TN' => 'Tennessee',
  203. 'TX' => 'Texas',
  204. 'UT' => 'Utah',
  205. 'VT' => 'Vermont',
  206. 'VA' => 'Virginia',
  207. 'WA' => 'Washington',
  208. 'WV' => 'West Virginia',
  209. 'WI' => 'Wisconsin',
  210. 'WY' => 'Wyoming',
  211. 'DC' => 'District of Columbia',
  212. 'GU' => 'Guam',
  213. 'PR' => 'Puerto Rico',
  214. 'VI' => 'Virgin Islands'
  215. );
  216. return $states;
  217. }
  218. function get_countries(){
  219. $countries = array(
  220. 'Afghanistan',
  221. 'Aland Islands',
  222. 'Albania',
  223. 'Algeria',
  224. 'American Samoa',
  225. 'Andorra',
  226. 'Angola',
  227. 'Anguilla',
  228. 'Antarctica',
  229. 'Antigua And Barbuda',
  230. 'Argentina',
  231. 'Armenia',
  232. 'Aruba',
  233. 'Australia',
  234. 'Austria',
  235. 'Azerbaijan',
  236. 'Bahamas',
  237. 'Bahrain',
  238. 'Bangladesh',
  239. 'Barbados',
  240. 'Belarus',
  241. 'Belgium',
  242. 'Belize',
  243. 'Benin',
  244. 'Bermuda',
  245. 'Bhutan',
  246. 'Bolivia',
  247. 'Bosnia And Herzegovina',
  248. 'Botswana',
  249. 'Bouvet Island',
  250. 'Brazil',
  251. 'British Indian Ocean Territory',
  252. 'Brunei Darussalam',
  253. 'Bulgaria',
  254. 'Burkina Faso',
  255. 'Burundi',
  256. 'Cambodia',
  257. 'Cameroon',
  258. 'Canada',
  259. 'Cape Verde',
  260. 'Cayman Islands',
  261. 'Central African Republic',
  262. 'Chad',
  263. 'Chile',
  264. 'China',
  265. 'Christmas Island',
  266. 'Cocos (Keeling) Islands',
  267. 'Colombia',
  268. 'Comoros',
  269. 'Congo',
  270. 'Congo, The Democratic Republic Of The',
  271. 'Cook Islands',
  272. 'Costa Rica',
  273. 'Cote D\'Ivoire',
  274. 'Croatia',
  275. 'Cuba',
  276. 'Cyprus',
  277. 'Czech Republic',
  278. 'Denmark',
  279. 'Djibouti',
  280. 'Dominica',
  281. 'Dominican Republic',
  282. 'Ecuador',
  283. 'Egypt',
  284. 'El Salvador',
  285. 'Equatorial Guinea',
  286. 'Eritrea',
  287. 'Estonia',
  288. 'Ethiopia',
  289. 'Falkland Islands (Malvinas)',
  290. 'Faroe Islands',
  291. 'Fiji',
  292. 'Finland',
  293. 'France',
  294. 'French Guiana',
  295. 'French Polynesia',
  296. 'French Southern Territories',
  297. 'Gabon',
  298. 'Gambia',
  299. 'Georgia',
  300. 'Germany',
  301. 'Ghana',
  302. 'Gibraltar',
  303. 'Greece',
  304. 'Greenland',
  305. 'Grenada',
  306. 'Guadeloupe',
  307. 'Guam',
  308. 'Guatemala',
  309. 'Guernsey',
  310. 'Guinea',
  311. 'Guinea-Bissau',
  312. 'Guyana',
  313. 'Haiti',
  314. 'Heard Island And Mcdonald Islands',
  315. 'Holy See (Vatican City State)',
  316. 'Honduras',
  317. 'Hong Kong',
  318. 'Hungary',
  319. 'Iceland',
  320. 'India',
  321. 'Indonesia',
  322. 'Iran, Islamic Republic Of',
  323. 'Iraq',
  324. 'Ireland',
  325. 'Isle Of Man',
  326. 'Israel',
  327. 'Italy',
  328. 'Jamaica',
  329. 'Japan',
  330. 'Jersey',
  331. 'Jordan',
  332. 'Kazakhstan',
  333. 'Kenya',
  334. 'Kiribati',
  335. 'Korea, Democratic People\'S Republic Of',
  336. 'Korea, Republic Of',
  337. 'Kuwait',
  338. 'Kyrgyzstan',
  339. 'Lao People\'S Democratic Republic',
  340. 'Latvia',
  341. 'Lebanon',
  342. 'Lesotho',
  343. 'Liberia',
  344. 'Libyan Arab Jamahiriya',
  345. 'Liechtenstein',
  346. 'Lithuania',
  347. 'Luxembourg',
  348. 'Macao',
  349. 'Macedonia, The Former Yugoslav Republic Of',
  350. 'Madagascar',
  351. 'Malawi',
  352. 'Malaysia',
  353. 'Maldives',
  354. 'Mali',
  355. 'Malta',
  356. 'Marshall Islands',
  357. 'Martinique',
  358. 'Mauritania',
  359. 'Mauritius',
  360. 'Mayotte',
  361. 'Mexico',
  362. 'Micronesia, Federated States Of',
  363. 'Moldova, Republic Of',
  364. 'Monaco',
  365. 'Mongolia',
  366. 'Montserrat',
  367. 'Morocco',
  368. 'Mozambique',
  369. 'Myanmar',
  370. 'Namibia',
  371. 'Nauru',
  372. 'Nepal',
  373. 'Netherlands',
  374. 'Netherlands Antilles',
  375. 'New Caledonia',
  376. 'New Zealand',
  377. 'Nicaragua',
  378. 'Niger',
  379. 'Nigeria',
  380. 'Niue',
  381. 'Norfolk Island',
  382. 'Northern Mariana Islands',
  383. 'Norway',
  384. 'Oman',
  385. 'Pakistan',
  386. 'Palau',
  387. 'Palestinian Territory, Occupied',
  388. 'Panama',
  389. 'Papua New Guinea',
  390. 'Paraguay',
  391. 'Peru',
  392. 'Philippines',
  393. 'Pitcairn',
  394. 'Poland',
  395. 'Portugal',
  396. 'Puerto Rico',
  397. 'Qatar',
  398. 'Reunion',
  399. 'Romania',
  400. 'Russian Federation',
  401. 'Rwanda',
  402. 'Saint Helena',
  403. 'Saint Kitts And Nevis',
  404. 'Saint Lucia',
  405. 'Saint Pierre And Miquelon',
  406. 'Saint Vincent And The Grenadines',
  407. 'Samoa',
  408. 'San Marino',
  409. 'Sao Tome And Principe',
  410. 'Saudi Arabia',
  411. 'Senegal',
  412. 'Serbia And Montenegro',
  413. 'Seychelles',
  414. 'Sierra Leone',
  415. 'Singapore',
  416. 'Slovakia',
  417. 'Slovenia',
  418. 'Solomon Islands',
  419. 'Somalia',
  420. 'South Africa',
  421. 'South Georgia And The South Sandwich Islands',
  422. 'Spain',
  423. 'Sri Lanka',
  424. 'Sudan',
  425. 'Suriname',
  426. 'Svalbard And Jan Mayen',
  427. 'Swaziland',
  428. 'Sweden',
  429. 'Switzerland',
  430. 'Syrian Arab Republic',
  431. 'Taiwan, Province Of China',
  432. 'Tajikistan',
  433. 'Tanzania, United Republic Of',
  434. 'Thailand',
  435. 'Timor-Leste',
  436. 'Togo',
  437. 'Tokelau',
  438. 'Tonga',
  439. 'Trinidad And Tobago',
  440. 'Tunisia',
  441. 'Turkey',
  442. 'Turkmenistan',
  443. 'Turks And Caicos Islands',
  444. 'Tuvalu',
  445. 'Uganda',
  446. 'Ukraine',
  447. 'United Arab Emirates',
  448. 'United Kingdom',
  449. 'United States',
  450. 'United States Minor Outlying Islands',
  451. 'Uruguay',
  452. 'Uzbekistan',
  453. 'Vanuatu',
  454. 'Venezuela',
  455. 'Viet Nam',
  456. 'Virgin Islands, British',
  457. 'Virgin Islands, U.S.',
  458. 'Wallis And Futuna',
  459. 'Western Sahara',
  460. 'Yemen',
  461. 'Zambia',
  462. 'Zimbabwe'
  463. );
  464. return $countries;
  465. }
  466. //close get countries and US states
  467. function get_month(){
  468. $months = array(
  469. '01' => 'January',
  470. '02' => 'February',
  471. '03' => 'March',
  472. '04' => 'April',
  473. '05' => 'May',
  474. '06' => 'June',
  475. '07' => 'July',
  476. '08' => 'August',
  477. '09' => 'September',
  478. '10' => 'October',
  479. '11' => 'November',
  480. '12' => 'December'
  481. );
  482. return $months;
  483. }
  484. //close get month
  485. function get_day(){
  486. $days = array();
  487. for($i=1; $i<=31; $i++){
  488. if(strlen($i) == 1){ $i = '0' . $i; }
  489. $days[$i] = $i;
  490. }
  491. return $days;
  492. }
  493. function get_year($min, $max){
  494. $years = range($min, $max);
  495. return $years;
  496. }
  497. function get_year_for_age(){
  498. $age_limit = date('Y') - 18;
  499. $years = range(1905, $age_limit);
  500. return $years;
  501. }
  502. function get_card_type(){
  503. $type = array(
  504. '1' => 'visa',
  505. '2' => 'mastercard',
  506. '3' => 'discover',
  507. '4' => 'amex'
  508. );
  509. return $type;
  510. }
  511. //close get month
  512. /*
  513. //string $filename = example.jpg
  514. //string $folder = directory under UPLOAD_PATH
  515. //int $width
  516. //int $height
  517. //CONSTANT definded in config.php
  518. //define('UPLOAD_URL' , SITE_URL . 'content/upload/');
  519. //define('UPLOAD_PATH' , __DIR__ . '\\content\\upload\\');
  520. //define('MIN_URL' , SITE_URL . 'content/media/min/');
  521. //define('MIN_PATH' , __DIR__ . '\\content\\media\\min\\');
  522. //return string resized image url
  523. */
  524. function resize_image($filename, $folder, $width, $height, $filetype = "jpg"){
  525. $ori_image_url = UPLOAD_PATH . '\\' . $folder . '\\' . $filename;
  526. $size = $width . '_' . $height;
  527. $res_image_url = MIN_PATH . $size . '\\' . $filename;
  528. $image_dir = dirname($res_image_url);
  529. //d(MIN_PATH);
  530. //d($image_dir);
  531. //d(is_dir($image_dir));
  532. if(!is_dir($image_dir)){mkdir($image_dir, 0777);}
  533. //d($res_image_url);
  534. //d(file_exists($res_image_url));
  535. if(!file_exists($res_image_url)){
  536. ////////
  537. // ----------Image Resizing Function--------
  538. $target_file = $ori_image_url;
  539. $resized_file = $res_image_url;
  540. $wmax = $width;
  541. $hmax = $height;
  542. ak_img_resize($target_file, $resized_file, $wmax, $hmax, $filetype);
  543. /////////
  544. }
  545. return MIN_URL . $size . '/' . $filename;
  546. }//close resize_image
  547. function excerpt($max_length, $value){
  548. if(strlen($value) > $max_length){
  549. $value = substr($value, 0, $max_length);
  550. $value .= "...";
  551. }
  552. return $value;
  553. }
  554. /*
  555. $table_name = string
  556. $culumns = array('culumn1', 'culumn2');
  557. $keywords = string, snow man falling from the sky
  558. $where = string, example1 = 1 AND example1 != 2 OR example3 LIKE '%hello%'
  559. $distinct = string, use as GROUP BY '{$distinct}'
  560. $primary_key = string, count($primary_key) as occurrences
  561. $search_mode= string "more" or "less" for more or less result
  562. */
  563. function search($table_name, $culumns, $keywords, $where="", $distinct="id", $primary_key="id", $order_by="id", $sort="ASC", $search_mode="more"){
  564. $keywords = trim(urldecode($keywords));
  565. ////////////////////////////////////prepare keyword for search
  566. $string = "";
  567. $new_string = "";
  568. $string = $keywords;
  569. $string = strtolower(htmlentities(urldecode($string)));//make the keyword lowercase and filter the html tag out
  570. if(strlen($string) >= 2){//if the entered keyword is longer than 2 characater, do the search function below //2
  571. $string = PorterStemmer::Stem($string);//removing the commoner morphological and inflexional endings from words in English
  572. $clean_string = new cleaner();
  573. $string = $clean_string->parseString($string);//remove the stupid words e.x me, I , do, what, and so on
  574. //if(strlen($string) >= 2){//2.5
  575. //if the clean string short than 2 chanracters, output nothing
  576. $split = explode(" ",$string);//split each word in the entered keyword and put them into an array
  577. //print_r($split);exit();
  578. //test the result of explode
  579. //filter out any word that less than 3 characters long in the array that created above
  580. //and make them a new string varibale
  581. foreach ($split as $array => $value) {//3
  582. if (strlen($value) >= 1) {//4
  583. $new_string .= ' '.$value.' ';
  584. }//close4
  585. }//end the foreach loop //close 3
  586. $new_string=substr($new_string,0,(strLen($new_string)-1));//remove the last space " "
  587. //echo $new_string; exit();
  588. //make the new string variable to an array again, because we need the array function to do the slq
  589. $split_stemmed = explode(" ",$new_string);
  590. ///////////orginal $sql = "SELECT DISTINCT COUNT(*) As occurrences, field1, field2, field3 FROM tablename WHERE (";
  591. //}//close 2.5
  592. }//close 2
  593. $sql = "SELECT *, COUNT({$primary_key}) As occurrences FROM {$table_name} ";
  594. //////////////////if senatized keyword is not shorter than 2 characters long, add keyword search query
  595. if(strlen($string) >= 2){
  596. $keyword_sql = "WHERE (";
  597. while(list($key,$val)=each($split_stemmed)){//5
  598. if($val<>" " and strlen($val) > 0){//6
  599. $val = '%'. $val .'%';
  600. // $val = '%'. $val;
  601. $keyword_sql .= "(";
  602. foreach($culumns as $culumn){
  603. $keyword_sql .= "{$culumn} LIKE '{$val}' OR ";
  604. }
  605. $keyword_sql = substr($keyword_sql,0,(strLen($keyword_sql)-3));//this will eat the last OR
  606. if($search_mode == "more"){
  607. $keyword_sql .= ") OR ";
  608. }elseif($search_mode == "less"){
  609. $keyword_sql .= ") AND";
  610. }
  611. }//close 6
  612. }//end the while loop //close5
  613. $keyword_sql = substr($keyword_sql,0,(strLen($keyword_sql)-4));//this will eat the last OR
  614. //$sql_find_all_for_count = $sql . ") GROUP BY id";
  615. if($where != ""){
  616. $keyword_sql .= ") AND " . $where;
  617. }else{
  618. $keyword_sql .= ")";
  619. }
  620. $keyword_sql .= " GROUP BY {$distinct} ";
  621. $sql = $sql . $keyword_sql;
  622. $sql .= "ORDER BY {$order_by} {$sort}";
  623. }else{//if search keyword is shorter than 2
  624. $keyword_sql = "WHERE ";
  625. $keyword_sql .= "(";
  626. foreach($culumns as $culumn){
  627. $keyword_sql .= "{$culumn} LIKE '%" . $string . "%' OR ";
  628. }
  629. $keyword_sql = substr($keyword_sql,0,(strLen($keyword_sql)-3));//this will eat the last OR
  630. if($where != ""){
  631. $keyword_sql .= ") AND " . $where;
  632. }else{
  633. $keyword_sql .= ")";
  634. }
  635. $keyword_sql .= " GROUP BY {$distinct} ";
  636. $sql = $sql . $keyword_sql;
  637. $sql .= "ORDER BY {$order_by} {$sort} LIMIT 30";
  638. }
  639. //close keyword search query
  640. //dd($sql);
  641. return $sql;
  642. }//close search function
  643. function params_string($params, $exception = array()){
  644. $url_var = "";
  645. if(is_array($params) && count($params)>0){
  646. foreach($params as $key => $val){
  647. if(!in_array($key, $exception)){
  648. $url_var .= $key . "/" . $val . "/";
  649. }
  650. }
  651. }
  652. return $url_var;
  653. }
  654. function file_format($filename){
  655. $filename_array = explode(".", $filename);
  656. $format = array_pop($filename_array);
  657. return $format;
  658. }
  659. function special_chars_clean($string) {
  660. $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
  661. $string = preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
  662. return preg_replace('/-+/', '-', $string); // Replaces multiple hyphens with single one.
  663. }
  664. /*Resize image base on min length of the shorter side(width or height)*/
  665. function zy_img_resize($target, $newcopy, $min_len, $ext) {
  666. list($w_orig, $h_orig) = getimagesize($target);
  667. $change_scale = "";
  668. if($w_orig > $h_orig)
  669. {
  670. $h = $min_len;
  671. $change_scale = $h/$h_orig;
  672. $w = $w_orig*$change_scale;
  673. }else{
  674. $w = $min_len;
  675. $change_scale = $w/$w_orig;
  676. $h = $h_orig*$change_scale;
  677. }
  678. $img = "";
  679. $ext = strtolower($ext);
  680. if ($ext == "gif"){
  681. $img = imagecreatefromgif($target);
  682. } else if($ext =="png"){
  683. $img = imagecreatefrompng($target);
  684. } else {
  685. $img = imagecreatefromjpeg($target);
  686. }
  687. $tci = imagecreatetruecolor($w, $h);
  688. // imagecopyresampled(dst_img, src_img, dst_x, dst_y, src_x, src_y, dst_w, dst_h, src_w, src_h)
  689. imagecopyresampled($tci, $img, 0, 0, 0, 0, $w, $h, $w_orig, $h_orig);
  690. if ($ext == "gif"){
  691. imagegif($tci, $newcopy);
  692. } else if($ext =="png"){
  693. imagepng($tci, $newcopy);
  694. } else {
  695. imagejpeg($tci, $newcopy, 84);
  696. }
  697. }
  698. /*
  699. Check if the image already has re-sized. If yes, retrun the path. If not, generated one and return the path.
  700. */
  701. function resize_image_by_minlen($folder_name=NULL, $filename, $minlen, $filetype = "jpg"){
  702. if($folder_name !== NULL)
  703. {
  704. $ori_image_url = $folder_name;//UPLOAD_PATH . $folder_name . DS . $filename;
  705. }else{
  706. $ori_image_url = UPLOAD_PATH . $filename;
  707. }
  708. $res_image_url = MIN_PATH . $minlen . DS . $filename;
  709. $image_dir = dirname($res_image_url);
  710. if(!is_dir($image_dir)){mkdir($image_dir, 0777);}
  711. if(!file_exists($res_image_url)){
  712. // ----------Call Image Resizing Function--------
  713. $target_file = $ori_image_url;
  714. $resized_file = $res_image_url;
  715. zy_img_resize($target_file, $resized_file, $minlen, $filetype);
  716. }
  717. return MIN_URL . $minlen . '/' . $filename;
  718. }//close resize_image_by_minlen
  719. /*After we have a resied image, we use this function to generate the crop version*/
  720. function images_thumb($filename, $minlen, $width, $height, $filetype){
  721. $size = $width . '_' . $height;
  722. $target_file = MIN_PATH . $minlen . DS . $filename;
  723. $thumb_file = THUMB_PATH . $size . DS . $filename;
  724. $image_dir = dirname($thumb_file);
  725. if(!is_dir($image_dir)){mkdir($image_dir, 0777);}
  726. if(!file_exists($thumb_file)){
  727. ak_img_thumb($target_file, $thumb_file, $width, $height, $filetype);
  728. }
  729. return THUMB_PATH . $size . DS . $filename;
  730. }
  731. /**
  732. * prints out script tag
  733. * @param type $name: name of script, or if script is in subfolder, then put subfolder/path/to/script.js
  734. */
  735. function script($name,$full_path=FRONT_JS) {
  736. echo "<script type=\"text/javascript\" src=\"".$full_path."{$name}\"></script>";
  737. }
  738. /**
  739. *
  740. * @param type $name
  741. * @param type $full_path: default path is in content/css. if css is not there then it can be overwritten
  742. */
  743. function css($name,$full_path = FRONT_CSS) {
  744. echo "<link rel=\"stylesheet\" type=\"text/css\" href=\"".$full_path."{$name}\">";
  745. }
  746. function link_to($href,$text,$html_objects = ['class'=>"btn btn-primary btn-add"]) {
  747. $attrs = "";
  748. foreach($html_objects as $key=>$val) {
  749. $attrs .= "{$key}='{$val}'";
  750. }
  751. return "<a href='{$href}' {$attrs}>{$text}</a>";
  752. }
  753. function filter_get() {
  754. $get_filter = array();
  755. foreach($_GET as $key=>$value) {
  756. $get_filter[$key] = filter_input(INPUT_GET,$key);
  757. }
  758. return $get_filter;
  759. }
  760. /**
  761. * function to save only for single image
  762. * @param type $file
  763. * @param type $obj
  764. * @param type $field_name
  765. * @param type $upload_path
  766. * @param type $sizes
  767. */
  768. function save_image($file,$obj,$field_name,$upload_path,$sizes) {
  769. if($file && !empty($file) && is_array($file) && $file['error'] != 4){//dd($file);
  770. if($obj->{$field_name} != "" && file_exists($upload_path.$obj->{$field_name})){
  771. unlink($upload_path . $obj->{$field_name});}
  772. $tem_file_name = $file['tmp_name'];
  773. $file_name = uniqid() . "_" . basename($file['name']);
  774. $file_name = str_replace(' ', '_', $file_name);
  775. $file_name = str_replace('-', '_', $file_name);
  776. $allow_format = array('jpg', 'png', 'gif');
  777. $filetype = explode("/", $file['type']); //$file['type'] has value like "image/jpeg"
  778. $filetype = strtolower(array_pop($filetype));
  779. if($filetype == 'jpeg'){$filetype = 'jpg';}
  780. if(in_array($filetype, $allow_format)){
  781. $img_path = compress_image($tem_file_name, $upload_path . $file_name, 60,$file['size']);
  782. if($img_path===false) {
  783. move_uploaded_file($tem_file_name, $upload_path . $file_name);
  784. }
  785. //move_uploaded_file($tem_file_name, $upload_path . $file_name);
  786. $obj->{$field_name} = $file_name;
  787. foreach($sizes as $key=>$val) {
  788. if(is_array($val) && count($val)==2) {
  789. resize_image_by_minlen($upload_path,
  790. $obj->{$field_name}, min($val), $filetype);
  791. $path = images_thumb($obj->{$field_name},min($val),
  792. $val[0],$val[1], file_format($obj->{$field_name}));
  793. $image_size_str = implode('_',$val);
  794. copy($path, $upload_path.$image_size_str.$file_name);
  795. }
  796. }
  797. $obj->save();
  798. }
  799. }//close upload featured_image
  800. }
  801. function compress_image($source_url, $destination_url, $quality,$size,$btsize=535396) {
  802. $info = getimagesize($source_url);
  803. if($size<$btsize) {return false;}
  804. if ($info['mime'] == 'image/jpeg') {
  805. $image = imagecreatefromjpeg($source_url);
  806. imagejpeg($image, $destination_url, $quality);
  807. }
  808. elseif ($info['mime'] == 'image/gif') {
  809. $image = imagecreatefromgif($source_url);
  810. imagegif($image, $destination_url, $quality);
  811. }
  812. elseif ($info['mime'] == 'image/png') {
  813. $image = imagecreatefrompng($source_url);
  814. imagepng($image, $destination_url, $quality);
  815. }
  816. //imagejpeg($image, $destination_url, $quality);
  817. return $destination_url;
  818. }
  819. function get_token() {
  820. if(isset($_SESSION['csrf_token'])) {
  821. return $_SESSION['csrf_token'];
  822. } else {
  823. $_SESSION['csrf_token'] = md5(uniqid(rand(),TRUE));
  824. return $_SESSION['csrf_token'];
  825. }
  826. }
  827. function strReplace($content, $limit, $strReplace)
  828. {
  829. return strlen($content) < $limit ? $content : substr($content, 0, $limit) . $strReplace;
  830. }
  831. function auto_version($file)
  832. {
  833. if(strpos($file, '/') !== 0 || !file_exists($_SERVER['DOCUMENT_ROOT'] . $file))
  834. return $file;
  835. $mtime = filemtime($_SERVER['DOCUMENT_ROOT'] . $file);
  836. return preg_replace('{\\.([^./]+)$}', ".$mtime.\$1", $file);
  837. }