PHP File Manager
Editing File: common_helper.php
<?php /* * Copyright (C) Wayne Purton-Smith - All Rights Reserved * Unauthorized copying of this file or removing this paragraph, via any medium is strictly prohibited * Proprietary and confidential * Written by Wayne Purton-Smith <waynepurtonsmith@hotmail.co.uk> February 2014 */ function display_date($format, $timestamp = NULL) { $is_bst = get_instance()->common->is_bst; $timestamp = (!is_numeric($timestamp)) ? time() : $timestamp; $timestamp += ($is_bst) ? 3600 : 0; return date($format, $timestamp); } function wayne() { return (isset($_SERVER['HTTP_USER_AGENT']) && stripos($_SERVER['HTTP_USER_AGENT'], 'rdit-dev') !== false); } function isRDIT() { return (in_array(get_instance()->input->ip_address(), array('172.16.0.1', '78.33.181.81', '217.37.157.165'))); } function help_link($identifier = '') { if(wayne() && ($identifier = format_whitespace($identifier)) != '') { return '<a href="#' . url_title($identifier, '-', true) . '" class="rdit-help tooltipped" title="What is this?" style="display: inline; vertical-align: baseline;" onclick="return false;"><img src="/assets/images/icons/information.png" alt="" /></a>'; } return ''; } function format_display() { return trim((string) implode(' ', array_filter(func_get_args()))); } function format_list() { return trim((string) implode(', ', array_filter(func_get_args()))); } function format_address() { return trim((string) implode(', ', array_map('format_name', array_filter(func_get_args())))); } function explode_twice($delimiter, $second_delimiter, $str) { $str = explode($delimiter, $str); $return_data = array(); foreach($str as $str_line) { list($data_key, $data_value) = explode($second_delimiter, $str_line); $return_data[$data_key] = $data_value; } return $return_data; } function access_array($array = array(), $key = '', $default = NULL) { if(is_array($array) && is_string($key)) { $key = (strpos($key, '.') !== false) ? explode('.', $key) : $key; if(is_string($key)) { return (array_key_exists($key, $array)) ? $array[$key] : $default; } else { $ref = $array; while(($key_name = array_shift($key))) { if(array_key_exists($key_name, $ref)) { $ref = $ref[$key_name]; } else { return $default; } } return $ref; } } return $default; } function get_date_info($timestamp = NULL) { $date_info = getdate($timestamp); if(isset($date_info['wday'])) { $date_info['wday'] = ($date_info['wday'] == 0) ? 7 : $date_info['wday']; } return $date_info; } function flip_date($date_str = '') { return implode('-', array_reverse(explode('-', $date_str))); } /* function format_name() { return str_ireplace(' and ', ' and ', trim((string) preg_replace_callback('/([a-z]+)-([a-z]{1})/i', function($matches){ return $matches[1] . '-' . strtoupper($matches[2]); }, ucwords(strtolower(implode(' ', array_filter(func_get_args()))))))); } */ // Credit to http://stackoverflow.com/a/17369332/264795 function format_name() { $str = strtolower(implode(' ', array_filter(func_get_args()))); $all_uppercase = 'Co|Lcs|Lcb|C\/O|Llc|Plc|Ltd'; $all_lowercase = 'De La|De Las|Der|Van De|Van Der|Vit De|Von|Or|Of|And|Van |St'; $prefixes = 'Mc'; $suffixes = "'S"; $abbreviations = 'St |Mr |Mrs |Miss|Ms |Dr |Prof |Nr |Rd '; // captialize all first letters $str = preg_replace_callback('/\\b(\\p{L})/u', function($matches) { return strtoupper($matches[1]); }, strtolower(trim($str))); if($all_uppercase) { // capitalize acronymns and initialisms e.g. PHP $str = preg_replace_callback("/\\b($all_uppercase)\\b/", function($matches) { return strtoupper($matches[1]); }, $str); } if(strpos($str, " ") !== FALSE) { $ara = explode(" ", $str); foreach ($ara as $k => $v) { if($k != count($ara)-1 && !preg_match("/[aeiouyAEIOUY]/", $v)) $ara[$k] = strtoupper($v); } $str = implode(" ", $ara); } elseif(!preg_match("/[aeiouy]/", $str)) { $str = strtoupper($str); } if($all_lowercase) { $str = preg_replace_callback("/\\b($all_lowercase)\\b/", function($matches) { return strtolower($matches[1]); }, $str); } if($prefixes) { // capitalize letter after certain name prefixes e.g 'Mc' $str = preg_replace_callback("/\\b($prefixes)(\\w)/", function($matches) { return $matches[1] . strtoupper($matches[2]); }, $str); } if($suffixes) { // decapitalize certain word suffixes e.g. 's $str = preg_replace_callback("/(\\w)($suffixes)\\b/", function($matches) { return $matches[1] . strtolower($matches[2]); }, $str); } $str = preg_replace_callback("/(?![^\b])|^($abbreviations)/i", function($matches) { if(isset($matches[1])) { return ucfirst(strtolower($matches[1])); } }, $str); // Mac Exceptions if(strpos($str, "Macd") === FALSE || strpos($str, "Macv") === FALSE) { $str = preg_replace("/Macd/", 'MacD', $str); $str = preg_replace("/Macv/", 'MacV', $str); } return trim(stripcslashes($str)); } function extract_names($name_str = '') { $first_name = reset(explode(' ', $name_str, 2)); $first_name = nullify($first_name); $last_name = reset(array_slice(explode(' ', $name_str), 1)); $last_name = nullify($last_name); return array($first_name, $last_name); } function is_order_number($str = '') { if(preg_match('/^#?[O|0]?([0-9]{3})-?([0-9]{3})$/i', $str, $matches)) { return 'O' . $matches[1] . '-' . $matches[2]; } return false; } function friendly_order_number($order_number = '') { return (is_order_number($order_number)) ? preg_replace('/(^\D)|-/', '', $order_number) : ''; } function format_customer_details($customer_details = array(), $customer_address = array(), $customer_contact = array()) { $customer_details = call_user_func_array('format_name', $customer_details); $customer_address = call_user_func_array('format_address', $customer_address); $contact_details = implode(' / ', array_filter($customer_contact)); return implode('<br />', array_filter(array($customer_details, $customer_address, $contact_details))); } function is_similar_address($address_one = array(), $address_two = array(), &$percentage = 0) { $address_one = strtolower((is_array($address_one)) ? call_user_func_array('format_name', $address_one) : format_name($address_one)); $address_two = strtolower((is_array($address_two)) ? call_user_func_array('format_name', $address_two) : format_name($address_two)); similar_text($address_one, $address_two, $compare_percentage); $percentage = $compare_percentage; return ($compare_percentage >= 99); } function format_postcode($postcode = '') { return strtoupper(remove_whitespace($postcode)); } function lined_address() { return trim((string) implode('<br />', array_filter(func_get_args(), 'input_value'))); } function two_lined_address() { $address_array = array_filter(array_map('trim', func_get_args()), 'input_value'); $address_array = array_chunk($address_array, ceil(count($address_array) / 2)); list($address_line_one, $address_line_two) = $address_array; return implode('<br />', array(implode(', ', $address_line_one), implode(', ', $address_line_two))); } function first_line_link($str = '', $link = '') { return preg_replace('/^([^\n\r]*)/', '<a href="' . $link . '">$1</a>', $str); } function display_money($amount = 0, $use_entity = true) { return (($use_entity) ? '£' : '£') . number_format((float) $amount, 2); } function remove_whitespace($str = '') { return (is_string($str)) ? preg_replace('/\s+/', '', $str) : NULL; } function format_whitespace($str = '', $strip = '') { return (is_string($str)) ? trim(trim(preg_replace('/\s{2,}/', ' ', $str)), $strip) : NULL; } function strposa($haystack, $needles = array(), $offset = 0, $case_sensitive = false) { $chr = array(); foreach($needles as $needle) { $func = ($case_sensitive) ? 'strpos' : 'stripos'; $res = call_user_func($func, $needle, $offset); if($res !== false) { $chr[$needle] = $res; } } return (!empty($chr)) ? min($chr) : false; } function cast_int_ids($data = array()) { return array_values(array_filter($data, function($int) { return (($int = (int) $int) > 0) ? $int : false; })); } function week_number($date) { return ceil(date('j', $date) / 7); } function order_status($status_id = 0) { return (($order_status = get_instance()->config->item('order_status_' . $status_id))) ? $order_status : 'N/A'; } function payment_type($type = 0) { $payment_types = array ( 1 => 'PayPal', 2 => 'BACS', 3 => 'Credit Card', 4 => 'Cash' ); return (func_num_args() === 0) ? $payment_types : ((isset($payment_types[$type])) ? $payment_types[$type] : 'Unknown'); } function accounting_payment_type($type = 0) { $payment_types = array ( PAYMENT_TYPE_CASH => 'Cash', PAYMENT_TYPE_BACS => 'BACS', PAYMENT_TYPE_CREDIT_CARD => 'Credit Card', PAYMENT_TYPE_CHEQUE => 'Cheque' ); return (isset($payment_types[$type])) ? $payment_types[$type] : $payment_types[PAYMENT_TYPE_CASH]; } function exit_with_json($output = array()) { //if(!in_array('ob_gzhandler', ob_list_handlers())) ob_start('ob_gzhandler'); header("Content-Type: application/json", true); header("Expires: Sun, 01 Jan 2014 00:00:00 GMT"); header("Cache-Control: no-store, no-cache, must-revalidate"); header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); if(is_php('5.4.0')) { exit(json_encode($output, JSON_PRETTY_PRINT)); } else { exit(jsonpp(json_encode($output))); } } if(!is_php('5.4.0')) { function jsonpp($json, $istr = ' ') { $result = ''; for($p = $q = $i = 0; isset($json[$p]); $p++) { $json[$p] == '"' && ($p > 0 ? $json[$p - 1] : '') != '\\' && $q = !$q; if(!$q && strchr(" \t\n\r", $json[$p])) { continue; } if(strchr('}]', $json[$p]) && !$q && $i--) { strchr('{[', $json[$p-1]) || $result .= "\n" . str_repeat($istr, $i); } $result .= $json[$p]; if(strchr(',{[', $json[$p]) && !$q) { $i += strchr('{[', $json[$p]) === false ? 0 : 1; strchr('}]', $json[$p + 1]) || $result .= "\n" . str_repeat($istr, $i); } } return str_replace('":', '": ', $result); } } function input_value($str = '') { return htmlentities((string) $str, ENT_QUOTES, 'UTF-8', false); } function per_page_dropdown($class_name = '') { return form_dropdown('per_page', array ( 30 => '30 per page', 60 => '60 per page', 90 => '90 per page', 120 => '120 per page', 150 => '150 per page' ), get_instance()->common->default_per_page, 'id="results-per-page"' . (($class_name) ? ' class="' . $class_name . '"' : '')); } function calculate_vat($amount = 0, $vat = 0) { return round($amount * (get_instance()->common->vat / 100), 2); } function calculate_distance($lat1 = 0, $lon1 = 0, $lat2 = 0, $lon2 = 0) { $theta = $lon1 - $lon2; $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta)); $dist = acos($dist); $dist = rad2deg($dist); $miles = $dist * 60 * 1.1515; return $miles; } function filter_param($param_key = '', $replace_param = '', $remove_params = array(), $url_mode_param = '') { $CI = get_instance(); $assoc_uri = $CI->uri->uri_to_assoc(); if(isset($assoc_uri[$param_key])) { unset($assoc_uri[$param_key]); } $assoc_uri[$param_key] = $replace_param; if(count($remove_params)) { foreach($remove_params as $i => $_rm_param) { if(isset($assoc_uri[$_rm_param])) { unset($assoc_uri[$_rm_param]); } } } ksort($assoc_uri, SORT_STRING); $uri_string = $CI->uri->assoc_to_uri($assoc_uri); if($uri_string != '') { return (($url_mode_param) ? $url_mode_param . '/' : '') . $uri_string; } return $uri_string; } function calculate_discount($number = 0, $amount = 0, $type = DISCOUNT_PERCENTAGE) { $number = abs($number); $amount = abs($amount); if($number > 0 && $amount > 0 && in_array($type, array(DISCOUNT_PERCENTAGE, DISCOUNT_AMOUNT))) { // ROUND(((`oi`.`total` / 100) * `o`.`discount`), 2) switch($type) { case DISCOUNT_PERCENTAGE: return (($total_discount = round(($number / 100) * $amount, 2)) >= 0) ? $total_discount : 0; break; case DISCOUNT_AMOUNT: return (($total_discount = round(($number - $amount), 2)) >= 0) ? $total_discount : 0; break; } } return 0; } function csv_to_array($csv = '') { $rows = explode(PHP_EOL, trim($csv)); $header = str_getcsv(array_shift($rows)); $data = array(); foreach($rows as $row) { $data[] = array_combine($header, str_getcsv($row)); } return $data; } function highlight_search($search_string = '', $string = '', $class_name = '') { $escaped_string = preg_quote($search_string, '/'); $start = 0; $matches = array(); while(($position = stripos($string, $search_string, $start)) !== false) { $get_from_index = (($position - 5) > 0) ? $position - 5 : 0; $matching_string = substr($string, $get_from_index, strlen($search_string) + 10); $matching_string = preg_replace('/(' . $escaped_string . ')/i', '<span class="highlighted' . (($class_name) ? ' ' . $class_name : '') . '">$1</span>', $matching_string); $matches[] = $matching_string; $start = $position + 1; } return implode('...', $matches); } // TODO: Make this more cleaner since sorting multiple columns is going to be confusing for the client // so best to stick to sorting one column at a time function toggle_sortable_component($change_sort_key = NULL, $sortable_columns = array(), $append_after = '', $append_for_key = NULL) { $existing_key_order = (isset($sortable_columns[$change_sort_key])) ? $sortable_columns[$change_sort_key] : 'asc'; $sortable_columns = array($change_sort_key => $existing_key_order); if(!empty($change_sort_key)) { if(isset($sortable_columns[$change_sort_key])) { $sortable_columns[$change_sort_key] = ($sortable_columns[$change_sort_key] == 'asc') ? 'desc' : 'asc'; } else { $sortable_columns[$change_sort_key] = 'asc'; } } if(strlen(($append_after = rtrim($append_after, '/')))) { if($append_for_key) { $sortable_columns = array($append_for_key => $sortable_columns); } return $append_after . ((strpos($append_after, '?') === false) ? '?' : '&') . rawurldecode(http_build_query($sortable_columns)); } return $sortable_columns; } function parse_query_components($query = '') { $query = strtolower($query); $keyed_query_regex = '/(^|[\w-]+)\:/'; if(!preg_match($keyed_query_regex, $query)) { return array('query' => $query); } $query = strtolower(trim(preg_replace($keyed_query_regex, "\n$1:", $query))); $query = explode("\n", $query); $query_data = array('query' => array()); $special_components = array('customer', 'total', 'unpaid', 'delivery', 'ordered'); foreach($query as $query_component) { if(strpos($query_component, ':') !== false) { list($search_key, $search_value) = explode(':', $query_component); $search_key = trim($search_key); $search_value = trim($search_value); if(in_array($search_key, $special_components)) { $query_data[$search_key] = $search_value; continue; } $query_component = $search_value; } $query_data['query'][] = $query_component; } $query_data['query'] = preg_replace('/\s+/', ' ', implode(' ', $query_data['query'])); if(isset($query_data['total'])) { if(strpos($query_data['total'], '~') !== false) { list($total, $margin) = array_filter(explode('~', $query_data['total']), function($value) { return (($value = (float) $value) > 0) ? $value : false; }); $query_data['total'] = $total; $query_data['total_margin'] = $margin; } } if(isset($query_data['unpaid'])) { $query_data['unpaid'] = ($query_data['unpaid'] === 'yes'); } foreach(array('delivery', 'ordered') as $query_key) { if(isset($query_data[$query_key]) && ($date_value = trim($query_data[$query_key]))) { if(preg_match_all('/[0-9-]{8,10}/i', $date_value, $matches, PREG_SET_ORDER)) { $date_from = strtotime($matches[0][0] . ' 00:00:00'); $date_to = (isset($matches[1][0])) ? strtotime($matches[1][0] . ' 23:59:59') : NULL; if($date_from > 1) $query_data[$query_key . '_date_from'] = $date_from; if($date_to > $date_from) $query_data[$query_key . '_date_to'] = $date_to; } unset($query_data[$query_key]); } } return $query_data; } function remove_outside_range($array = array(), $min = 0, $max = 0) { return array_values(array_filter($array, function($value) use($min, $max) { return ($value >= $min && $value <= $max) ? $value : false; })); } function is_valid_postcode($postcode = '') { return (bool) preg_match('/GIR[ ]?0AA|((AB|AL|B|BA|BB|BD|BH|BL|BN|BR|BS|BT|BX|CA|CB|CF|CH|CM|CO|CR|CT|CV|CW|DA|DD|DE|DG|DH|DL|DN|DT|DY|E|EC|EH|EN|EX|FK|FY|G|GL|GY|GU|HA|HD|HG|HP|HR|HS|HU|HX|IG|IM|IP|IV|JE|KA|KT|KW|KY|L|LA|LD|LE|LL|LN|LS|LU|M|ME|MK|ML|N|NE|NG|NN|NP|NR|NW|OL|OX|PA|PE|PH|PL|PO|PR|RG|RH|RM|S|SA|SE|SG|SK|SL|SM|SN|SO|SP|SR|SS|ST|SW|SY|TA|TD|TF|TN|TQ|TR|TS|TW|UB|W|WA|WC|WD|WF|WN|WR|WS|WV|YO|ZE)(\d[\dA-Z]?[ ]?\d[ABD-HJLN-UW-Z]{2}))|BFPO[ ]?\d{1,4}/i', $postcode); } function date_suffix($day = 1, $include_date = true) { $day = (int) $day; $suffix = ''; if($day >= 10 && $day <= 13) { $suffix = 'th'; } else { switch(substr($day, -1)) { default: $suffix = 'th'; break; case 1: $suffix = 'st'; break; case 2: $suffix = 'nd'; break; case 3: $suffix = 'rd'; break; } } return (($include_date) ? $day : '') . $suffix; } function required_fields_filled() { $number_of_passed_values = func_num_args(); $field_values = array_filter(array_map('trim', func_get_args())); if(empty($field_values)) { return false; } return (count($field_values) === $number_of_passed_values); } function referrals_dropdown($name = '', $selected = array(), $attributes = '') { $referral_types = get_instance()->common->getReferrals(); $options = array(); foreach($referral_types as $referral_type) { $options[$referral_type->refer_id] = $referral_type->label; } return form_dropdown($name, $options, $selected, $attributes); } function payments_dropdown($name = '', $selected = array(), $attributes = '') { $payment_types = get_instance()->common->getPaymentTypes(); $options = array(); foreach($payment_types as $payment_type) { $options[$payment_type->type_id] = $payment_type->label; } return form_dropdown($name, $options, $selected, $attributes); } function countries_dropdown($name = '', $selected = array(), $attributes = '') { $countries = get_instance()->common->getCountries(); $options = array(); foreach($countries as $country) { $options[$country->iso] = $country->name; } return form_dropdown($name, $options, $selected, $attributes); } function iso_code_to_country($country_iso = '') { if(($country_iso = strtoupper(remove_whitespace($country_iso))) != '' && strlen($country_iso) === 2) { return (($country_info = get_instance()->common->getCountries(NULL, $country_iso))) ? $country_info->name : NULL; } return NULL; } function country_to_iso_code($country_name = '') { if(($country_name = strtoupper(format_whitespace($country_name))) != '') { return (($country_info = get_instance()->common->getCountries(NULL, NULL, $country_name))) ? $country_info->iso : NULL; } return NULL; } function regions_dropdown($name = '', $selected = array(), $attributes = '') { $regions = get_instance()->common->getCountryRegions(); $options = array(); foreach($regions as $region) { $options[$region->region_id] = $region->name; } return form_dropdown($name, $options, $selected, $attributes); } function remove_double_zero($amount = 0) { $formatted_amount = (string) number_format($amount, 2); if(substr($formatted_amount, -3) === '.00') { $formatted_amount = substr($formatted_amount, 0, -3); } return $formatted_amount; } function decode_post_data($post) { array_walk_recursive($post, '_decode_data'); } function get_max_upload_size() { $max_size = 0; foreach(array('upload_max_filesize', 'post_max_size') as $ini_key) { if(preg_match('/^(\d+)(g|m|k)$/', strtolower(ini_get($ini_key)), $matches)) { $size = (int) $matches[1]; $measurement = $matches[2]; switch($measurement) { case 'g': $size = $size * 1024 * 1024 * 1024; break; case 'm': $size = $size * 1024 * 1024; break; } if($size > $max_size) { $max_size = $size; } } } return (($max_size / 1024 / 1024)) . ' MB'; } function _decode_data(&$str) { if(is_string($str) && strlen($str) && trim($str) !== '') { $str = htmlspecialchars_decode($str, ENT_QUOTES); } return $str; } function scrambled_hash($password = '') { $first_half = md5($password); $second_half = md5(sha1(strrev($password), true)); $hash = ''; for($i = 0; $i < 2; $i++) { $scope = ''; for($j = 0; $j < 16; $j++) { $scope .= $first_half[$j]; } for($j = 0; $j < 16; $j++) { $scope .= $second_half[$j]; } $hash .= $scope; } $new_password = ''; $hash_length = strlen($hash); for($i = 0; $i < $hash_length; $i++) { $new_password .= md5($hash[0] . ':' . $hash[$i] . ':' . $hash[$hash_length - 1]); } return $new_password; } function hash_password($password = '') { require_once(APPPATH . 'third_party/phppass/phppassword.php'); return password_hash(scrambled_hash($password), PASSWORD_BCRYPT); } function verify_password($password = '', $hash = '') { require_once(APPPATH . 'third_party/phppass/phppassword.php'); return password_verify(scrambled_hash($password), $hash); } function preprint() { array_map(function($arg_data) { echo '<pre>', print_r($arg_data, true), '</pre>'; }, func_get_args()); } function predump() { echo '<pre>'; call_user_func_array('var_dump', func_get_args()); echo '</pre>'; } // Converts empty strings to NULL function nullify($str) { if(is_array($str) || is_object($str)) { return (count((array) $str) === 0) ? NULL : $str; } return (strlen(trim((string) $str)) === 0) ? NULL : $str; } function generate_unique_identifier($length = 8, $table = NULL, $column = NULL) { $characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; $char_length = strlen($characters); if(strlen($table) && strlen($column)) { $CI =& get_instance(); $looped_over = 0; $max_checks = 10; do { if($looped_over >= $max_checks) { return false; break; } $identifier = ''; for($i = 0; $i < $char_length; $i++) { if(strlen($identifier) < $length) { $identifier .= $characters[rand(0, $char_length - 1)]; } } $looped_over++; } while($CI->db->query("SELECT 1 FROM `$table` WHERE `$column` = ? LIMIT 1", array($identifier))->num_rows() > 0); return $identifier; } else { $identifier = ''; for($i = 0; $i < $char_length; $i++) { if(strlen($identifier) < $length) { $identifier .= $characters[rand(0, $char_length - 1)]; } } return $identifier; } } function calendar_month_info($month = NULL, $year = NULL) { $month = (($month = (int) $month) >= 1 && $month <= 12) ? $month : date('n'); $year = (($year = (int) $year) > 0) ? $year : date('Y'); $data = array_fill_keys(range(1, cal_days_in_month(CAL_GREGORIAN, $month, $year)), NULL); foreach($data as $day_of_month => $null_data) { $data[$day_of_month] = getdate(strtotime($day_of_month . '-' . $month . '-' . $year)); } return $data; }
Cancel