"EUR", "ATS" => "EUR", "BEF" => "EUR", "CYP" => "EUR", "DEM" => "EUR", "EEK" => "EUR", "ESP" => "EUR", "FIM" => "EUR", "FRF" => "EUR", "GRD" => "EUR", "IEP" => "EUR", "ITL" => "EUR", "KZT" => "EUR", "LTL" => "EUR", "LUF" => "EUR", "LVL" => "EUR", "MCF" => "EUR", "MTL" => "EUR", "NLG" => "EUR", "PTE" => "EUR", "RUB" => "EUR", "SIT" => "EUR", "SKK" => "EUR", "SML" => "EUR", "VAL" => "EUR", "DDM" => "EUR", "ESA" => "EUR", "ESB" => "EUR", ]; foreach (array_keys($locale['currency']) as $country_iso) { $c_iso = !empty($currency_exceptions[$country_iso]) ? $currency_exceptions[$country_iso] : $country_iso; $c_symbol = (!empty($locale['currency_symbol'][$c_iso]) ? html_entity_decode($locale['currency_symbol'][$c_iso], ENT_QUOTES, $locale['charset']) : $c_iso); $c_text = $locale['currency'][$c_iso]; $__currency[$country_iso] = $description ? $c_text." ($c_symbol)" : $c_symbol; } } return $iso === NULL ? $__currency : (isset($currency_symbol[$iso]) ? $currency_symbol[$iso] : NULL); } /** * Check if a given theme exists and is valid * * @param string $theme * * @return boolean * @global string[] $settings * */ function theme_exists($theme) { if ($theme == "Default") { $theme = fusion_get_settings('theme'); } return is_string($theme) and preg_match("/^([a-z0-9_-]){2,50}$/i", $theme) and file_exists(THEMES.$theme."/theme.php") and file_exists(THEMES.$theme."/styles.css"); } /** * Set a valid theme * * @param string $theme * * @global array $locale * * @global string[] $settings */ function set_theme($theme) { $locale = fusion_get_locale(); if (defined("THEME")) { return; } if (theme_exists($theme)) { define("THEME", THEMES.($theme == "Default" ? fusion_get_settings('theme') : $theme)."/"); return; } foreach (new GlobIterator(THEMES.'*') as $dir) { if ($dir->isDir() and theme_exists($dir->getBasename())) { define("THEME", $dir->getPathname()."/"); return; } } // Don't stop if we are in admin panel since we use different themes now $no_theme_message = str_replace("[SITE_EMAIL]", fusion_get_settings("siteemail"), $locale['global_301']); if (preg_match("/\/administration\//i", $_SERVER['PHP_SELF'])) { addNotice('danger', "".$theme." - ".$locale['global_300'].".

\n".$no_theme_message); } else { echo "".$theme." - ".$locale['global_300'].".

\n"; echo $no_theme_message; die(); } } /** * Set the admin password when needed * * @param $password * * @return bool */ function set_admin_pass($password) { return Authenticate::setAdminCookie($password); } /** * Check if admin password matches userdata * * @param string $password * * @return boolean */ function check_admin_pass($password) { return Authenticate::validateAuthAdmin($password); } /** * Redirect browser using header or script function * * @param $location - Desintation URL * @param bool|FALSE $delay - meta refresh delay * @param bool|FALSE $script - true if you want to redirect via javascript * @param int $code * * @define STOP_REDIRECT to prevent redirection */ function redirect($location, $delay = FALSE, $script = FALSE, $code = 200) { //define('STOP_REDIRECT', true); //$location = fusion_get_settings('site_seo') && defined('IN_PERMALINK') ? FUSION_ROOT.$location : $location; if (!defined('STOP_REDIRECT')) { if (isnum($delay)) { $ref = ""; add_to_head($ref); } else { if ($script == FALSE && !headers_sent()) { set_status_header($code); header("Location: ".str_replace("&", "&", $location)); exit; } else { echo "\n"; exit; } } } else { debug_print_backtrace(); echo "redirected to ".$location; } } /** * Set HTTP status header * * @param int $code status header code * * @return bool whether header was sent */ function set_status_header($code = 200) { if (headers_sent()) { return FALSE; } $protocol = $_SERVER['SERVER_PROTOCOL']; if ('HTTP/1.1' != $protocol && 'HTTP/1.0' != $protocol) { $protocol = 'HTTP/1.0'; } $desc = [ 100 => 'Continue', 101 => 'Switching Protocols', 102 => 'Processing', 200 => 'OK', 201 => 'Created', 202 => 'Accepted', 203 => 'Non-Authoritative Information', 204 => 'No Content', 205 => 'Reset Content', 206 => 'Partial Content', 207 => 'Multi-Status', 226 => 'IM Used', 300 => 'Multiple Choices', 301 => 'Moved Permanently', 302 => 'Found', 303 => 'See Other', 304 => 'Not Modified', 305 => 'Use Proxy', 306 => 'Reserved', 307 => 'Temporary Redirect', 400 => 'Bad Request', 401 => 'Unauthorized', 402 => 'Payment Required', 403 => 'Forbidden', 404 => 'Not Found', 405 => 'Method Not Allowed', 406 => 'Not Acceptable', 407 => 'Proxy Authentication Required', 408 => 'Request Timeout', 409 => 'Conflict', 410 => 'Gone', 411 => 'Length Required', 412 => 'Precondition Failed', 413 => 'Request Entity Too Large', 414 => 'Request-URI Too Long', 415 => 'Unsupported Media Type', 416 => 'Requested Range Not Satisfiable', 417 => 'Expectation Failed', 422 => 'Unprocessable Entity', 423 => 'Locked', 424 => 'Failed Dependency', 426 => 'Upgrade Required', 500 => 'Internal Server Error', 501 => 'Not Implemented', 502 => 'Bad Gateway', 503 => 'Service Unavailable', 504 => 'Gateway Timeout', 505 => 'HTTP Version Not Supported', 506 => 'Variant Also Negotiates', 507 => 'Insufficient Storage', 510 => 'Not Extended' ]; $desc = isset($desc[$code]) ? $desc[$code] : ''; header("$protocol $code $desc"); return TRUE; } /** * Clean URL Function, prevents entities in server globals * * @param string $url * * @return string */ function cleanurl($url) { $bad_entities = ["&", "\"", "'", '\"', "\'", "<", ">", "", "", "*"]; $safe_entities = ["&", "", "", "", "", "", "", "", "", ""]; return str_replace($bad_entities, $safe_entities, $url); } /** * Strip Input Function, prevents HTML in unwanted places * * @param string|string[] $text * * @return string|string[] */ function stripinput($text) { if (!is_array($text)) { return str_replace('\\', '\', htmlspecialchars(stripslash(trim($text)), ENT_QUOTES)); } foreach ($text as $i => $item) { $text[$i] = stripinput($item); } return $text; } /** * Strips all "; return $res; } else { return $email; } } /** * Format spaces and tabs in code bb tags * * @param string $text * * @return string */ function formatcode($text) { $text = str_replace( [" ", " ", "\t"], ["  ", "  ", "   "], $text ); $text = preg_replace("/^ {1}/m", " ", $text); return $text; } /** * Highlights given words in subject * * @param array $word The highlighted word * @param string $subject The source text * * @return string */ function highlight_words($word, $subject) { for ($i = 0, $l = count($word); $i < $l; $i++) { $word[$i] = str_replace([ "\\", "+", "*", "?", "[", "^", "]", "$", "(", ")", "{", "}", "=", "!", "<", ">", "|", ":", "#", "-", "_" ], "", $word[$i]); if (!empty($word[$i])) { $subject = preg_replace("#($word[$i])(?![^<]*>)#i", "\${1}", $subject); } } return $subject; } /** * This function sanitize news & article submissions * * @param string $text * @param boolean $striptags FALSE if you don't want to remove html tags. TRUE by default * * @return string */ function descript($text, $striptags = TRUE) { // Convert problematic ascii characters to their true values $patterns = [ '#(&\#x)([0-9A-F]+);*#si' => '', '#(<[^>]+[/\"\'\s])(onmouseover|onmousedown|onmouseup|onmouseout|onmousemove|onclick|ondblclick|onfocus|onload|xmlns)[^>]*>#iU' => '>', '#([a-z]*)=([\`\'\"]*)script:#iU' => '$1=$2nojscript...', '#([a-z]*)=([\`\'\"]*)javascript:#iU' => '$1=$2nojavascript...', '#([a-z]*)=([\'\"]*)vbscript:#iU' => '$1=$2novbscript...', '#(<[^>]+)style=([\`\'\"]*).*expression\([^>]*>#iU' => "$1>", '#(<[^>]+)style=([\`\'\"]*).*behaviour\([^>]*>#iU' => "$1>" ]; foreach (array_merge(['(', ')', ':'], range('A', 'Z'), range('a', 'z')) as $chr) { $patterns["#(&\#)(0*".ord($chr)."+);*#si"] = $chr; } if ($striptags) { do { $count = 0; $text = preg_replace('#]*>#i', "", $text, -1, $count); } while ($count); } return preg_replace(array_keys($patterns), $patterns, $text); } /** * Scan image files for malicious code * * @param string $file * * @return boolean */ function verify_image($file) { $txt = file_get_contents($file); $patterns = [ '#\<\?php#i', '#&(quot|lt|gt|nbsp);#i', '#&\#x([0-9a-f]+);#i', '#&\#([0-9]+);#i', "#([a-z]*)=([\`\'\"]*)script:#iU", "#([a-z]*)=([\`\'\"]*)javascript:#iU", "#([a-z]*)=([\'\"]*)vbscript:#iU", "#(<[^>]+)style=([\`\'\"]*).*expression\([^>]*>#iU", "#(<[^>]+)style=([\`\'\"]*).*behaviour\([^>]*>#iU", "#]*>#i" ]; foreach ($patterns as $pattern) { if (preg_match($pattern, $txt)) { return FALSE; } } return TRUE; } /** * Replace offensive words with the defined replacement word * * @param string $text * * @return string */ function censorwords($text) { $settings['bad_words'] = trim(fusion_get_settings('bad_words')); $settings['bad_words_enabled'] = (boolean)fusion_get_settings('bad_words_enabled'); $settings['bad_word_replace'] = fusion_get_settings('bad_word_replace'); if ($settings['bad_words_enabled'] && $settings['bad_words']) { $words = preg_quote($settings['bad_words'], "/"); $words = preg_replace("/\\s+/", "|", $words); $text = preg_replace("/".$words."/si", $settings['bad_word_replace'], $text); } return $text; } /** * Get a user level's name by the numeric code of level * * @param int $userlevel * * @return string * @global array $locale * */ function getuserlevel($userlevel) { $locale = fusion_get_locale(); $userlevels = [ USER_LEVEL_MEMBER => $locale['user1'], USER_LEVEL_ADMIN => $locale['user2'], USER_LEVEL_SUPER_ADMIN => $locale['user3'] ]; return isset($userlevels[$userlevel]) ? $userlevels[$userlevel] : NULL; } /** * Get a user status by the numeric code of the status * * @param int $userstatus * * @return string|NULL NULL if the status does not exist * @global array $locale * */ function getuserstatus($userstatus) { $locale = fusion_get_locale(); return ($userstatus >= 0 and $userstatus <= 8) ? $locale['status'.$userstatus] : NULL; } /** * Check if Administrator has correct rights assigned * * @param string $right The code of the right * * @return boolean */ function checkrights($right) { if (iADMIN && in_array($right, explode(".", iUSER_RIGHTS))) { return TRUE; } else { return FALSE; } } /** * Function to redirect on invalid page access. * * @param $rights * @param bool $debug */ function pageAccess($rights, $debug = FALSE) { $error = []; if ($debug) { print_p('Admin Panel mode'); } if (!defined('iAUTH')) { $error[] = 'iAuth error'; } if (!isset($_GET['aid'])) { $error[] = 'Aid link error'; } if (iADMIN && !empty($_GET['aid'])) { if ($_GET['aid'] != iAUTH) { $error[] = 'Aidlink mismatch. '.iAUTH.' != '.$_GET['aid']."
"; $error[] .= USER_IP; } } else { $error[] = "You are logged out while accessing admin panel"; } if (!checkrights($rights)) { $error[] = 'Checkrights Error'; } if (!empty($error)) { if ($debug) { print_p($error); } else { redirect(BASEDIR); } } } /** * Check if user is assigned to the specified user group * * @param int $group * * @return boolean */ function checkgroup($group) { if (iSUPERADMIN) { return TRUE; } else if (iADMIN && ($group == "0" || $group == USER_LEVEL_MEMBER || $group == USER_LEVEL_ADMIN)) { return TRUE; } else if (iMEMBER && ($group == "0" || $group == USER_LEVEL_MEMBER)) { return TRUE; } else if (iGUEST && $group == "0") { return TRUE; } else if (iMEMBER && $group && in_array($group, explode(".", iUSER_GROUPS))) { return TRUE; } else { return FALSE; } } /** * Check access given a user level and user group * * @param $group * @param $user_level * @param $user_groups * * @return bool */ function checkusergroup($group, $user_level, $user_groups) { if ($user_level == USER_LEVEL_SUPER_ADMIN) { return TRUE; } else if ($user_level == USER_LEVEL_ADMIN && ($group == 0 || $group == USER_LEVEL_MEMBER || $group == USER_LEVEL_ADMIN)) { return TRUE; } else if ($user_level == USER_LEVEL_MEMBER && ($group == 0 || $group == USER_LEVEL_MEMBER)) { return TRUE; } else if ($user_level == USER_LEVEL_PUBLIC && $group == 0) { return TRUE; } else if ($user_level == USER_LEVEL_MEMBER && $group && in_array($group, explode('.', $user_groups))) { return TRUE; } return FALSE; } /** * Cache groups' data into an array * * @return array */ function cache_groups() { static $groups_cache = NULL; if ($groups_cache === NULL) { $groups_cache = []; $result = dbquery("SELECT * FROM ".DB_USER_GROUPS." ORDER BY group_id ASC"); while ($data = dbarray($result)) { $groups_cache[] = $data; } } return $groups_cache; } /** * Compile access levels & user group array * * @return array structure of elements: array($levelOrGroupid, $levelnameOrGroupname, $levelGroupDescription, * $levelGroupIcon) * @global array $locale */ function getusergroups() { $locale = fusion_get_locale(); $groups_array = [ [USER_LEVEL_PUBLIC, $locale['user0'], $locale['user0'], 'fa fa-user'], [USER_LEVEL_MEMBER, $locale['user1'], $locale['user1'], 'fa fa-user'], [USER_LEVEL_ADMIN, $locale['user2'], $locale['user2'], 'fa fa-user'], [USER_LEVEL_SUPER_ADMIN, $locale['user3'], $locale['user3'], 'fa fa-user'] ]; $groups_cache = cache_groups(); foreach ($groups_cache as $group) { $group_icon = !empty($group['group_icon']) ? $group['group_icon'] : ''; array_push($groups_array, [$group['group_id'], $group['group_name'], $group['group_description'], $group_icon]); } return $groups_array; } /** * Get the name of the access level or user group * * @param int $group_id * @param boolean $return_desc If TRUE, group_description will be returned instead of group_name * @param boolean $return_icon If TRUE, group_icon will be returned instead of group_icon group_name * * @return bool * @global array $locale * */ function getgroupname($group_id, $return_desc = FALSE, $return_icon = FALSE) { foreach (getusergroups() as $group) { if ($group_id == $group[0]) { return ($return_desc ? ($group[2] ?: '-') : (!empty($group[3]) && $return_icon ? " " : "").$group[1]); } } return FALSE; } /** * Get All Groups Arrays * * @return array */ function fusion_get_groups() { $visibility_opts = []; foreach (getusergroups() as $groups) { $visibility_opts[$groups[0]] = $groups[1]; } return $visibility_opts; } /** * Getting the real users_group access. * Return true or false. (BOOLEAN) * * @param $field * * @return bool */ function users_groupaccess($field) { if (preg_match("(^\.{$field}$|\.{$field}\.|\.{$field}$)", fusion_get_userdata('user_groups'))) { return TRUE; } return FALSE; } /** * Getting the access levels used when asking the database for data * * @param string $field * * @return string The part of WHERE clause. Always returns a condition */ function groupaccess($field) { $res = ''; if (iGUEST) { $res = $field." = ".USER_LEVEL_PUBLIC; } else if (iSUPERADMIN) { $res = "1 = 1"; } else if (iADMIN) { $res = $field." in (".USER_LEVEL_PUBLIC.", ".USER_LEVEL_MEMBER.", ".USER_LEVEL_ADMIN.")"; } else if (iMEMBER) { $res = $field." in (".USER_LEVEL_PUBLIC.", ".USER_LEVEL_MEMBER.")"; } if (iUSER_GROUPS != "" && !iSUPERADMIN) { $res = "(".$res." OR $field='".str_replace(".", "' OR $field='", iUSER_GROUPS)."')"; } return $res; } /** * UF blacklist for SQL - same as groupaccess() but $field is the user_id column. * * @param string $field The name of the field * * @return string It can return an empty condition! */ function blacklist($field) { $userdata = fusion_get_userdata('user_id'); $blacklist = []; if (in_array('user_blacklist', fieldgenerator(DB_USERS))) { if (!empty($userdata['user_id'])) { $result = dbquery("SELECT user_id, user_level FROM ".DB_USERS." WHERE user_blacklist REGEXP('^\\\.{$userdata['user_id']}$|\\\.{$userdata['user_id']}\\\.|\\\.{$userdata['user_id']}$')"); if (dbrows($result) > 0) { while ($data = dbarray($result)) { if ($data['user_level'] > USER_LEVEL_ADMIN) { $blacklist[] = $data['user_id']; // all users to filter } } } } $i = 0; $sql = ''; foreach ($blacklist as $id) { $sql .= ($i > 0) ? "AND $field !='$id'" : "($field !='$id'"; $i++; } $sql .= $sql ? ")" : ' 1=1 '; return "$sql"; } else { return ""; } } /** * check if user was blacklisted by a member * * @param int $user_id * * @return boolean * @global string[] $userdata * */ function user_blacklisted($user_id) { return in_array('user_blacklist', fieldgenerator(DB_USERS)) and in_array($user_id, explode('.', fusion_get_userdata('user_blacklist'))); } /** * Create a list of files or folders and store them in an array * * @param string $folder * @param string $filter - The names of the filtered folder separated by "|", FALSE to use default filter * @param boolean $sort - FALSE if you don't want to sort the result. TRUE by default * @param string $type - possible values: 'files' to list files, 'folders' to list folders * @param string $ext_filter - file extensions separated by "|". Only when $type is 'files' * * @return array */ function makefilelist($folder, $filter = '', $sort = TRUE, $type = "files", $ext_filter = "") { $res = []; $default_filters = '.|..|.DS_Store'; if ($filter === FALSE) { $filter = $default_filters; } $filter = explode("|", $filter); if ($type == "files" && !empty($ext_filter)) { $ext_filter = explode("|", strtolower($ext_filter)); } if (file_exists($folder)) { $temp = opendir($folder); while ($file = readdir($temp)) { if ($type == "files" && !in_array($file, $filter)) { if (!empty($ext_filter)) { if (!in_array(substr(strtolower(stristr($file, '.')), +1), $ext_filter) && !is_dir($folder.$file)) { $res[] = $file; } } else { if (is_file($folder.$file)) { $res[] = $file; } } } else if ($type == "folders" && !in_array($file, $filter)) { if (is_dir($folder.$file)) { $res[] = $file; } } } closedir($temp); if ($sort) { sort($res); } } else { $error_log = debug_backtrace()[1]; $function = (isset($error_log['class']) ? $error_log['class'] : '').(isset($error_log['type']) ? $error_log['type'] : '').(isset($error_log['function']) ? $error_log['function'] : ''); $error_log = strtr(fusion_get_locale('err_103', LOCALE.LOCALESET.'errors.php'), [ '{%folder%}' => $folder, '{%function%}' => (!empty($function) ? ''.$function.'' : '') ]); setError(2, $error_log, debug_backtrace()[1]['file'], debug_backtrace()[1]['line'], ''); } return $res; } /** * Create a selection list from an array created by makefilelist() * * @param string[] $files * @param string $selected * * @return string */ function makefileopts(array $files, $selected = "") { $res = ""; foreach ($files as $file) { $sel = ($selected == $file ? " selected='selected'" : ""); $res .= "\n"; } return $res; } /** * Making Page Navigation * * @param int $start The number of the first listed item - $_GET['rowstart'] * @param int $count The number of displayed items - LIMIT on sql * @param int $total The number of all items - a dbcount of total * @param int $range The number of links before and after the current page * @param string $link The base url before the appended part * @param string $getname the variable name in the query string which stores * the number of the current page * @param boolean $button Displays as button * * @return boolean|string FALSE if $count is invalid * @global array $locale * */ function makepagenav($start, $count, $total, $range = 0, $link = "", $getname = "rowstart", $button = FALSE) { $locale = fusion_get_locale(); /* Bootstrap may be disabled in theme (see Gillette for example) without settings change in DB. In such case this function will not work properly. With this fix (used $settings instead fusion_get_settings) function will work.*/ if (fusion_get_settings("bootstrap") || defined('BOOTSTRAP')) { $tpl_global = "\n"; $tpl_currpage = "%d\n"; $tpl_page = "%s\n"; $tpl_divider = "\n
"; $tpl_firstpage = "1\n"; $tpl_lastpage = "%s\n"; $tpl_button = "%s\n"; } else { $tpl_global = "\n"; $tpl_currpage = "%d"; $tpl_page = "%s"; $tpl_divider = "..."; $tpl_firstpage = "1"; $tpl_lastpage = "%s\n"; $tpl_button = "%s\n"; } if ($link == '') { $link = FUSION_SELF."?"; if (fusion_get_settings("site_seo") && defined('IN_PERMALINK')) { global $filepath; $link = $filepath."?"; } } if (!preg_match("#[0-9]+#", $count) || $count == 0) { return FALSE; } $pg_cnt = ceil($total / $count); if ($pg_cnt <= 1) { return ""; } $idx_back = $start - $count; $idx_next = $start + $count; if ($button == TRUE) { if ($idx_next >= $total) { return sprintf($tpl_button, 0, $link.$getname, 0, $locale['load_end']); } else { return sprintf($tpl_button, $idx_next, $link.$getname, $idx_next, $locale['load_more']); } } $cur_page = ceil(($start + 1) / $count); $res = ""; if ($idx_back >= 0) { if ($cur_page > ($range + 1)) { $res .= sprintf($tpl_firstpage, $link.$getname); if ($cur_page != ($range + 2)) { $res .= $tpl_divider; } } } $idx_fst = max($cur_page - $range, 1); $idx_lst = min($cur_page + $range, $pg_cnt); if ($range == 0) { $idx_fst = 1; $idx_lst = $pg_cnt; } for ($i = $idx_fst; $i <= $idx_lst; $i++) { $offset_page = ($i - 1) * $count; if ($i == $cur_page) { $res .= sprintf($tpl_currpage, $link.$getname, $offset_page, $i); } else { $res .= sprintf($tpl_page, $offset_page, $link.$getname, $offset_page, $i); } } if ($idx_next < $total) { if ($cur_page < ($pg_cnt - $range)) { if ($cur_page != ($pg_cnt - $range - 1)) { $res .= $tpl_divider; } $res .= sprintf($tpl_lastpage, ($pg_cnt - 1) * $count, $link.$getname, ($pg_cnt - 1) * $count, $pg_cnt); } } return sprintf($tpl_global, "".$locale['global_092']." ".$cur_page.$locale['global_093'].$pg_cnt." ", $res); } /** * @param string $scroll_url The ajax script that loads the content * @param int $rowstart Current rowstart - $_GET['rowstart'] * @param int $total_count The total rows - dbrows($result); * @param string $getname Default is 'rowstart' * @param string $additional_http_query '§ion=some_section' * * @return string */ function infinite_scroll($scroll_url, $rowstart = 0, $total_count = 0, $getname = 'rowstart', $additional_http_query = '') { $locale = fusion_get_locale(); add_to_jquery(" var count = $rowstart+1; $(window).scroll(function(){ if ($(window).scrollTop() == ($(document).height() - $(window).height())) { if (count <= '$total_count') { loadInfinityContent(count); count++; } } }); function loadInfinityContent(pageNumber){ $('.infiniteLoader').show('fast'); $.ajax({ url: '$scroll_url', type:'GET', data: 'action=infinite_scroll&$getname='+ pageNumber +'".($additional_http_query ? "&".$additional_http_query : '')."', success: function(html){ $('.infiniteLoader').hide(); $('#scroll_target').append(html); // This will be the div where our content will be loaded } }); return false; } "); return "
"; } /** * Hierarchy Page Breadcrumbs * This function generates breadcrumbs on all your category needs on $_GET['rownav'] as your cat_id * * @param array $tree_index dbquery_tree(DB_NEWS_CATS, "news_cat_id", "news_cat_parent") / tree_index(dbquery_tree_full(DB_NEWS_CATS, "news_cat_id", "news_cat_parent")) * @param array $tree_full dbquery_tree_full(DB_NEWS_CATS, "news_cat_id", "news_cat_parent") * @param $id_col "news_cat_id", * @param $title_col "news_cat_name", * @param string $getname cat_id for $_GET['cat_id'] * @param string $key key for breadcrumb instance */ function make_page_breadcrumbs($tree_index, $tree_full, $id_col, $title_col, $getname = "rownav", $key = 'default') { $_GET[$getname] = !empty($_GET[$getname]) && isnum($_GET[$getname]) ? $_GET[$getname] : 0; // Recursive fatal protection if (!function_exists('breadcrumb_page_arrays')) { function breadcrumb_page_arrays($tree_index, $tree_full, $id_col, $title_col, $getname, $id) { $crumb = []; if (isset($tree_index[get_parent($tree_index, $id)])) { $_name = get_parent_array($tree_full, $id); $crumb = [ 'link' => isset($_name[$id_col]) ? clean_request($getname."=".$_name[$id_col], ["aid"], TRUE) : "", 'title' => isset($_name[$title_col]) ? \PHPFusion\QuantumFields::parse_label($_name[$title_col]) : "", ]; if (get_parent($tree_index, $id) == 0) { return $crumb; } $crumb_1 = breadcrumb_page_arrays($tree_index, $tree_full, $id_col, $title_col, $getname, get_parent($tree_index, $id)); if (!empty($crumb_1)) { $crumb = array_merge_recursive($crumb, $crumb_1); } } return $crumb; } } // then we make a infinity recursive function to loop/break it out. $crumb = breadcrumb_page_arrays($tree_index, $tree_full, $id_col, $title_col, $getname, $_GET[$getname]); // then we sort in reverse. $title_count = !empty($crumb['title']) && is_array($crumb['title']) ? count($crumb['title']) > 1 : 0; if ($title_count) { krsort($crumb['title']); krsort($crumb['link']); } if ($title_count) { foreach ($crumb['title'] as $i => $value) { \PHPFusion\BreadCrumbs::getInstance($key)->addBreadCrumb(['link' => $crumb['link'][$i], 'title' => $value]); if ($i == count($crumb['title']) - 1) { OutputHandler::addToTitle($GLOBALS['locale']['global_200'].$value); OutputHandler::addToMeta($value); } } } else if (isset($crumb['title'])) { OutputHandler::addToTitle($GLOBALS['locale']['global_200'].$crumb['title']); OutputHandler::addToMeta($crumb['title']); \PHPFusion\BreadCrumbs::getInstance($key)->addBreadCrumb(['link' => $crumb['link'], 'title' => $crumb['title']]); } } /** * Format the date & time accordingly * * @param string $format shortdate, longdate, forumdate, newsdate or date pattern for the strftime * @param int $val unix timestamp * @param array $options * * @return string * @global string[] $settings * @global string[] $userdata * */ function showdate($format, $val, $options = []) { $userdata = fusion_get_userdata(); if (isset($options['tz_override'])) { $tz_client = $options['tz_override']; } else { if (!empty($userdata['user_timezone'])) { $tz_client = $userdata['user_timezone']; } else { $tz_client = fusion_get_settings('timeoffset'); } } if (empty($tz_client)) { $tz_client = 'Europe/London'; } $client_dtz = new DateTimeZone($tz_client); $client_dt = new DateTime('now', $client_dtz); $offset = $client_dtz->getOffset($client_dt); if (!empty($val)) { if (in_array($format, ['shortdate', 'longdate', 'forumdate', 'newsdate'])) { $format = fusion_get_settings($format); $offset = intval($val) + $offset; return strftime($format, $offset); } else { $offset = intval($val) + $offset; return strftime($format, $offset); } } else { $format = fusion_get_settings($format); $offset = intval(TIME) + $offset; return strftime($format, $offset); } } /** * Translate bytes into kB, MB, GB or TB by CrappoMan, lelebart fix * * @param int $size The number of bytes * @param int $digits Precision * @param boolean $dir TRUE if it is the size of a directory * * @return string * @global array $locale * */ function parsebytesize($size, $digits = 2, $dir = FALSE) { $locale = fusion_get_locale(); $kb = 1024; $mb = 1024 * $kb; $gb = 1024 * $mb; $tb = 1024 * $gb; $size = (empty($size)) ? "0" : $size; if (($size == 0) && ($dir)) { return "0 ".$locale['global_460']; } else if ($size < $kb) { return $size.$locale['global_461']; } else if ($size < $mb) { return round($size / $kb, $digits).'kB'; } else if ($size < $gb) { return round($size / $mb, $digits).'MB'; } else if ($size < $tb) { return round($size / $gb, $digits).'GB'; } else { return round($size / $tb, $digits).'TB'; } } /** * User profile link * * @param int $user_id * @param string $user_name * @param int $user_status * @param string $class html class of link * @param bool $display_link * * @return string */ function profile_link($user_id, $user_name, $user_status, $class = "profile-link", $display_link = TRUE) { $locale = fusion_get_locale(); $settings = fusion_get_settings(); $class = ($class ? "class='$class'" : ""); if ((in_array($user_status, [ 0, 3, 7 ]) || checkrights("M")) && (iMEMBER || $settings['hide_userprofiles'] == "0") && $display_link == TRUE ) { $link = "".$user_name.""; } else if ($user_status == "5" || $user_status == "6") { $link = $locale['user_anonymous']; } else { $link = $user_name; } return $link; } /** * Variable dump printer for debugging purposes * * @param $array * @param bool $modal * @param bool $print * * @return string */ function print_p($array, $modal = FALSE, $print = TRUE) { ob_start(); echo htmlspecialchars(print_r($array, TRUE), ENT_QUOTES, 'utf-8'); $debug = ob_get_clean(); if ($modal == TRUE) { $modal = openmodal('Debug', 'Debug'); $modal .= "
";
        $modal .= $debug;
        $modal .= "
\n"; $modal .= closemodal(); PHPFusion\OutputHandler::addToFooter($modal); return FALSE; } if ($print == TRUE) { echo "
";
        echo $debug;
        echo "
\n"; } return $debug; } /** * Fetch the settings from the database * * @param string $key The key of one setting * * @return string[]|string Associative array of settings or one setting by key * if $key was given */ function fusion_get_settings($key = NULL) { // It is initialized only once because of 'static' static $settings = []; if (empty($settings) and defined('DB_SETTINGS') and dbconnection() && db_exists('settings')) { $result = dbquery("SELECT * FROM ".DB_SETTINGS); while ($data = dbarray($result)) { $settings[$data['settings_name']] = $data['settings_value']; } } return $key === NULL ? $settings : (isset($settings[$key]) ? $settings[$key] : NULL); } /** * Get Locale * Fetch a given locale key * * @param string $key - The key of one setting * @param string $include_file - The full path of the file which to be included, can be either string or array * * @return null */ function fusion_get_locale($key = NULL, $include_file = '') { $locale = \PHPFusion\Locale::getInstance('default'); if ($include_file) { $locale::setLocale($include_file); } return $locale->getLocale($key); } /** * Fetches username * * @param $user_id * * @return string */ function fusion_get_username($user_id) { $result = NULL; $result = (dbresult(dbquery("SELECT user_name FROM ".DB_USERS." WHERE user_id='".intval($user_id)."'"), 0)); return ($result !== NULL) ? $result : fusion_get_locale("na"); } /** * Get a user own data * * @param string $key - The column of one user information * * @return null */ function fusion_get_userdata($key = NULL) { global $userdata; if (empty($userdata)) { $userdata = ["user_level" => 0, "user_rights" => "", "user_groups" => "", "user_theme" => 'Default']; } $userdata = $userdata + [ "user_id" => 0, "user_name" => fusion_get_locale("user_guest"), "user_status" => 1, "user_level" => 0, "user_rights" => "", "user_groups" => "", "user_theme" => fusion_get_settings("theme"), ]; return $key === NULL ? $userdata : (isset($userdata[$key]) ? $userdata[$key] : NULL); } /** * Get any users data * * @param $user_id - the user id * @param null $key - the keys of your user id * * @return mixed */ function fusion_get_user($user_id, $key = NULL) { global $performance_test; static $user = []; if (!isset($user[$user_id]) && isnum($user_id)) { $user[$user_id] = dbarray(dbquery("SELECT * FROM ".DB_USERS." WHERE user_id='".intval($user_id)."'")); // check how many times this query is made with the same user. $performance_test = $performance_test + 1; } if (!isset($user[$user_id])) { return NULL; } return $key === NULL ? $user[$user_id] : (isset($user[$user_id][$key]) ? $user[$user_id][$key] : NULL); } /** * Get Aidlink * * @return string */ function fusion_get_aidlink() { $aidlink = ''; if (defined('iADMIN') && iADMIN && defined('iAUTH')) { $aidlink = '?aid='.iAUTH; } return (string)$aidlink; } /** * Get form tokens * * @param $form_id * @param int $max_tokens * * @return string */ function fusion_get_token($form_id, $max_tokens = 5) { return \defender\Token::generate_token($form_id, $max_tokens); } /** * Fetch PM Settings * * @param $user_id * @param null $key - user_inbox, user_outbox, user_archive, user_pm_email_notify, user_pm_save_sent * * @return array|bool|null */ function user_pm_settings($user_id, $key = NULL) { return \PHPFusion\PrivateMessages::get_pm_settings($user_id, $key); } /** * Run the installer or halt the script */ function fusion_run_installer() { if (file_exists("install.php")) { redirect("install.php"); } else { die("No config.php or install.php files were found"); } } /*------------------------- * Language Handling +-------------------------/ /** * Define Site Language * @param $lang */ function define_site_language($lang) { if (valid_language($lang)) { define('LANGUAGE', $lang); define('LOCALESET', $lang.'/'); } } // Set the requested language function set_language($lang) { $userdata = fusion_get_userdata(); if (valid_language($lang)) { if (iMEMBER) { dbquery("UPDATE ".DB_USERS." SET user_language='".$lang."' WHERE user_id='".$userdata['user_id']."'"); } else { $rows = dbrows(dbquery("SELECT user_language FROM ".DB_LANGUAGE_SESSIONS." WHERE user_ip='".USER_IP."'")); if ($rows != 0) { dbquery("UPDATE ".DB_LANGUAGE_SESSIONS." SET user_language='".$lang."', user_datestamp='".time()."' WHERE user_ip='".USER_IP."'"); } else { dbquery("INSERT INTO ".DB_LANGUAGE_SESSIONS." (user_ip, user_language, user_datestamp) VALUES ('".USER_IP."', '".$lang."', '".TIME."');"); } // Sanitize guest sessions occasionally dbquery("DELETE FROM ".DB_LANGUAGE_SESSIONS." WHERE user_datestamp<'".(TIME - (86400 * 60))."'"); } } } /** * Check if a given language is valid or if exists * Checks whether a language can be found in enabled languages array * Can also be used to check whether a language actually exists * * @param string $lang * @param bool $file_check intended to be used when enabling languages in Admin Panel * * @return bool */ function valid_language($lang, $file_check = FALSE) { $enabled_languages = fusion_get_enabled_languages(); if (preg_match("/^([a-z0-9_-]){2,50}$/i", $lang) && ($file_check ? file_exists(LOCALE.$lang."/global.php") : isset($enabled_languages[$lang])) ) { return TRUE; } else { return FALSE; } } /** * Create a selection list of possible languages in list * * @param string $selected_language * * @return string * @todo rename it from get_available_languages_list to a more proper name * */ function get_available_languages_list($selected_language = "") { $enabled_languages = fusion_get_enabled_languages(); $res = ""; foreach ($enabled_languages as $language) { $sel = ($selected_language == $language ? " selected='selected'" : ""); $label = str_replace('_', ' ', $language); $res .= "\n"; } return $res; } /** * Get Language Switch Arrays * * @return array */ function fusion_get_language_switch() { static $language_switch = []; if (empty($language_link)) { $enabled_languages = fusion_get_enabled_languages(); foreach ($enabled_languages as $language => $language_name) { $link = clean_request('lang='.$language, ['lang'], FALSE); $language_switch[$language] = [ "language_name" => $language_name, "language_icon_s" => BASEDIR."locale/$language/$language-s.png", "language_icon" => BASEDIR."locale/$language/$language.png", "language_link" => $link, ]; } } return (array)$language_switch; } /** * Language switcher function * * @param bool|TRUE $icon */ function lang_switcher($icon = TRUE) { $locale = fusion_get_locale(); $enabled_languages = fusion_get_enabled_languages(); if (count($enabled_languages) <= 1) { return; } openside($locale['global_ML102']); echo "
".$locale['UM101']."
\n"; if ($icon) { $language_switch = fusion_get_language_switch(); if (!empty($language_switch)) { $row = 0; foreach ($language_switch as $folder => $langData) { $icon = "".$langData[\n"; if ($folder != LANGUAGE) { $icon = "".$icon."\n "; } echo(($row > 0 and $row % 4 === 0) ? '
' : ''); echo "
\n".$icon."
\n"; $row++; } } } else { include_once INCLUDES."translate_include.php"; echo openform('lang_menu_form', 'post', FUSION_SELF); echo form_select('lang_menu', '', fusion_get_settings('locale'), ["options" => fusion_get_enabled_languages(), "width" => "100%"]); echo closeform(); add_to_jquery(" function showflag(item){ return '
\"'+item.text'+ item.text +'
'; } $('#lang_menu').select2({ placeholder: '".$locale['global_ML103']."', formatSelection: showflag, escapeMarkup: function(m) { return m; }, formatResult: showflag, }).bind('change', function(item) { window.location.href = '".FUSION_REQUEST."?lang='+$(this).val(); }); "); } closeside(); } /** * Detect whether the system is installed and return the config file path * * @return string */ function fusion_detect_installation() { $config_path = dirname(__DIR__).'/config.php'; if (!is_file($config_path) or !filesize($config_path)) { fusion_run_installer(); } return $config_path; } /** * Get the array of enabled languages * * @staticvar string[] $enabled_languages * @return string[] */ function fusion_get_enabled_languages() { $settings = fusion_get_settings(); static $enabled_languages = NULL; if ($enabled_languages === NULL) { if (isset($settings['enabled_languages'])) { $values = explode('.', $settings['enabled_languages']); foreach ($values as $language_name) { $enabled_languages[$language_name] = translate_lang_names($language_name); } } } return (array)$enabled_languages; } function fusion_get_detected_language() { static $detected_languages = NULL; if ($detected_languages === NULL) { $all_languages = makefilelist(LOCALE, ".svn|.|..", TRUE, "folders"); foreach ($all_languages as $language_name) { $detected_languages[$language_name] = translate_lang_names($language_name); } } return (array)$detected_languages; } /** * Log user actions * * @param $user_id * @param $column_name - affected column * @param $new_value * @param $old_value * Note: Showing $action can be done using $locale in 9.1 via registration in a table */ function save_user_log($user_id, $column_name, $new_value, $old_value) { $data = [ "userlog_id" => 0, "userlog_user_id" => $user_id, "userlog_field" => $column_name, "userlog_value_new" => $new_value, "userlog_value_old" => $old_value, "userlog_timestamp" => time(), ]; dbquery_insert(DB_USER_LOG, $data, "save", ["keep_session" => TRUE]); } /** * Minify JS Code * * @param $code * * @return string */ function jsminify($code) { $minifier = new \PHPFusion\Minify\JS($code); return $minifier->minify(); } /** * A wrapper function for file_put_contents with cache invalidation * If opcache is enabled on the server, this function will write the file * as the original file_put_contents and invalidate the cache of the file. * It is needed when you create a file dynamically and want to include it * before the cache is invalidated. Redirection does not matter. * * @param string $file file path * @param string|string[] $data * @param int $flags * * @return int Number of written bytes */ function write_file($file, $data, $flags = NULL) { $bytes = NULL; if ($flags === NULL) { $bytes = \file_put_contents($file, $data); } else { $bytes = \file_put_contents($file, $data, $flags); } if (function_exists('opcache_invalidate')) { \opcache_invalidate($file, TRUE); } return $bytes; } /** * Returns nearest data unit * * @param $total_bit * * @return int */ function calculate_byte($total_bit) { $calc_opts = fusion_get_locale('1020', LOCALE.LOCALESET."admin/settings.php"); foreach ($calc_opts as $byte => $val) { if ($total_bit / $byte <= 999) { return (int)$byte; } } return 1048576; }