<?php

	#########################################################
	/*
	~~~~~~ LIST OF FUNCTIONS ~~~~~~
		getTableList() -- returns an associative array (tableName => tableData, tableData is array(tableCaption, tableDescription, tableIcon)) of tables accessible by current user
		get_table_groups() -- returns an associative array (table_group => tables_array)
		logInMember() -- checks POST login. If not valid, redirects to index.php, else returns TRUE
		getTablePermissions($tn) -- returns an array of permissions allowed for logged member to given table (allowAccess, allowInsert, allowView, allowEdit, allowDelete) -- allowAccess is set to true if any access level is allowed
		get_sql_fields($tn) -- returns the SELECT part of the table view query
		get_sql_from($tn[, true, [, false]]) -- returns the FROM part of the table view query, with full joins (unless third paramaeter is set to true), optionally skipping permissions if true passed as 2nd param.
		get_joined_record($table, $id[, true]) -- returns assoc array of record values for given PK value of given table, with full joins, optionally skipping permissions if true passed as 3rd param.
		get_defaults($table) -- returns assoc array of table fields as array keys and default values (or empty), excluding automatic values as array values
		htmlUserBar() -- returns html code for displaying user login status to be used on top of pages.
		showNotifications($msg, $class) -- returns html code for displaying a notification. If no parameters provided, processes the GET request for possible notifications.
		parseMySQLDate(a, b) -- returns a if valid mysql date, or b if valid mysql date, or today if b is true, or empty if b is false.
		parseCode(code) -- calculates and returns special values to be inserted in automatic fields.
		addFilter(i, filterAnd, filterField, filterOperator, filterValue) -- enforce a filter over data
		clearFilters() -- clear all filters
		loadView($view, $data) -- passes $data to templates/{$view}.php and returns the output
		loadTable($table, $data) -- loads table template, passing $data to it
		filterDropdownBy($filterable, $filterers, $parentFilterers, $parentPKField, $parentCaption, $parentTable, &$filterableCombo) -- applies cascading drop-downs for a lookup field, returns js code to be inserted into the page
		br2nl($text) -- replaces all variations of HTML <br> tags with a new line character
		htmlspecialchars_decode($text) -- inverse of htmlspecialchars()
		entitiesToUTF8($text) -- convert unicode entities (e.g. &#1234;) to actual UTF8 characters, requires multibyte string PHP extension
		func_get_args_byref() -- returns an array of arguments passed to a function, by reference
		permissions_sql($table, $level) -- returns an array containing the FROM and WHERE additions for applying permissions to an SQL query
		error_message($msg[, $back_url]) -- returns html code for a styled error message .. pass explicit false in second param to suppress back button
		toMySQLDate($formattedDate, $sep = datalist_date_separator, $ord = datalist_date_format)
		reIndex(&$arr) -- returns a copy of the given array, with keys replaced by 1-based numeric indices, and values replaced by original keys
		get_embed($provider, $url[, $width, $height, $retrieve]) -- returns embed code for a given url (supported providers: youtube, googlemap)
		check_record_permission($table, $id, $perm = 'view') -- returns true if current user has the specified permission $perm ('view', 'edit' or 'delete') for the given recors, false otherwise
		NavMenus($options) -- returns the HTML code for the top navigation menus. $options is not implemented currently.
		StyleSheet() -- returns the HTML code for included style sheet files to be placed in the <head> section.
		getUploadDir($dir) -- if dir is empty, returns upload dir configured in defaultLang.php, else returns $dir.
		PrepareUploadedFile($FieldName, $MaxSize, $FileTypes='jpg|jpeg|gif|png', $NoRename=false, $dir="") -- validates and moves uploaded file for given $FieldName into the given $dir (or the default one if empty)
		get_home_links($homeLinks, $default_classes, $tgroup) -- process $homeLinks array and return custom links for homepage. Applies $default_classes to links if links have classes defined, and filters links by $tgroup (using '*' matches all table_group values)
		quick_search_html($search_term, $label, $separate_dv = true) -- returns HTML code for the quick search box.
	~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	*/

	#########################################################

	function getTableList($skip_authentication = false) {
		$arrAccessTables = [];
		$arrTables = [
			/* 'table_name' => ['table caption', 'homepage description', 'icon', 'table group name'] */   
			'sugerir_valor' => ['Sugerir Valor de Atividade', '', 'resources/table_icons/coins_add.png', 'Contribui&#231;&#227;o'],
			'sugerir_atividade' => ['Sugerir Nova Atividade', '', 'resources/table_icons/book_add.png', 'Contribui&#231;&#227;o'],
			'c001' => ['Cr&#233;dito Rural, Agroindustrial e outras modalidades', '', 'resources/table_icons/add.png', 'Categorias'],
			'c001_ref' => ['Refer&#234;ncias', '', 'table.gif', 'Categorias'],
			'c001_ref_colaborar' => ['Quero Colaborar', '', 'table.gif', 'Categorias'],
			'c001_ref_inativas' => ['Refer&#234;ncias Gerais', '', 'table.gif', 'Categorias'],
			'categorias' => ['Categorias', '', 'resources/table_icons/chart_pie.png', 'Admin'],
			'referencias_ativas' => ['Refer&#234;ncias (Ativas)', '', 'resources/table_icons/note_add.png', 'Admin'],
			'referencias_inativas' => ['Refer&#234;ncias (Inativas)', '', 'resources/table_icons/note_delete.png', 'Admin'],
			'uta' => ['Unidade do T.A.', '', 'resources/table_icons/cfta.png', 'Admin'],
			'unidades' => ['Unidades', '', 'resources/table_icons/web_concierge.png', 'Admin'],
			'atividades' => ['Atividades', '', 'resources/table_icons/add.png', 'Admin'],
			'c002' => ['Topografia', '', 'resources/table_icons/add.png', 'Categorias'],
			'c002_ref' => ['Refer&#234;ncias', '', 'table.gif', 'Categorias'],
			'c002_ref_colaborar' => ['Quero Colaborar', '', 'table.gif', 'Categorias'],
			'c002_ref_inativas' => ['Refer&#234;ncias Gerais', '', 'table.gif', 'Categorias'],
			'colaborar_atividade' => ['Sugerir nova Atividade', '', 'resources/table_icons/accept.png', 'Contribui&#231;&#227;o'],
			'informacoes' => ['Informa&#231;&#245;es Gerais', '', 'resources/table_icons/cfta.png', 'Informa&#231;&#245;es'],
			'c003' => ['Impacto e Saneamento Ambiental', '', 'resources/table_icons/add.png', 'Categorias'],
			'c003_ref' => ['Refer&#234;ncias', '', 'table.gif', 'Categorias'],
			'c003_ref_colaborar' => ['Quero Colaborar', '', 'table.gif', 'Categorias'],
			'c003_ref_inativas' => ['Refer&#234;ncias Gerais', '', 'table.gif', 'Categorias'],
			'c004' => ['Paisagismo e Jardinagem', '', 'resources/table_icons/add.png', 'Categorias'],
			'c004_ref' => ['Refer&#234;ncias', '', 'table.gif', 'Categorias'],
			'c004_ref_colaborar' => ['Quero Colaborar', '', 'table.gif', 'Categorias'],
			'c004_ref_inativas' => ['Refer&#234;ncias Gerais', '', 'table.gif', 'Categorias'],
		];
		if($skip_authentication || getLoggedAdmin()) return $arrTables;

		if(is_array($arrTables)) {
			foreach($arrTables as $tn => $tc) {
				$arrPerm = getTablePermissions($tn);
				if($arrPerm['access']) $arrAccessTables[$tn] = $tc;
			}
		}

		return $arrAccessTables;
	}

	#########################################################

	function get_table_groups($skip_authentication = false) {
		$tables = getTableList($skip_authentication);
		$all_groups = ['Categorias', 'Contribui&#231;&#227;o', 'Informa&#231;&#245;es', 'Admin'];

		$groups = [];
		foreach($all_groups as $grp) {
			foreach($tables as $tn => $td) {
				if($td[3] && $td[3] == $grp) $groups[$grp][] = $tn;
				if(!$td[3]) $groups[0][] = $tn;
			}
		}

		return $groups;
	}

	#########################################################

	function getTablePermissions($tn) {
		static $table_permissions = [];
		if(isset($table_permissions[$tn])) return $table_permissions[$tn];

		$groupID = getLoggedGroupID();
		$memberID = makeSafe(getLoggedMemberID());
		$res_group = sql("SELECT `tableName`, `allowInsert`, `allowView`, `allowEdit`, `allowDelete` FROM `membership_grouppermissions` WHERE `groupID`='{$groupID}'", $eo);
		$res_user  = sql("SELECT `tableName`, `allowInsert`, `allowView`, `allowEdit`, `allowDelete` FROM `membership_userpermissions`  WHERE LCASE(`memberID`)='{$memberID}'", $eo);

		while($row = db_fetch_assoc($res_group)) {
			$table_permissions[$row['tableName']] = [
				1 => intval($row['allowInsert']),
				2 => intval($row['allowView']),
				3 => intval($row['allowEdit']),
				4 => intval($row['allowDelete']),
				'insert' => intval($row['allowInsert']),
				'view' => intval($row['allowView']),
				'edit' => intval($row['allowEdit']),
				'delete' => intval($row['allowDelete'])
			];
		}

		// user-specific permissions, if specified, overwrite his group permissions
		while($row = db_fetch_assoc($res_user)) {
			$table_permissions[$row['tableName']] = [
				1 => intval($row['allowInsert']),
				2 => intval($row['allowView']),
				3 => intval($row['allowEdit']),
				4 => intval($row['allowDelete']),
				'insert' => intval($row['allowInsert']),
				'view' => intval($row['allowView']),
				'edit' => intval($row['allowEdit']),
				'delete' => intval($row['allowDelete'])
			];
		}

		// if user has any type of access, set 'access' flag
		foreach($table_permissions as $t => $p) {
			$table_permissions[$t]['access'] = $table_permissions[$t][0] = false;

			if($p['insert'] || $p['view'] || $p['edit'] || $p['delete']) {
				$table_permissions[$t]['access'] = $table_permissions[$t][0] = true;
			}
		}

		return $table_permissions[$tn];
	}

	#########################################################

	function get_sql_fields($table_name) {
		$sql_fields = [
			'sugerir_valor' => "`sugerir_valor`.`id` as 'id', `sugerir_valor`.`data` as 'data', `sugerir_valor`.`nome` as 'nome', `sugerir_valor`.`cpf` as 'cpf', `sugerir_valor`.`celular` as 'celular', `sugerir_valor`.`email` as 'email', `sugerir_valor`.`cidade` as 'cidade', `sugerir_valor`.`uf` as 'uf', IF(    CHAR_LENGTH(`categorias1`.`nome`), CONCAT_WS('',   `categorias1`.`nome`), '') as 'categoria', IF(    CHAR_LENGTH(`atividades1`.`atividade`) || CHAR_LENGTH(`atividades1`.`descricao`), CONCAT_WS('',   `atividades1`.`atividade`, ' - ', `atividades1`.`descricao`), '') as 'atividade', `sugerir_valor`.`quantidade` as 'quantidade', IF(    CHAR_LENGTH(`unidades1`.`unidade`), CONCAT_WS('',   `unidades1`.`unidade`), '') as 'unidade', `sugerir_valor`.`valor` as 'valor', `sugerir_valor`.`obs` as 'obs'",
			'sugerir_atividade' => "`sugerir_atividade`.`id` as 'id', `sugerir_atividade`.`data` as 'data', `sugerir_atividade`.`nome` as 'nome', `sugerir_atividade`.`cpf` as 'cpf', `sugerir_atividade`.`celular` as 'celular', `sugerir_atividade`.`email` as 'email', `sugerir_atividade`.`cidade` as 'cidade', `sugerir_atividade`.`uf` as 'uf', IF(    CHAR_LENGTH(`categorias1`.`nome`), CONCAT_WS('',   `categorias1`.`nome`), '') as 'categoria', `sugerir_atividade`.`atividade` as 'atividade', `sugerir_atividade`.`quantidade` as 'quantidade', IF(    CHAR_LENGTH(`unidades1`.`unidade`), CONCAT_WS('',   `unidades1`.`unidade`), '') as 'unidade', FORMAT(`sugerir_atividade`.`valor`, 2) as 'valor', `sugerir_atividade`.`obs` as 'obs'",
			'c001' => "`c001`.`id` as 'id', `c001`.`cod_categoria` as 'cod_categoria', `c001`.`categoria` as 'categoria', `c001`.`atividade` as 'atividade', `c001`.`descricao` as 'descricao', `c001`.`quantidade` as 'quantidade', IF(    CHAR_LENGTH(`unidades1`.`unidade`), CONCAT_WS('',   `unidades1`.`unidade`), '') as 'unidade', `c001`.`uta` as 'uta', `c001`.`valor` as 'valor'",
			'c001_ref' => "`c001_ref`.`id` as 'id', IF(    CHAR_LENGTH(`c0011`.`id`), CONCAT_WS('',   `c0011`.`id`), '') as 'id_categoria', DATE_FORMAT(`c001_ref`.`data`, '%e/%c/%Y') as 'data', `c001_ref`.`nome` as 'nome', `c001_ref`.`cpf` as 'cpf', `c001_ref`.`celular` as 'celular', `c001_ref`.`email` as 'email', `c001_ref`.`cidade` as 'cidade', `c001_ref`.`uf` as 'uf', `c001_ref`.`regiao` as 'regiao', `c001_ref`.`quantidade` as 'quantidade', `c001_ref`.`unidade` as 'unidade', `c001_ref`.`uta` as 'uta', `c001_ref`.`valor` as 'valor', `c001_ref`.`obs` as 'obs', `c001_ref`.`situacao` as 'situacao'",
			'c001_ref_colaborar' => "`c001_ref_colaborar`.`id` as 'id', IF(    CHAR_LENGTH(`c0011`.`id`), CONCAT_WS('',   `c0011`.`id`), '') as 'id_categoria', DATE_FORMAT(`c001_ref_colaborar`.`data`, '%e/%c/%Y') as 'data', `c001_ref_colaborar`.`nome` as 'nome', `c001_ref_colaborar`.`cpf` as 'cpf', `c001_ref_colaborar`.`celular` as 'celular', `c001_ref_colaborar`.`email` as 'email', `c001_ref_colaborar`.`cidade` as 'cidade', `c001_ref_colaborar`.`uf` as 'uf', `c001_ref_colaborar`.`espaco` as 'espaco', `c001_ref_colaborar`.`colaboracao` as 'colaboracao', `c001_ref_colaborar`.`regiao` as 'regiao', `c001_ref_colaborar`.`quantidade` as 'quantidade', IF(    CHAR_LENGTH(`unidades1`.`unidade`), CONCAT_WS('',   `unidades1`.`unidade`), '') as 'unidade', `c001_ref_colaborar`.`valor` as 'valor', `c001_ref_colaborar`.`uta` as 'uta', `c001_ref_colaborar`.`obs` as 'obs', `c001_ref_colaborar`.`situacao` as 'situacao'",
			'c001_ref_inativas' => "`c001_ref_inativas`.`id` as 'id', IF(    CHAR_LENGTH(`c0011`.`id`), CONCAT_WS('',   `c0011`.`id`), '') as 'id_categoria', DATE_FORMAT(`c001_ref_inativas`.`data`, '%e/%c/%Y') as 'data', `c001_ref_inativas`.`nome` as 'nome', `c001_ref_inativas`.`cpf` as 'cpf', `c001_ref_inativas`.`celular` as 'celular', `c001_ref_inativas`.`email` as 'email', `c001_ref_inativas`.`cidade` as 'cidade', `c001_ref_inativas`.`uf` as 'uf', `c001_ref_inativas`.`regiao` as 'regiao', `c001_ref_inativas`.`quantidade` as 'quantidade', `c001_ref_inativas`.`unidade` as 'unidade', `c001_ref_inativas`.`uta` as 'uta', `c001_ref_inativas`.`valor` as 'valor', `c001_ref_inativas`.`obs` as 'obs', `c001_ref_inativas`.`situacao` as 'situacao'",
			'categorias' => "`categorias`.`id` as 'id', `categorias`.`cod` as 'cod', `categorias`.`nome` as 'nome', `categorias`.`atividade` as 'atividade', `categorias`.`descricao` as 'descricao'",
			'referencias_ativas' => "`referencias_ativas`.`id` as 'id', `referencias_ativas`.`data` as 'data', IF(    CHAR_LENGTH(`c0011`.`categoria`) || CHAR_LENGTH(`c0011`.`atividade`), CONCAT_WS('',   `c0011`.`categoria`, ' / ', `c0011`.`atividade`), '') as 'id_categoria', `referencias_ativas`.`nome` as 'nome', `referencias_ativas`.`cpf` as 'cpf', `referencias_ativas`.`celular` as 'celular', `referencias_ativas`.`email` as 'email', `referencias_ativas`.`cidade` as 'cidade', `referencias_ativas`.`uf` as 'uf', `referencias_ativas`.`regiao` as 'regiao', `referencias_ativas`.`quantidade` as 'quantidade', `referencias_ativas`.`unidade` as 'unidade', `referencias_ativas`.`uta` as 'uta', `referencias_ativas`.`valor` as 'valor', `referencias_ativas`.`obs` as 'obs', `referencias_ativas`.`situacao` as 'situacao'",
			'referencias_inativas' => "`referencias_inativas`.`id` as 'id', `referencias_inativas`.`data` as 'data', IF(    CHAR_LENGTH(`c0011`.`categoria`) || CHAR_LENGTH(`c0011`.`atividade`), CONCAT_WS('',   `c0011`.`categoria`, ' / ', `c0011`.`atividade`), '') as 'id_categoria', `referencias_inativas`.`nome` as 'nome', `referencias_inativas`.`cpf` as 'cpf', `referencias_inativas`.`celular` as 'celular', `referencias_inativas`.`email` as 'email', `referencias_inativas`.`cidade` as 'cidade', `referencias_inativas`.`uf` as 'uf', `referencias_inativas`.`regiao` as 'regiao', `referencias_inativas`.`quantidade` as 'quantidade', `referencias_inativas`.`unidade` as 'unidade', `referencias_inativas`.`uta` as 'uta', `referencias_inativas`.`valor` as 'valor', `referencias_inativas`.`obs` as 'obs', `referencias_inativas`.`situacao` as 'situacao'",
			'uta' => "`uta`.`id` as 'id', `uta`.`nome` as 'nome', `uta`.`valor` as 'valor'",
			'unidades' => "`unidades`.`id` as 'id', `unidades`.`unidade` as 'unidade', `unidades`.`obs` as 'obs'",
			'atividades' => "`atividades`.`id` as 'id', `atividades`.`categoria` as 'categoria', `atividades`.`atividade` as 'atividade', `atividades`.`descricao` as 'descricao'",
			'c002' => "`c002`.`id` as 'id', `c002`.`atividade` as 'atividade', `c002`.`descricao` as 'descricao', `c002`.`quantidade` as 'quantidade', IF(    CHAR_LENGTH(`unidades1`.`unidade`), CONCAT_WS('',   `unidades1`.`unidade`), '') as 'unidade', `c002`.`uta` as 'uta', `c002`.`valor` as 'valor'",
			'c002_ref' => "`c002_ref`.`id` as 'id', IF(    CHAR_LENGTH(`c0021`.`id`), CONCAT_WS('',   `c0021`.`id`), '') as 'id_categoria', DATE_FORMAT(`c002_ref`.`data`, '%e/%c/%Y') as 'data', `c002_ref`.`nome` as 'nome', `c002_ref`.`cpf` as 'cpf', `c002_ref`.`celular` as 'celular', `c002_ref`.`email` as 'email', `c002_ref`.`cidade` as 'cidade', `c002_ref`.`uf` as 'uf', `c002_ref`.`regiao` as 'regiao', `c002_ref`.`quantidade` as 'quantidade', `c002_ref`.`unidade` as 'unidade', `c002_ref`.`uta` as 'uta', `c002_ref`.`valor` as 'valor', `c002_ref`.`obs` as 'obs', `c002_ref`.`situacao` as 'situacao'",
			'c002_ref_colaborar' => "`c002_ref_colaborar`.`id` as 'id', IF(    CHAR_LENGTH(`c0021`.`id`), CONCAT_WS('',   `c0021`.`id`), '') as 'id_categoria', DATE_FORMAT(`c002_ref_colaborar`.`data`, '%e/%c/%Y') as 'data', `c002_ref_colaborar`.`nome` as 'nome', `c002_ref_colaborar`.`cpf` as 'cpf', `c002_ref_colaborar`.`celular` as 'celular', `c002_ref_colaborar`.`email` as 'email', `c002_ref_colaborar`.`cidade` as 'cidade', `c002_ref_colaborar`.`uf` as 'uf', `c002_ref_colaborar`.`espaco` as 'espaco', `c002_ref_colaborar`.`colaboracao` as 'colaboracao', `c002_ref_colaborar`.`regiao` as 'regiao', `c002_ref_colaborar`.`quantidade` as 'quantidade', IF(    CHAR_LENGTH(`unidades1`.`unidade`), CONCAT_WS('',   `unidades1`.`unidade`), '') as 'unidade', `c002_ref_colaborar`.`valor` as 'valor', `c002_ref_colaborar`.`uta` as 'uta', `c002_ref_colaborar`.`obs` as 'obs', `c002_ref_colaborar`.`situacao` as 'situacao'",
			'c002_ref_inativas' => "`c002_ref_inativas`.`id` as 'id', IF(    CHAR_LENGTH(`c0021`.`id`), CONCAT_WS('',   `c0021`.`id`), '') as 'id_categoria', DATE_FORMAT(`c002_ref_inativas`.`data`, '%e/%c/%Y') as 'data', `c002_ref_inativas`.`nome` as 'nome', `c002_ref_inativas`.`cpf` as 'cpf', `c002_ref_inativas`.`celular` as 'celular', `c002_ref_inativas`.`email` as 'email', `c002_ref_inativas`.`cidade` as 'cidade', `c002_ref_inativas`.`uf` as 'uf', `c002_ref_inativas`.`regiao` as 'regiao', `c002_ref_inativas`.`quantidade` as 'quantidade', `c002_ref_inativas`.`unidade` as 'unidade', `c002_ref_inativas`.`uta` as 'uta', `c002_ref_inativas`.`valor` as 'valor', `c002_ref_inativas`.`obs` as 'obs', `c002_ref_inativas`.`situacao` as 'situacao'",
			'colaborar_atividade' => "`colaborar_atividade`.`id` as 'id', IF(    CHAR_LENGTH(`c0021`.`id`), CONCAT_WS('',   `c0021`.`id`), '') as 'id_categoria', DATE_FORMAT(`colaborar_atividade`.`data`, '%e/%c/%Y') as 'data', `colaborar_atividade`.`nome` as 'nome', `colaborar_atividade`.`cpf` as 'cpf', `colaborar_atividade`.`celular` as 'celular', `colaborar_atividade`.`email` as 'email', `colaborar_atividade`.`cidade` as 'cidade', `colaborar_atividade`.`uf` as 'uf', `colaborar_atividade`.`espaco` as 'espaco', IF(    CHAR_LENGTH(`categorias1`.`nome`), CONCAT_WS('',   `categorias1`.`nome`), '') as 'colaboracao', IF(    CHAR_LENGTH(`categorias2`.`nome`), CONCAT_WS('',   `categorias2`.`nome`), '') as 'categoria', `colaborar_atividade`.`atividade` as 'atividade', `colaborar_atividade`.`regiao` as 'regiao', `colaborar_atividade`.`quantidade` as 'quantidade', IF(    CHAR_LENGTH(`unidades1`.`unidade`), CONCAT_WS('',   `unidades1`.`unidade`), '') as 'unidade', `colaborar_atividade`.`valor` as 'valor', `colaborar_atividade`.`uta` as 'uta', `colaborar_atividade`.`obs` as 'obs', `colaborar_atividade`.`situacao` as 'situacao'",
			'informacoes' => "`informacoes`.`id` as 'id', `informacoes`.`assunto` as 'assunto', `informacoes`.`nome` as 'nome'",
			'c003' => "`c003`.`id` as 'id', `c003`.`atividade` as 'atividade', `c003`.`descricao` as 'descricao', `c003`.`quantidade` as 'quantidade', IF(    CHAR_LENGTH(`unidades1`.`unidade`), CONCAT_WS('',   `unidades1`.`unidade`), '') as 'unidade', `c003`.`uta` as 'uta', `c003`.`valor` as 'valor'",
			'c003_ref' => "`c003_ref`.`id` as 'id', IF(    CHAR_LENGTH(`c0031`.`id`), CONCAT_WS('',   `c0031`.`id`), '') as 'id_categoria', DATE_FORMAT(`c003_ref`.`data`, '%e/%c/%Y') as 'data', `c003_ref`.`nome` as 'nome', `c003_ref`.`cpf` as 'cpf', `c003_ref`.`celular` as 'celular', `c003_ref`.`email` as 'email', `c003_ref`.`cidade` as 'cidade', `c003_ref`.`uf` as 'uf', `c003_ref`.`regiao` as 'regiao', `c003_ref`.`quantidade` as 'quantidade', `c003_ref`.`unidade` as 'unidade', `c003_ref`.`uta` as 'uta', `c003_ref`.`valor` as 'valor', `c003_ref`.`obs` as 'obs', `c003_ref`.`situacao` as 'situacao'",
			'c003_ref_colaborar' => "`c003_ref_colaborar`.`id` as 'id', IF(    CHAR_LENGTH(`c0031`.`id`), CONCAT_WS('',   `c0031`.`id`), '') as 'id_categoria', DATE_FORMAT(`c003_ref_colaborar`.`data`, '%e/%c/%Y') as 'data', `c003_ref_colaborar`.`nome` as 'nome', `c003_ref_colaborar`.`cpf` as 'cpf', `c003_ref_colaborar`.`celular` as 'celular', `c003_ref_colaborar`.`email` as 'email', `c003_ref_colaborar`.`cidade` as 'cidade', `c003_ref_colaborar`.`uf` as 'uf', `c003_ref_colaborar`.`espaco` as 'espaco', `c003_ref_colaborar`.`colaboracao` as 'colaboracao', `c003_ref_colaborar`.`regiao` as 'regiao', `c003_ref_colaborar`.`quantidade` as 'quantidade', IF(    CHAR_LENGTH(`unidades1`.`unidade`), CONCAT_WS('',   `unidades1`.`unidade`), '') as 'unidade', `c003_ref_colaborar`.`valor` as 'valor', `c003_ref_colaborar`.`uta` as 'uta', `c003_ref_colaborar`.`obs` as 'obs', `c003_ref_colaborar`.`situacao` as 'situacao'",
			'c003_ref_inativas' => "`c003_ref_inativas`.`id` as 'id', IF(    CHAR_LENGTH(`c0031`.`id`), CONCAT_WS('',   `c0031`.`id`), '') as 'id_categoria', DATE_FORMAT(`c003_ref_inativas`.`data`, '%e/%c/%Y') as 'data', `c003_ref_inativas`.`nome` as 'nome', `c003_ref_inativas`.`cpf` as 'cpf', `c003_ref_inativas`.`celular` as 'celular', `c003_ref_inativas`.`email` as 'email', `c003_ref_inativas`.`cidade` as 'cidade', `c003_ref_inativas`.`uf` as 'uf', `c003_ref_inativas`.`regiao` as 'regiao', `c003_ref_inativas`.`quantidade` as 'quantidade', `c003_ref_inativas`.`unidade` as 'unidade', `c003_ref_inativas`.`uta` as 'uta', `c003_ref_inativas`.`valor` as 'valor', `c003_ref_inativas`.`obs` as 'obs', `c003_ref_inativas`.`situacao` as 'situacao'",
			'c004' => "`c004`.`id` as 'id', `c004`.`atividade` as 'atividade', `c004`.`descricao` as 'descricao', `c004`.`quantidade` as 'quantidade', IF(    CHAR_LENGTH(`unidades1`.`unidade`), CONCAT_WS('',   `unidades1`.`unidade`), '') as 'unidade', `c004`.`uta` as 'uta', `c004`.`valor` as 'valor'",
			'c004_ref' => "`c004_ref`.`id` as 'id', IF(    CHAR_LENGTH(`c0041`.`id`), CONCAT_WS('',   `c0041`.`id`), '') as 'id_categoria', DATE_FORMAT(`c004_ref`.`data`, '%e/%c/%Y') as 'data', `c004_ref`.`nome` as 'nome', `c004_ref`.`cpf` as 'cpf', `c004_ref`.`celular` as 'celular', `c004_ref`.`email` as 'email', `c004_ref`.`cidade` as 'cidade', `c004_ref`.`uf` as 'uf', `c004_ref`.`regiao` as 'regiao', `c004_ref`.`quantidade` as 'quantidade', `c004_ref`.`unidade` as 'unidade', `c004_ref`.`uta` as 'uta', `c004_ref`.`valor` as 'valor', `c004_ref`.`obs` as 'obs', `c004_ref`.`situacao` as 'situacao'",
			'c004_ref_colaborar' => "`c004_ref_colaborar`.`id` as 'id', IF(    CHAR_LENGTH(`c0041`.`id`), CONCAT_WS('',   `c0041`.`id`), '') as 'id_categoria', DATE_FORMAT(`c004_ref_colaborar`.`data`, '%e/%c/%Y') as 'data', `c004_ref_colaborar`.`nome` as 'nome', `c004_ref_colaborar`.`cpf` as 'cpf', `c004_ref_colaborar`.`celular` as 'celular', `c004_ref_colaborar`.`email` as 'email', `c004_ref_colaborar`.`cidade` as 'cidade', `c004_ref_colaborar`.`uf` as 'uf', `c004_ref_colaborar`.`espaco` as 'espaco', `c004_ref_colaborar`.`colaboracao` as 'colaboracao', `c004_ref_colaborar`.`regiao` as 'regiao', `c004_ref_colaborar`.`quantidade` as 'quantidade', IF(    CHAR_LENGTH(`unidades1`.`unidade`), CONCAT_WS('',   `unidades1`.`unidade`), '') as 'unidade', `c004_ref_colaborar`.`valor` as 'valor', `c004_ref_colaborar`.`uta` as 'uta', `c004_ref_colaborar`.`obs` as 'obs', `c004_ref_colaborar`.`situacao` as 'situacao'",
			'c004_ref_inativas' => "`c004_ref_inativas`.`id` as 'id', IF(    CHAR_LENGTH(`c0041`.`id`), CONCAT_WS('',   `c0041`.`id`), '') as 'id_categoria', DATE_FORMAT(`c004_ref_inativas`.`data`, '%e/%c/%Y') as 'data', `c004_ref_inativas`.`nome` as 'nome', `c004_ref_inativas`.`cpf` as 'cpf', `c004_ref_inativas`.`celular` as 'celular', `c004_ref_inativas`.`email` as 'email', `c004_ref_inativas`.`cidade` as 'cidade', `c004_ref_inativas`.`uf` as 'uf', `c004_ref_inativas`.`regiao` as 'regiao', `c004_ref_inativas`.`quantidade` as 'quantidade', `c004_ref_inativas`.`unidade` as 'unidade', `c004_ref_inativas`.`uta` as 'uta', `c004_ref_inativas`.`valor` as 'valor', `c004_ref_inativas`.`obs` as 'obs', `c004_ref_inativas`.`situacao` as 'situacao'",
		];

		if(isset($sql_fields[$table_name])) return $sql_fields[$table_name];

		return false;
	}

	#########################################################

	function get_sql_from($table_name, $skip_permissions = false, $skip_joins = false, $lower_permissions = false) {
		$sql_from = [
			'sugerir_valor' => "`sugerir_valor` LEFT JOIN `categorias` as categorias1 ON `categorias1`.`id`=`sugerir_valor`.`categoria` LEFT JOIN `atividades` as atividades1 ON `atividades1`.`id`=`sugerir_valor`.`atividade` LEFT JOIN `unidades` as unidades1 ON `unidades1`.`id`=`sugerir_valor`.`unidade` ",
			'sugerir_atividade' => "`sugerir_atividade` LEFT JOIN `categorias` as categorias1 ON `categorias1`.`id`=`sugerir_atividade`.`categoria` LEFT JOIN `unidades` as unidades1 ON `unidades1`.`id`=`sugerir_atividade`.`unidade` ",
			'c001' => "`c001` LEFT JOIN `unidades` as unidades1 ON `unidades1`.`id`=`c001`.`unidade` ",
			'c001_ref' => "`c001_ref` LEFT JOIN `c001` as c0011 ON `c0011`.`id`=`c001_ref`.`id_categoria` ",
			'c001_ref_colaborar' => "`c001_ref_colaborar` LEFT JOIN `c001` as c0011 ON `c0011`.`id`=`c001_ref_colaborar`.`id_categoria` LEFT JOIN `unidades` as unidades1 ON `unidades1`.`id`=`c001_ref_colaborar`.`unidade` ",
			'c001_ref_inativas' => "`c001_ref_inativas` LEFT JOIN `c001` as c0011 ON `c0011`.`id`=`c001_ref_inativas`.`id_categoria` ",
			'categorias' => "`categorias` ",
			'referencias_ativas' => "`referencias_ativas` LEFT JOIN `c001` as c0011 ON `c0011`.`id`=`referencias_ativas`.`id_categoria` ",
			'referencias_inativas' => "`referencias_inativas` LEFT JOIN `c001` as c0011 ON `c0011`.`id`=`referencias_inativas`.`id_categoria` ",
			'uta' => "`uta` ",
			'unidades' => "`unidades` ",
			'atividades' => "`atividades` ",
			'c002' => "`c002` LEFT JOIN `unidades` as unidades1 ON `unidades1`.`id`=`c002`.`unidade` ",
			'c002_ref' => "`c002_ref` LEFT JOIN `c002` as c0021 ON `c0021`.`id`=`c002_ref`.`id_categoria` ",
			'c002_ref_colaborar' => "`c002_ref_colaborar` LEFT JOIN `c002` as c0021 ON `c0021`.`id`=`c002_ref_colaborar`.`id_categoria` LEFT JOIN `unidades` as unidades1 ON `unidades1`.`id`=`c002_ref_colaborar`.`unidade` ",
			'c002_ref_inativas' => "`c002_ref_inativas` LEFT JOIN `c002` as c0021 ON `c0021`.`id`=`c002_ref_inativas`.`id_categoria` ",
			'colaborar_atividade' => "`colaborar_atividade` LEFT JOIN `c002` as c0021 ON `c0021`.`id`=`colaborar_atividade`.`id_categoria` LEFT JOIN `categorias` as categorias1 ON `categorias1`.`id`=`colaborar_atividade`.`colaboracao` LEFT JOIN `categorias` as categorias2 ON `categorias2`.`id`=`colaborar_atividade`.`categoria` LEFT JOIN `unidades` as unidades1 ON `unidades1`.`id`=`colaborar_atividade`.`unidade` ",
			'informacoes' => "`informacoes` ",
			'c003' => "`c003` LEFT JOIN `unidades` as unidades1 ON `unidades1`.`id`=`c003`.`unidade` ",
			'c003_ref' => "`c003_ref` LEFT JOIN `c003` as c0031 ON `c0031`.`id`=`c003_ref`.`id_categoria` ",
			'c003_ref_colaborar' => "`c003_ref_colaborar` LEFT JOIN `c003` as c0031 ON `c0031`.`id`=`c003_ref_colaborar`.`id_categoria` LEFT JOIN `unidades` as unidades1 ON `unidades1`.`id`=`c003_ref_colaborar`.`unidade` ",
			'c003_ref_inativas' => "`c003_ref_inativas` LEFT JOIN `c003` as c0031 ON `c0031`.`id`=`c003_ref_inativas`.`id_categoria` ",
			'c004' => "`c004` LEFT JOIN `unidades` as unidades1 ON `unidades1`.`id`=`c004`.`unidade` ",
			'c004_ref' => "`c004_ref` LEFT JOIN `c004` as c0041 ON `c0041`.`id`=`c004_ref`.`id_categoria` ",
			'c004_ref_colaborar' => "`c004_ref_colaborar` LEFT JOIN `c004` as c0041 ON `c0041`.`id`=`c004_ref_colaborar`.`id_categoria` LEFT JOIN `unidades` as unidades1 ON `unidades1`.`id`=`c004_ref_colaborar`.`unidade` ",
			'c004_ref_inativas' => "`c004_ref_inativas` LEFT JOIN `c004` as c0041 ON `c0041`.`id`=`c004_ref_inativas`.`id_categoria` ",
		];

		$pkey = [
			'sugerir_valor' => 'id',
			'sugerir_atividade' => 'id',
			'c001' => 'id',
			'c001_ref' => 'id',
			'c001_ref_colaborar' => 'id',
			'c001_ref_inativas' => 'id',
			'categorias' => 'id',
			'referencias_ativas' => 'id',
			'referencias_inativas' => 'id',
			'uta' => 'id',
			'unidades' => 'id',
			'atividades' => 'id',
			'c002' => 'id',
			'c002_ref' => 'id',
			'c002_ref_colaborar' => 'id',
			'c002_ref_inativas' => 'id',
			'colaborar_atividade' => 'id',
			'informacoes' => 'id',
			'c003' => 'id',
			'c003_ref' => 'id',
			'c003_ref_colaborar' => 'id',
			'c003_ref_inativas' => 'id',
			'c004' => 'id',
			'c004_ref' => 'id',
			'c004_ref_colaborar' => 'id',
			'c004_ref_inativas' => 'id',
		];

		if(!isset($sql_from[$table_name])) return false;

		$from = ($skip_joins ? "`{$table_name}`" : $sql_from[$table_name]);

		if($skip_permissions) return $from . ' WHERE 1=1';

		// mm: build the query based on current member's permissions
		// allowing lower permissions if $lower_permissions set to 'user' or 'group'
		$perm = getTablePermissions($table_name);
		if($perm['view'] == 1 || ($perm['view'] > 1 && $lower_permissions == 'user')) { // view owner only
			$from .= ", `membership_userrecords` WHERE `{$table_name}`.`{$pkey[$table_name]}`=`membership_userrecords`.`pkValue` AND `membership_userrecords`.`tableName`='{$table_name}' AND LCASE(`membership_userrecords`.`memberID`)='" . getLoggedMemberID() . "'";
		} elseif($perm['view'] == 2 || ($perm['view'] > 2 && $lower_permissions == 'group')) { // view group only
			$from .= ", `membership_userrecords` WHERE `{$table_name}`.`{$pkey[$table_name]}`=`membership_userrecords`.`pkValue` AND `membership_userrecords`.`tableName`='{$table_name}' AND `membership_userrecords`.`groupID`='" . getLoggedGroupID() . "'";
		} elseif($perm['view'] == 3) { // view all
			$from .= ' WHERE 1=1';
		} else { // view none
			return false;
		}

		return $from;
	}

	#########################################################

	function get_joined_record($table, $id, $skip_permissions = false) {
		$sql_fields = get_sql_fields($table);
		$sql_from = get_sql_from($table, $skip_permissions);

		if(!$sql_fields || !$sql_from) return false;

		$pk = getPKFieldName($table);
		if(!$pk) return false;

		$safe_id = makeSafe($id, false);
		$sql = "SELECT {$sql_fields} FROM {$sql_from} AND `{$table}`.`{$pk}`='{$safe_id}'";
		$eo['silentErrors'] = true;
		$res = sql($sql, $eo);
		if($row = db_fetch_assoc($res)) return $row;

		return false;
	}

	#########################################################

	function get_defaults($table) {
		/* array of tables and their fields, with default values (or empty), excluding automatic values */
		$defaults = [
			'sugerir_valor' => [
				'id' => '',
				'data' => '',
				'nome' => '',
				'cpf' => '',
				'celular' => '',
				'email' => '',
				'cidade' => '',
				'uf' => '',
				'categoria' => '',
				'atividade' => '',
				'quantidade' => '',
				'unidade' => '',
				'valor' => '',
				'obs' => '',
			],
			'sugerir_atividade' => [
				'id' => '',
				'data' => '',
				'nome' => '',
				'cpf' => '',
				'celular' => '',
				'email' => '',
				'cidade' => '',
				'uf' => '',
				'categoria' => '',
				'atividade' => '',
				'quantidade' => '',
				'unidade' => '',
				'valor' => '',
				'obs' => '',
			],
			'c001' => [
				'id' => '',
				'cod_categoria' => '',
				'categoria' => '',
				'atividade' => '',
				'descricao' => '',
				'quantidade' => '',
				'unidade' => '',
				'uta' => '',
				'valor' => '',
			],
			'c001_ref' => [
				'id' => '',
				'id_categoria' => '',
				'data' => '',
				'nome' => '',
				'cpf' => '',
				'celular' => '',
				'email' => '',
				'cidade' => '',
				'uf' => '',
				'regiao' => '',
				'quantidade' => '',
				'unidade' => '',
				'uta' => '',
				'valor' => '',
				'obs' => '',
				'situacao' => 'INATIVA',
			],
			'c001_ref_colaborar' => [
				'id' => '',
				'id_categoria' => '',
				'data' => '',
				'nome' => '',
				'cpf' => '',
				'celular' => '',
				'email' => '',
				'cidade' => '',
				'uf' => '',
				'espaco' => '',
				'colaboracao' => '',
				'regiao' => '',
				'quantidade' => '',
				'unidade' => '',
				'valor' => '',
				'uta' => '',
				'obs' => '',
				'situacao' => 'INATIVA',
			],
			'c001_ref_inativas' => [
				'id' => '',
				'id_categoria' => '',
				'data' => '',
				'nome' => '',
				'cpf' => '',
				'celular' => '',
				'email' => '',
				'cidade' => '',
				'uf' => '',
				'regiao' => '',
				'quantidade' => '',
				'unidade' => '',
				'uta' => '',
				'valor' => '',
				'obs' => '',
				'situacao' => '',
			],
			'categorias' => [
				'id' => '',
				'cod' => '',
				'nome' => '',
				'atividade' => '',
				'descricao' => '',
			],
			'referencias_ativas' => [
				'id' => '',
				'data' => '',
				'id_categoria' => '',
				'nome' => '',
				'cpf' => '',
				'celular' => '',
				'email' => '',
				'cidade' => '',
				'uf' => '',
				'regiao' => '',
				'quantidade' => '',
				'unidade' => '',
				'uta' => '',
				'valor' => '',
				'obs' => '',
				'situacao' => '',
			],
			'referencias_inativas' => [
				'id' => '',
				'data' => '',
				'id_categoria' => '',
				'nome' => '',
				'cpf' => '',
				'celular' => '',
				'email' => '',
				'cidade' => '',
				'uf' => '',
				'regiao' => '',
				'quantidade' => '',
				'unidade' => '',
				'uta' => '',
				'valor' => '',
				'obs' => '',
				'situacao' => '',
			],
			'uta' => [
				'id' => '',
				'nome' => '',
				'valor' => '',
			],
			'unidades' => [
				'id' => '',
				'unidade' => '',
				'obs' => '',
			],
			'atividades' => [
				'id' => '',
				'categoria' => '',
				'atividade' => '',
				'descricao' => '',
			],
			'c002' => [
				'id' => '',
				'atividade' => '',
				'descricao' => '',
				'quantidade' => '',
				'unidade' => '',
				'uta' => '',
				'valor' => '',
			],
			'c002_ref' => [
				'id' => '',
				'id_categoria' => '',
				'data' => '',
				'nome' => '',
				'cpf' => '',
				'celular' => '',
				'email' => '',
				'cidade' => '',
				'uf' => '',
				'regiao' => '',
				'quantidade' => '',
				'unidade' => '',
				'uta' => '',
				'valor' => '',
				'obs' => '',
				'situacao' => 'INATIVA',
			],
			'c002_ref_colaborar' => [
				'id' => '',
				'id_categoria' => '',
				'data' => '',
				'nome' => '',
				'cpf' => '',
				'celular' => '',
				'email' => '',
				'cidade' => '',
				'uf' => '',
				'espaco' => '',
				'colaboracao' => '',
				'regiao' => '',
				'quantidade' => '',
				'unidade' => '',
				'valor' => '',
				'uta' => '',
				'obs' => '',
				'situacao' => 'INATIVA',
			],
			'c002_ref_inativas' => [
				'id' => '',
				'id_categoria' => '',
				'data' => '',
				'nome' => '',
				'cpf' => '',
				'celular' => '',
				'email' => '',
				'cidade' => '',
				'uf' => '',
				'regiao' => '',
				'quantidade' => '',
				'unidade' => '',
				'uta' => '',
				'valor' => '',
				'obs' => '',
				'situacao' => '',
			],
			'colaborar_atividade' => [
				'id' => '',
				'id_categoria' => '',
				'data' => '',
				'nome' => '',
				'cpf' => '',
				'celular' => '',
				'email' => '',
				'cidade' => '',
				'uf' => '',
				'espaco' => '',
				'colaboracao' => '',
				'categoria' => '',
				'atividade' => '',
				'regiao' => '',
				'quantidade' => '',
				'unidade' => '',
				'valor' => '',
				'uta' => '',
				'obs' => '',
				'situacao' => 'INATIVA',
			],
			'informacoes' => [
				'id' => '',
				'assunto' => '',
				'nome' => '',
			],
			'c003' => [
				'id' => '',
				'atividade' => '',
				'descricao' => '',
				'quantidade' => '',
				'unidade' => '',
				'uta' => '',
				'valor' => '',
			],
			'c003_ref' => [
				'id' => '',
				'id_categoria' => '',
				'data' => '',
				'nome' => '',
				'cpf' => '',
				'celular' => '',
				'email' => '',
				'cidade' => '',
				'uf' => '',
				'regiao' => '',
				'quantidade' => '',
				'unidade' => '',
				'uta' => '',
				'valor' => '',
				'obs' => '',
				'situacao' => 'INATIVA',
			],
			'c003_ref_colaborar' => [
				'id' => '',
				'id_categoria' => '',
				'data' => '',
				'nome' => '',
				'cpf' => '',
				'celular' => '',
				'email' => '',
				'cidade' => '',
				'uf' => '',
				'espaco' => '',
				'colaboracao' => '',
				'regiao' => '',
				'quantidade' => '',
				'unidade' => '',
				'valor' => '',
				'uta' => '',
				'obs' => '',
				'situacao' => 'INATIVA',
			],
			'c003_ref_inativas' => [
				'id' => '',
				'id_categoria' => '',
				'data' => '',
				'nome' => '',
				'cpf' => '',
				'celular' => '',
				'email' => '',
				'cidade' => '',
				'uf' => '',
				'regiao' => '',
				'quantidade' => '',
				'unidade' => '',
				'uta' => '',
				'valor' => '',
				'obs' => '',
				'situacao' => '',
			],
			'c004' => [
				'id' => '',
				'atividade' => '',
				'descricao' => '',
				'quantidade' => '',
				'unidade' => '',
				'uta' => '',
				'valor' => '',
			],
			'c004_ref' => [
				'id' => '',
				'id_categoria' => '',
				'data' => '',
				'nome' => '',
				'cpf' => '',
				'celular' => '',
				'email' => '',
				'cidade' => '',
				'uf' => '',
				'regiao' => '',
				'quantidade' => '',
				'unidade' => '',
				'uta' => '',
				'valor' => '',
				'obs' => '',
				'situacao' => 'INATIVA',
			],
			'c004_ref_colaborar' => [
				'id' => '',
				'id_categoria' => '',
				'data' => '',
				'nome' => '',
				'cpf' => '',
				'celular' => '',
				'email' => '',
				'cidade' => '',
				'uf' => '',
				'espaco' => '',
				'colaboracao' => '',
				'regiao' => '',
				'quantidade' => '',
				'unidade' => '',
				'valor' => '',
				'uta' => '',
				'obs' => '',
				'situacao' => 'INATIVA',
			],
			'c004_ref_inativas' => [
				'id' => '',
				'id_categoria' => '',
				'data' => '',
				'nome' => '',
				'cpf' => '',
				'celular' => '',
				'email' => '',
				'cidade' => '',
				'uf' => '',
				'regiao' => '',
				'quantidade' => '',
				'unidade' => '',
				'uta' => '',
				'valor' => '',
				'obs' => '',
				'situacao' => '',
			],
		];

		return isset($defaults[$table]) ? $defaults[$table] : [];
	}

	#########################################################

	function logInMember() {
		$redir = 'index.php';
		if($_POST['signIn'] != '') {
			if($_POST['username'] != '' && $_POST['password'] != '') {
				$username = makeSafe(strtolower($_POST['username']));
				$hash = sqlValue("select passMD5 from membership_users where lcase(memberID)='{$username}' and isApproved=1 and isBanned=0");
				$password = $_POST['password'];

				if(password_match($password, $hash)) {
					$_SESSION['memberID'] = $username;
					$_SESSION['memberGroupID'] = sqlValue("SELECT `groupID` FROM `membership_users` WHERE LCASE(`memberID`)='{$username}'");

					if($_POST['rememberMe'] == 1) {
						RememberMe::login($username);
					} else {
						RememberMe::delete();
					}

					// harden user's password hash
					password_harden($username, $password, $hash);

					// hook: login_ok
					if(function_exists('login_ok')) {
						$args = [];
						if(!$redir = login_ok(getMemberInfo(), $args)) {
							$redir = 'index.php';
						}
					}

					redirect($redir);
					exit;
				}
			}

			// hook: login_failed
			if(function_exists('login_failed')) {
				$args = [];
				login_failed([
					'username' => $_POST['username'],
					'password' => $_POST['password'],
					'IP' => $_SERVER['REMOTE_ADDR']
				], $args);
			}

			if(!headers_sent()) header('HTTP/1.0 403 Forbidden');
			redirect("index.php?loginFailed=1");
			exit;
		}

		/* do we have a JWT auth header? */
		jwt_check_login();

		if(!empty($_SESSION['memberID']) && !empty($_SESSION['memberGroupID'])) return;

		/* check if a rememberMe cookie exists and sign in user if so */
		if(RememberMe::check()) {
			$username = makeSafe(strtolower(RememberMe::user()));
			$_SESSION['memberID'] = $username;
			$_SESSION['memberGroupID'] = sqlValue("SELECT `groupID` FROM `membership_users` WHERE LCASE(`memberID`)='{$username}'");
		}
	}

	#########################################################

	function htmlUserBar() {
		global $Translation;
		if(!defined('PREPEND_PATH')) define('PREPEND_PATH', '');

		$mi = getMemberInfo();
		$adminConfig = config('adminConfig');
		$home_page = (basename($_SERVER['PHP_SELF']) == 'index.php');
		ob_start();

		?>
		<nav class="navbar navbar-default navbar-fixed-top hidden-print" role="navigation">
			<div class="navbar-header">
				<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
					<span class="sr-only">Toggle navigation</span>
					<span class="icon-bar"></span>
					<span class="icon-bar"></span>
					<span class="icon-bar"></span>
				</button>
				<!-- application title is obtained from the name besides the yellow database icon in AppGini, use underscores for spaces -->
				<a class="navbar-brand" href="<?php echo PREPEND_PATH; ?>index.php"><i class="glyphicon glyphicon-home"></i> CFTA</a>
			</div>
			<div class="collapse navbar-collapse">
				<ul class="nav navbar-nav"><?php echo ($home_page ? '' : NavMenus()); ?></ul>

				<?php if(userCanImport()){ ?>
					<ul class="nav navbar-nav">
						<a href="<?php echo PREPEND_PATH; ?>import-csv.php" class="btn btn-default navbar-btn hidden-xs btn-import-csv" title="<?php echo html_attr($Translation['import csv file']); ?>"><i class="glyphicon glyphicon-th"></i> <?php echo $Translation['import CSV']; ?></a>
						<a href="<?php echo PREPEND_PATH; ?>import-csv.php" class="btn btn-default navbar-btn visible-xs btn-lg btn-import-csv" title="<?php echo html_attr($Translation['import csv file']); ?>"><i class="glyphicon glyphicon-th"></i> <?php echo $Translation['import CSV']; ?></a>
					</ul>
				<?php } ?>

				<?php if(getLoggedAdmin() !== false) { ?>
					<ul class="nav navbar-nav">
						<a href="<?php echo PREPEND_PATH; ?>admin/pageHome.php" class="btn btn-danger navbar-btn hidden-xs" title="<?php echo html_attr($Translation['admin area']); ?>"><i class="glyphicon glyphicon-cog"></i> <?php echo $Translation['admin area']; ?></a>
						<a href="<?php echo PREPEND_PATH; ?>admin/pageHome.php" class="btn btn-danger navbar-btn visible-xs btn-lg" title="<?php echo html_attr($Translation['admin area']); ?>"><i class="glyphicon glyphicon-cog"></i> <?php echo $Translation['admin area']; ?></a>
					</ul>
				<?php } ?>

				<?php if(!$_GET['signIn'] && !$_GET['loginFailed']) { ?>
					<?php if(!$mi['username'] || $mi['username'] == $adminConfig['anonymousMember']) { ?>
						<p class="navbar-text navbar-right">&nbsp;</p>
						<a href="<?php echo PREPEND_PATH; ?>index.php?signIn=1" class="btn btn-success navbar-btn navbar-right"><?php echo $Translation['sign in']; ?></a>
						<p class="navbar-text navbar-right">
							<?php echo $Translation['not signed in']; ?>
						</p>
					<?php } else { ?>
						<ul class="nav navbar-nav navbar-right hidden-xs" style="min-width: 330px;">
							<a class="btn navbar-btn btn-default" href="<?php echo PREPEND_PATH; ?>index.php?signOut=1"><i class="glyphicon glyphicon-log-out"></i> <?php echo $Translation['sign out']; ?></a>

							<p class="navbar-text signed-in-as">
								<?php echo $Translation['signed as']; ?> <strong><a href="<?php echo PREPEND_PATH; ?>membership_profile.php" class="navbar-link username"><?php echo $mi['username']; ?></a></strong>
							</p>
						</ul>
						<ul class="nav navbar-nav visible-xs">
							<a class="btn navbar-btn btn-default btn-lg visible-xs" href="<?php echo PREPEND_PATH; ?>index.php?signOut=1"><i class="glyphicon glyphicon-log-out"></i> <?php echo $Translation['sign out']; ?></a>
							<p class="navbar-text text-center signed-in-as">
								<?php echo $Translation['signed as']; ?> <strong><a href="<?php echo PREPEND_PATH; ?>membership_profile.php" class="navbar-link username"><?php echo $mi['username']; ?></a></strong>
							</p>
						</ul>
						<script>
							/* periodically check if user is still signed in */
							setInterval(function() {
								$j.ajax({
									url: '<?php echo PREPEND_PATH; ?>ajax_check_login.php',
									success: function(username) {
										if(!username.length) window.location = '<?php echo PREPEND_PATH; ?>index.php?signIn=1';
									}
								});
							}, 60000);
						</script>
					<?php } ?>
				<?php } ?>

				<p class="navbar-text navbar-right help-shortcuts-launcher-container hidden-xs">
					<img
						class="help-shortcuts-launcher" 
						src="<?php echo PREPEND_PATH; ?>resources/images/keyboard.png" 
						title="<?php echo html_attr($Translation['keyboard shortcuts']); ?>">
				</p>
			</div>
		</nav>
		<?php

		$html = ob_get_contents();
		ob_end_clean();

		return $html;
	}

	#########################################################

	function showNotifications($msg = '', $class = '', $fadeout = true) {
		global $Translation;
		if($error_message = strip_tags($_REQUEST['error_message']))
			$error_message = '<div class="text-bold">' . $error_message . '</div>';

		if(!$msg) { // if no msg, use url to detect message to display
			if($_REQUEST['record-added-ok'] != '') {
				$msg = $Translation['new record saved'];
				$class = 'alert-success';
			} elseif($_REQUEST['record-added-error'] != '') {
				$msg = $Translation['Couldn\'t save the new record'] . $error_message;
				$class = 'alert-danger';
				$fadeout = false;
			} elseif($_REQUEST['record-updated-ok'] != '') {
				$msg = $Translation['record updated'];
				$class = 'alert-success';
			} elseif($_REQUEST['record-updated-error'] != '') {
				$msg = $Translation['Couldn\'t save changes to the record'] . $error_message;
				$class = 'alert-danger';
				$fadeout = false;
			} elseif($_REQUEST['record-deleted-ok'] != '') {
				$msg = $Translation['The record has been deleted successfully'];
				$class = 'alert-success';
			} elseif($_REQUEST['record-deleted-error'] != '') {
				$msg = $Translation['Couldn\'t delete this record'] . $error_message;
				$class = 'alert-danger';
				$fadeout = false;
			} else {
				return '';
			}
		}
		$id = 'notification-' . rand();

		ob_start();
		// notification template
		?>
		<div id="%%ID%%" class="alert alert-dismissable %%CLASS%%" style="opacity: 1; padding-top: 6px; padding-bottom: 6px; animation: fadeIn 1.5s ease-out;">
			<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
			%%MSG%%
		</div>
		<script>
			$j(function() {
				var autoDismiss = <?php echo $fadeout ? 'true' : 'false'; ?>,
					embedded = !$j('nav').length,
					messageDelay = 10, fadeDelay = 1.5;

				if(!autoDismiss) {
					if(embedded)
						$j('#%%ID%%').before('<div style="height: 2rem;"></div>');
					else
						$j('#%%ID%%').css({ margin: '0 0 1rem' });

					return;
				}

				// below code runs only in case of autoDismiss

				if(embedded)
					$j('#%%ID%%').css({ margin: '1rem 0 -1rem' });
				else
					$j('#%%ID%%').css({ margin: '-15px 0 -20px' });

				setTimeout(function() {
					$j('#%%ID%%').css({    animation: 'fadeOut ' + fadeDelay + 's ease-out' });
				}, messageDelay * 1000);

				setTimeout(function() {
					$j('#%%ID%%').css({    visibility: 'hidden' });
				}, (messageDelay + fadeDelay) * 1000);
			})
		</script>
		<style>
			@keyframes fadeIn {
				0%   { opacity: 0; }
				100% { opacity: 1; }
			}
			@keyframes fadeOut {
				0%   { opacity: 1; }
				100% { opacity: 0; }
			}
		</style>

		<?php
		$out = ob_get_clean();

		$out = str_replace('%%ID%%', $id, $out);
		$out = str_replace('%%MSG%%', $msg, $out);
		$out = str_replace('%%CLASS%%', $class, $out);

		return $out;
	}

	#########################################################

	function parseMySQLDate($date, $altDate) {
		// is $date valid?
		if(preg_match("/^\d{4}-\d{1,2}-\d{1,2}$/", trim($date))) {
			return trim($date);
		}

		if($date != '--' && preg_match("/^\d{4}-\d{1,2}-\d{1,2}$/", trim($altDate))) {
			return trim($altDate);
		}

		if($date != '--' && $altDate && intval($altDate)==$altDate) {
			return @date('Y-m-d', @time() + ($altDate >= 1 ? $altDate - 1 : $altDate) * 86400);
		}

		return '';
	}

	#########################################################

	function parseCode($code, $isInsert = true, $rawData = false) {
		if($isInsert) {
			$arrCodes = [
				'<%%creatorusername%%>' => $_SESSION['memberID'],
				'<%%creatorgroupid%%>' => $_SESSION['memberGroupID'],
				'<%%creatorip%%>' => $_SERVER['REMOTE_ADDR'],
				'<%%creatorgroup%%>' => sqlValue("SELECT `name` FROM `membership_groups` WHERE `groupID`='{$_SESSION['memberGroupID']}'"),

				'<%%creationdate%%>' => ($rawData ? @date('Y-m-d') : @date('j/n/Y')),
				'<%%creationtime%%>' => ($rawData ? @date('H:i:s') : @date('h:i:s a')),
				'<%%creationdatetime%%>' => ($rawData ? @date('Y-m-d H:i:s') : @date('j/n/Y h:i:s a')),
				'<%%creationtimestamp%%>' => ($rawData ? @date('Y-m-d H:i:s') : @time())
			];
		} else {
			$arrCodes = [
				'<%%editorusername%%>' => $_SESSION['memberID'],
				'<%%editorgroupid%%>' => $_SESSION['memberGroupID'],
				'<%%editorip%%>' => $_SERVER['REMOTE_ADDR'],
				'<%%editorgroup%%>' => sqlValue("SELECT `name` FROM `membership_groups` WHERE `groupID`='{$_SESSION['memberGroupID']}'"),

				'<%%editingdate%%>' => ($rawData ? @date('Y-m-d') : @date('j/n/Y')),
				'<%%editingtime%%>' => ($rawData ? @date('H:i:s') : @date('h:i:s a')),
				'<%%editingdatetime%%>' => ($rawData ? @date('Y-m-d H:i:s') : @date('j/n/Y h:i:s a')),
				'<%%editingtimestamp%%>' => ($rawData ? @date('Y-m-d H:i:s') : @time())
			];
		}

		$pc = str_ireplace(array_keys($arrCodes), array_values($arrCodes), $code);

		return $pc;
	}

	#########################################################

	function addFilter($index, $filterAnd, $filterField, $filterOperator, $filterValue) {
		// validate input
		if($index < 1 || $index > 80 || !is_int($index)) return false;
		if($filterAnd != 'or')   $filterAnd = 'and';
		$filterField = intval($filterField);

		/* backward compatibility */
		if(in_array($filterOperator, $GLOBALS['filter_operators'])) {
			$filterOperator = array_search($filterOperator, $GLOBALS['filter_operators']);
		}

		if(!in_array($filterOperator, array_keys($GLOBALS['filter_operators']))) {
			$filterOperator = 'like';
		}

		if(!$filterField) {
			$filterOperator = '';
			$filterValue = '';
		}

		$_REQUEST['FilterAnd'][$index] = $filterAnd;
		$_REQUEST['FilterField'][$index] = $filterField;
		$_REQUEST['FilterOperator'][$index] = $filterOperator;
		$_REQUEST['FilterValue'][$index] = $filterValue;

		return true;
	}

	#########################################################

	function clearFilters() {
		for($i=1; $i<=80; $i++) {
			addFilter($i, '', 0, '', '');
		}
	}

	#########################################################

	if(!function_exists('str_ireplace')) {
		function str_ireplace($search, $replace, $subject) {
			$ret=$subject;
			if(is_array($search)) {
				for($i=0; $i<count($search); $i++) {
					$ret=str_ireplace($search[$i], $replace[$i], $ret);
				}
			} else {
				$ret=preg_replace('/'.preg_quote($search, '/').'/i', $replace, $ret);
			}

			return $ret;
		} 
	} 

	#########################################################

	/**
	* Loads a given view from the templates folder, passing the given data to it
	* @param $view the name of a php file (without extension) to be loaded from the 'templates' folder
	* @param $the_data_to_pass_to_the_view (optional) associative array containing the data to pass to the view
	* @return the output of the parsed view as a string
	*/
	function loadView($view, $the_data_to_pass_to_the_view=false) {
		global $Translation;

		$view = dirname(__FILE__)."/templates/$view.php";
		if(!is_file($view)) return false;

		if(is_array($the_data_to_pass_to_the_view)) {
			foreach($the_data_to_pass_to_the_view as $k => $v)
				$$k = $v;
		}
		unset($the_data_to_pass_to_the_view, $k, $v);

		ob_start();
		@include($view);
		$out=ob_get_contents();
		ob_end_clean();

		return $out;
	}

	#########################################################

	/**
	* Loads a table template from the templates folder, passing the given data to it
	* @param $table_name the name of the table whose template is to be loaded from the 'templates' folder
	* @param $the_data_to_pass_to_the_table associative array containing the data to pass to the table template
	* @return the output of the parsed table template as a string
	*/
	function loadTable($table_name, $the_data_to_pass_to_the_table = []) {
		$dont_load_header = $the_data_to_pass_to_the_table['dont_load_header'];
		$dont_load_footer = $the_data_to_pass_to_the_table['dont_load_footer'];

		$header = $table = $footer = '';

		if(!$dont_load_header) {
			// try to load tablename-header
			if(!($header = loadView("{$table_name}-header", $the_data_to_pass_to_the_table))) {
				$header = loadView('table-common-header', $the_data_to_pass_to_the_table);
			}
		}

		$table = loadView($table_name, $the_data_to_pass_to_the_table);

		if(!$dont_load_footer) {
			// try to load tablename-footer
			if(!($footer = loadView("{$table_name}-footer", $the_data_to_pass_to_the_table))) {
				$footer = loadView('table-common-footer', $the_data_to_pass_to_the_table);
			}
		}

		return "{$header}{$table}{$footer}";
	}

	#########################################################

	function filterDropdownBy($filterable, $filterers, $parentFilterers, $parentPKField, $parentCaption, $parentTable, &$filterableCombo) {
		$filterersArray = explode(',', $filterers);
		$parentFilterersArray = explode(',', $parentFilterers);
		$parentFiltererList = '`' . implode('`, `', $parentFilterersArray) . '`';
		$res=sql("SELECT `$parentPKField`, $parentCaption, $parentFiltererList FROM `$parentTable` ORDER BY 2", $eo);
		$filterableData = [];
		while($row=db_fetch_row($res)) {
			$filterableData[$row[0]] = $row[1];
			$filtererIndex = 0;
			foreach($filterersArray as $filterer) {
				$filterableDataByFilterer[$filterer][$row[$filtererIndex + 2]][$row[0]] = $row[1];
				$filtererIndex++;
			}
			$row[0] = addslashes($row[0]);
			$row[1] = addslashes($row[1]);
			$jsonFilterableData .= "\"{$row[0]}\":\"{$row[1]}\",";
		}
		$jsonFilterableData .= '}';
		$jsonFilterableData = '{'.str_replace(',}', '}', $jsonFilterableData);     
		$filterJS = "\nvar {$filterable}_data = $jsonFilterableData;";

		foreach($filterersArray as $filterer) {
			if(is_array($filterableDataByFilterer[$filterer])) foreach($filterableDataByFilterer[$filterer] as $filtererItem => $filterableItem) {
				$jsonFilterableDataByFilterer[$filterer] .= '"'.addslashes($filtererItem).'":{';
				foreach($filterableItem as $filterableItemID => $filterableItemData) {
					$jsonFilterableDataByFilterer[$filterer] .= '"'.addslashes($filterableItemID).'":"'.addslashes($filterableItemData).'",';
				}
				$jsonFilterableDataByFilterer[$filterer] .= '},';
			}
			$jsonFilterableDataByFilterer[$filterer] .= '}';
			$jsonFilterableDataByFilterer[$filterer] = '{'.str_replace(',}', '}', $jsonFilterableDataByFilterer[$filterer]);

			$filterJS.="\n\n// code for filtering {$filterable} by {$filterer}\n";
			$filterJS.="\nvar {$filterable}_data_by_{$filterer} = {$jsonFilterableDataByFilterer[$filterer]}; ";
			$filterJS.="\nvar selected_{$filterable} = \$j('#{$filterable}').val();";
			$filterJS.="\nvar {$filterable}_change_by_{$filterer} = function() {";
			$filterJS.="\n\t$('{$filterable}').options.length=0;";
			$filterJS.="\n\t$('{$filterable}').options[0] = new Option();";
			$filterJS.="\n\tif(\$j('#{$filterer}').val()) {";
			$filterJS.="\n\t\tfor({$filterable}_item in {$filterable}_data_by_{$filterer}[\$j('#{$filterer}').val()]) {";
			$filterJS.="\n\t\t\t$('{$filterable}').options[$('{$filterable}').options.length] = new Option(";
			$filterJS.="\n\t\t\t\t{$filterable}_data_by_{$filterer}[\$j('#{$filterer}').val()][{$filterable}_item],";
			$filterJS.="\n\t\t\t\t{$filterable}_item,";
			$filterJS.="\n\t\t\t\t({$filterable}_item == selected_{$filterable} ? true : false),";
			$filterJS.="\n\t\t\t\t({$filterable}_item == selected_{$filterable} ? true : false)";
			$filterJS.="\n\t\t\t);";
			$filterJS.="\n\t\t}";
			$filterJS.="\n\t} else {";
			$filterJS.="\n\t\tfor({$filterable}_item in {$filterable}_data) {";
			$filterJS.="\n\t\t\t$('{$filterable}').options[$('{$filterable}').options.length] = new Option(";
			$filterJS.="\n\t\t\t\t{$filterable}_data[{$filterable}_item],";
			$filterJS.="\n\t\t\t\t{$filterable}_item,";
			$filterJS.="\n\t\t\t\t({$filterable}_item == selected_{$filterable} ? true : false),";
			$filterJS.="\n\t\t\t\t({$filterable}_item == selected_{$filterable} ? true : false)";
			$filterJS.="\n\t\t\t);";
			$filterJS.="\n\t\t}";
			$filterJS.="\n\t\tif(selected_{$filterable} && selected_{$filterable} == \$j('#{$filterable}').val()) {";
			$filterJS.="\n\t\t\tfor({$filterer}_item in {$filterable}_data_by_{$filterer}) {";
			$filterJS.="\n\t\t\t\tfor({$filterable}_item in {$filterable}_data_by_{$filterer}[{$filterer}_item]) {";
			$filterJS.="\n\t\t\t\t\tif({$filterable}_item == selected_{$filterable}) {";
			$filterJS.="\n\t\t\t\t\t\t$('{$filterer}').value = {$filterer}_item;";
			$filterJS.="\n\t\t\t\t\t\tbreak;";
			$filterJS.="\n\t\t\t\t\t}";
			$filterJS.="\n\t\t\t\t}";
			$filterJS.="\n\t\t\t\tif({$filterable}_item == selected_{$filterable}) break;";
			$filterJS.="\n\t\t\t}";
			$filterJS.="\n\t\t}";
			$filterJS.="\n\t}";
			$filterJS.="\n\t$('{$filterable}').highlight();";
			$filterJS.="\n};";
			$filterJS.="\n$('{$filterer}').observe('change', function() { window.setTimeout({$filterable}_change_by_{$filterer}, 25); });";
			$filterJS.="\n";
		}

		$filterableCombo = new Combo;
		$filterableCombo->ListType = 0;
		$filterableCombo->ListItem = array_slice(array_values($filterableData), 0, 10);
		$filterableCombo->ListData = array_slice(array_keys($filterableData), 0, 10);
		$filterableCombo->SelectName = $filterable;
		$filterableCombo->AllowNull = true;

		return $filterJS;
	}

	#########################################################
	function br2nl($text) {
		return  preg_replace('/\<br(\s*)?\/?\>/i', "\n", $text);
	}

	#########################################################

	if(!function_exists('htmlspecialchars_decode')) {
		function htmlspecialchars_decode($string, $quote_style = ENT_COMPAT) {
			return strtr($string, array_flip(get_html_translation_table(HTML_SPECIALCHARS, $quote_style)));
		}
	}

	#########################################################

	function entitiesToUTF8($input) {
		return preg_replace_callback('/(&#[0-9]+;)/', '_toUTF8', $input);
	}

	function _toUTF8($m) {
		if(function_exists('mb_convert_encoding')) {
			return mb_convert_encoding($m[1], "UTF-8", "HTML-ENTITIES");
		} else {
			return $m[1];
		}
	}

	#########################################################

	function func_get_args_byref() {
		if(!function_exists('debug_backtrace')) return false;

		$trace = debug_backtrace();
		return $trace[1]['args'];
	}

	#########################################################

	function permissions_sql($table, $level = 'all') {
		if(!in_array($level, ['user', 'group'])) { $level = 'all'; }
		$perm = getTablePermissions($table);
		$from = '';
		$where = '';
		$pk = getPKFieldName($table);

		if($perm['view'] == 1 || ($perm['view'] > 1 && $level == 'user')) { // view owner only
			$from = 'membership_userrecords';
			$where = "(`$table`.`$pk`=membership_userrecords.pkValue and membership_userrecords.tableName='$table' and lcase(membership_userrecords.memberID)='" . getLoggedMemberID() . "')";
		} elseif($perm['view'] == 2 || ($perm['view'] > 2 && $level == 'group')) { // view group only
			$from = 'membership_userrecords';
			$where = "(`$table`.`$pk`=membership_userrecords.pkValue and membership_userrecords.tableName='$table' and membership_userrecords.groupID='" . getLoggedGroupID() . "')";
		} elseif($perm['view'] == 3) { // view all
			// no further action
		} elseif($perm['view'] == 0) { // view none
			return false;
		}

		return ['where' => $where, 'from' => $from, 0 => $where, 1 => $from];
	}

	#########################################################

	function error_message($msg, $back_url = '', $full_page = true) {
		$curr_dir = dirname(__FILE__);
		global $Translation;

		ob_start();

		if($full_page) include($curr_dir . '/header.php');

		echo '<div class="panel panel-danger">';
			echo '<div class="panel-heading"><h3 class="panel-title">' . $Translation['error:'] . '</h3></div>';
			echo '<div class="panel-body"><p class="text-danger">' . $msg . '</p>';
			if($back_url !== false) { // explicitly passing false suppresses the back link completely
				echo '<div class="text-center">';
				if($back_url) {
					echo '<a href="' . $back_url . '" class="btn btn-danger btn-lg vspacer-lg"><i class="glyphicon glyphicon-chevron-left"></i> ' . $Translation['< back'] . '</a>';
				} else {
					echo '<a href="#" class="btn btn-danger btn-lg vspacer-lg" onclick="history.go(-1); return false;"><i class="glyphicon glyphicon-chevron-left"></i> ' . $Translation['< back'] . '</a>';
				}
				echo '</div>';
			}
			echo '</div>';
		echo '</div>';

		if($full_page) include($curr_dir . '/footer.php');

		return ob_get_clean();
	}

	#########################################################

	function toMySQLDate($formattedDate, $sep = datalist_date_separator, $ord = datalist_date_format) {
		// extract date elements
		$de=explode($sep, $formattedDate);
		$mySQLDate=intval($de[strpos($ord, 'Y')]).'-'.intval($de[strpos($ord, 'm')]).'-'.intval($de[strpos($ord, 'd')]);
		return $mySQLDate;
	}

	#########################################################

	function reIndex(&$arr) {
		$i=1;
		foreach($arr as $n=>$v) {
			$arr2[$i]=$n;
			$i++;
		}
		return $arr2;
	}

	#########################################################

	function get_embed($provider, $url, $max_width = '', $max_height = '', $retrieve = 'html') {
		global $Translation;
		if(!$url) return '';

		$providers = [
			'youtube' => ['oembed' => 'https://www.youtube.com/oembed?'],
			'googlemap' => ['oembed' => '', 'regex' => '/^http.*\.google\..*maps/i'],
		];

		if(!isset($providers[$provider])) {
			return '<div class="text-danger">' . $Translation['invalid provider'] . '</div>';
		}

		if(isset($providers[$provider]['regex']) && !preg_match($providers[$provider]['regex'], $url)) {
			return '<div class="text-danger">' . $Translation['invalid url'] . '</div>';
		}

		if($providers[$provider]['oembed']) {
			$oembed = $providers[$provider]['oembed'] . 'url=' . urlencode($url) . "&amp;maxwidth={$max_width}&amp;maxheight={$max_height}&amp;format=json";
			$data_json = request_cache($oembed);

			$data = json_decode($data_json, true);
			if($data === null) {
				/* an error was returned rather than a json string */
				if($retrieve == 'html') return "<div class=\"text-danger\">{$data_json}\n<!-- {$oembed} --></div>";
				return '';
			}

			return (isset($data[$retrieve]) ? $data[$retrieve] : $data['html']);
		}

		/* special cases (where there is no oEmbed provider) */
		if($provider == 'googlemap') return get_embed_googlemap($url, $max_width, $max_height, $retrieve);

		return '<div class="text-danger">Invalid provider!</div>';
	}

	#########################################################

	function get_embed_googlemap($url, $max_width = '', $max_height = '', $retrieve = 'html') {
		global $Translation;
		$url_parts = parse_url($url);
		$coords_regex = '/-?\d+(\.\d+)?[,+]-?\d+(\.\d+)?(,\d{1,2}z)?/'; /* https://stackoverflow.com/questions/2660201 */

		if(preg_match($coords_regex, $url_parts['path'] . '?' . $url_parts['query'], $m)) {
			list($lat, $long, $zoom) = explode(',', $m[0]);
			$zoom = intval($zoom);
			if(!$zoom) $zoom = 10; /* default zoom */
			if(!$max_height) $max_height = 360;
			if(!$max_width) $max_width = 480;

			$api_key = config('adminConfig')['googleAPIKey'];
			$embed_url = "https://www.google.com/maps/embed/v1/view?key={$api_key}&amp;center={$lat},{$long}&amp;zoom={$zoom}&amp;maptype=roadmap";
			$thumbnail_url = "https://maps.googleapis.com/maps/api/staticmap?key={$api_key}&amp;center={$lat},{$long}&amp;zoom={$zoom}&amp;maptype=roadmap&amp;size={$max_width}x{$max_height}";

			if($retrieve == 'html') {
				return "<iframe width=\"{$max_width}\" height=\"{$max_height}\" frameborder=\"0\" style=\"border:0\" src=\"{$embed_url}\"></iframe>";
			} else {
				return $thumbnail_url;
			}
		} else {
			return '<div class="text-danger">' . $Translation['cant retrieve coordinates from url'] . '</div>';
		}
	}

	#########################################################

	function request_cache($request, $force_fetch = false) {
		$max_cache_lifetime = 7 * 86400; /* max cache lifetime in seconds before refreshing from source */

		/* membership_cache table exists? if not, create it */
		static $cache_table_exists = false;
		if(!$cache_table_exists && !$force_fetch) {
			$te = sqlValue("show tables like 'membership_cache'");
			if(!$te) {
				if(!sql("CREATE TABLE `membership_cache` (`request` VARCHAR(100) NOT NULL, `request_ts` INT, `response` TEXT NOT NULL, PRIMARY KEY (`request`))", $eo)) {
					/* table can't be created, so force fetching request */
					return request_cache($request, true);
				}
			}
			$cache_table_exists = true;
		}

		/* retrieve response from cache if exists */
		if(!$force_fetch) {
			$res = sql("select response, request_ts from membership_cache where request='" . md5($request) . "'", $eo);
			if(!$row = db_fetch_array($res)) return request_cache($request, true);

			$response = $row[0];
			$response_ts = $row[1];
			if($response_ts < time() - $max_cache_lifetime) return request_cache($request, true);
		}

		/* if no response in cache, issue a request */
		if(!$response || $force_fetch) {
			$response = @file_get_contents($request);
			if($response === false) {
				$error = error_get_last();
				$error_message = preg_replace('/.*: (.*)/', '$1', $error['message']);
				return $error_message;
			} elseif($cache_table_exists) {
				/* store response in cache */
				$ts = time();
				sql("replace into membership_cache set request='" . md5($request) . "', request_ts='{$ts}', response='" . makeSafe($response, false) . "'", $eo);
			}
		}

		return $response;
	}

	#########################################################

	function check_record_permission($table, $id, $perm = 'view') {
		if($perm != 'edit' && $perm != 'delete') $perm = 'view';

		$perms = getTablePermissions($table);
		if(!$perms[$perm]) return false;

		$safe_id = makeSafe($id);
		$safe_table = makeSafe($table);

		if($perms[$perm] == 1) { // own records only
			$username = getLoggedMemberID();
			$owner = sqlValue("select memberID from membership_userrecords where tableName='{$safe_table}' and pkValue='{$safe_id}'");
			if($owner == $username) return true;
		} elseif($perms[$perm] == 2) { // group records
			$group_id = getLoggedGroupID();
			$owner_group_id = sqlValue("select groupID from membership_userrecords where tableName='{$safe_table}' and pkValue='{$safe_id}'");
			if($owner_group_id == $group_id) return true;
		} elseif($perms[$perm] == 3) { // all records
			return true;
		}

		return false;
	}

	#########################################################

	function NavMenus($options = []) {
		if(!defined('PREPEND_PATH')) define('PREPEND_PATH', '');
		global $Translation;
		$prepend_path = PREPEND_PATH;

		/* default options */
		if(empty($options)) {
			$options = ['tabs' => 7];
		}

		$table_group_name = array_keys(get_table_groups()); /* 0 => group1, 1 => group2 .. */
		/* if only one group named 'None', set to translation of 'select a table' */
		if((count($table_group_name) == 1 && $table_group_name[0] == 'None') || count($table_group_name) < 1) $table_group_name[0] = $Translation['select a table'];
		$table_group_index = array_flip($table_group_name); /* group1 => 0, group2 => 1 .. */
		$menu = array_fill(0, count($table_group_name), '');

		$t = time();
		$arrTables = getTableList();
		if(is_array($arrTables)) {
			foreach($arrTables as $tn => $tc) {
				/* ---- list of tables where hide link in nav menu is set ---- */
				$tChkHL = array_search($tn, ['sugerir_valor','sugerir_atividade','c001_ref','c001_ref_colaborar','c001_ref_inativas','c002_ref','c002_ref_colaborar','c002_ref_inativas','c003_ref','c003_ref_colaborar','c003_ref_inativas','c004_ref','c004_ref_colaborar','c004_ref_inativas']);

				/* ---- list of tables where filter first is set ---- */
				$tChkFF = array_search($tn, []);
				if($tChkFF !== false && $tChkFF !== null) {
					$searchFirst = '&Filter_x=1';
				} else {
					$searchFirst = '';
				}

				/* when no groups defined, $table_group_index['None'] is NULL, so $menu_index is still set to 0 */
				$menu_index = intval($table_group_index[$tc[3]]);
				if(!$tChkHL && $tChkHL !== 0) $menu[$menu_index] .= "<li><a href=\"{$prepend_path}{$tn}_view.php?t={$t}{$searchFirst}\"><img src=\"{$prepend_path}" . ($tc[2] ? $tc[2] : 'blank.gif') . "\" height=\"32\"> {$tc[0]}</a></li>";
			}
		}

		// custom nav links, as defined in "hooks/links-navmenu.php" 
		global $navLinks;
		if(is_array($navLinks)) {
			$memberInfo = getMemberInfo();
			$links_added = [];
			foreach($navLinks as $link) {
				if(!isset($link['url']) || !isset($link['title'])) continue;
				if(getLoggedAdmin() !== false || @in_array($memberInfo['group'], $link['groups']) || @in_array('*', $link['groups'])) {
					$menu_index = intval($link['table_group']);
					if(!$links_added[$menu_index]) $menu[$menu_index] .= '<li class="divider"></li>';

					/* add prepend_path to custom links if they aren't absolute links */
					if(!preg_match('/^(http|\/\/)/i', $link['url'])) $link['url'] = $prepend_path . $link['url'];
					if(!preg_match('/^(http|\/\/)/i', $link['icon']) && $link['icon']) $link['icon'] = $prepend_path . $link['icon'];

					$menu[$menu_index] .= "<li><a href=\"{$link['url']}\"><img src=\"" . ($link['icon'] ? $link['icon'] : "{$prepend_path}blank.gif") . "\" height=\"32\"> {$link['title']}</a></li>";
					$links_added[$menu_index]++;
				}
			}
		}

		$menu_wrapper = '';
		for($i = 0; $i < count($menu); $i++) {
			$menu_wrapper .= <<<EOT
				<li class="dropdown">
					<a href="#" class="dropdown-toggle" data-toggle="dropdown">{$table_group_name[$i]} <b class="caret"></b></a>
					<ul class="dropdown-menu" role="menu">{$menu[$i]}</ul>
				</li>
EOT;
		}

		return $menu_wrapper;
	}

	#########################################################

	function StyleSheet() {
		if(!defined('PREPEND_PATH')) define('PREPEND_PATH', '');
		$prepend_path = PREPEND_PATH;

		$css_links = <<<EOT

			<link rel="stylesheet" href="{$prepend_path}resources/initializr/css/bootstrap.css">
			<link rel="stylesheet" href="{$prepend_path}resources/lightbox/css/lightbox.css" media="screen">
			<link rel="stylesheet" href="{$prepend_path}resources/select2/select2.css" media="screen">
			<link rel="stylesheet" href="{$prepend_path}resources/timepicker/bootstrap-timepicker.min.css" media="screen">
			<link rel="stylesheet" href="{$prepend_path}dynamic.css">
EOT;

		return $css_links;
	}

	#########################################################

	function PrepareUploadedFile($FieldName, $MaxSize, $FileTypes = 'jpg|jpeg|gif|png', $NoRename = false, $dir = '') {
		global $Translation;
		$f = $_FILES[$FieldName];
		if($f['error'] == 4 || !$f['name']) return '';

		$dir = getUploadDir($dir);

		/* get php.ini upload_max_filesize in bytes */
		$php_upload_size_limit = trim(ini_get('upload_max_filesize'));
		$last = strtolower($php_upload_size_limit[strlen($php_upload_size_limit) - 1]);
		switch($last) {
			case 'g':
				$php_upload_size_limit *= 1024;
			case 'm':
				$php_upload_size_limit *= 1024;
			case 'k':
				$php_upload_size_limit *= 1024;
		}

		$MaxSize = min($MaxSize, $php_upload_size_limit);

		if($f['size'] > $MaxSize || $f['error']) {
			echo error_message(str_replace(['<MaxSize>', '{MaxSize}'], intval($MaxSize / 1024), $Translation['file too large']));
			exit;
		}
		if(!preg_match('/\.(' . $FileTypes . ')$/i', $f['name'], $ft)) {
			echo error_message(str_replace(['<FileTypes>', '{FileTypes}'], str_replace('|', ', ', $FileTypes), $Translation['invalid file type']));
			exit;
		}

		$name = str_replace(' ', '_', $f['name']);
		if(!$NoRename) $name = substr(md5(microtime() . rand(0, 100000)), -17) . $ft[0];

		if(!file_exists($dir)) @mkdir($dir, 0777);

		if(!@move_uploaded_file($f['tmp_name'], $dir . $name)) {
			echo error_message("Couldn't save the uploaded file. Try chmoding the upload folder '{$dir}' to 777.");
			exit;
		}

		@chmod($dir . $name, 0666);
		return $name;
	}

	#########################################################

	function get_home_links($homeLinks, $default_classes, $tgroup = '') {
		if(!is_array($homeLinks) || !count($homeLinks)) return '';

		$memberInfo = getMemberInfo();

		ob_start();
		foreach($homeLinks as $link) {
			if(!isset($link['url']) || !isset($link['title'])) continue;
			if($tgroup != $link['table_group'] && $tgroup != '*') continue;

			/* fall-back classes if none defined */
			if(!$link['grid_column_classes']) $link['grid_column_classes'] = $default_classes['grid_column'];
			if(!$link['panel_classes']) $link['panel_classes'] = $default_classes['panel'];
			if(!$link['link_classes']) $link['link_classes'] = $default_classes['link'];

			if(getLoggedAdmin() !== false || @in_array($memberInfo['group'], $link['groups']) || @in_array('*', $link['groups'])) {
				?>
				<div class="col-xs-12 <?php echo $link['grid_column_classes']; ?>">
					<div class="panel <?php echo $link['panel_classes']; ?>">
						<div class="panel-body">
							<a class="btn btn-block btn-lg <?php echo $link['link_classes']; ?>" title="<?php echo preg_replace("/&amp;(#[0-9]+|[a-z]+);/i", "&$1;", html_attr(strip_tags($link['description']))); ?>" href="<?php echo $link['url']; ?>"><?php echo ($link['icon'] ? '<img src="' . $link['icon'] . '">' : ''); ?><strong><?php echo $link['title']; ?></strong></a>
							<div class="panel-body-description"><?php echo $link['description']; ?></div>
						</div>
					</div>
				</div>
				<?php
			}
		}

		$html = ob_get_contents();
		ob_end_clean();

		return $html;
	}

	#########################################################

	function quick_search_html($search_term, $label, $separate_dv = true) {
		global $Translation;

		$safe_search = html_attr($search_term);
		$safe_label = html_attr($label);
		$safe_clear_label = html_attr($Translation['Reset Filters']);

		if($separate_dv) {
			$reset_selection = "document.myform.SelectedID.value = '';";
		} else {
			$reset_selection = "document.myform.writeAttribute('novalidate', 'novalidate');";
		}
		$reset_selection .= ' document.myform.NoDV.value=1; return true;';

		$html = <<<EOT
		<div class="input-group" id="quick-search">
			<input type="text" id="SearchString" name="SearchString" value="{$safe_search}" class="form-control" placeholder="{$safe_label}">
			<span class="input-group-btn">
				<button name="Search_x" value="1" id="Search" type="submit" onClick="{$reset_selection}" class="btn btn-default" title="{$safe_label}"><i class="glyphicon glyphicon-search"></i></button>
				<button name="ClearQuickSearch" value="1" id="ClearQuickSearch" type="submit" onClick="\$j('#SearchString').val(''); {$reset_selection}" class="btn btn-default" title="{$safe_clear_label}"><i class="glyphicon glyphicon-remove-circle"></i></button>
			</span>
		</div>
EOT;
		return $html;
	}

	#########################################################

