<?php
/**
* (c) 2000, 2001, 2002, 2003 Remistech Sdn Bhd. All Rights Reserved.
*  Developed by John Lim
*  Licensed to Natsoft (M) Sdn Bhd to distribute and support. Refer to LICENSE document.
*/ 

/*---------------------------------------------------------------------------------------*/
// UI
/*---------------------------------------------------------------------------------------*/

function LensModifyUI(&$lens)
{
	//if ($lens->detailRightColor === 'white class=lens-dright') return;
	if (!($lens->colorNavBorder === 'gray' && $lens->colorOdd === 'beige')) return;
	
	$txt = strip_tags($lens->lang->topCaption);
	$lens->lang->topCaption = "<span id=bold-b>$txt</span>";
	$lens->colorNav = '#F0F0F0 class=lens-nav';
	$lens->colorNavBorder = '#F0F0F0 class=lens-nav';
	$lens->scrollBgColor = '#F0F0F0 class=lens-nav';
	$lens->colorTitle = '#C0C0F0 id=lens-title';
	$lens->colorSort = 'paleturquoise id=lens-sort';
	$lens->colorSelect = 'lightblue id=lens-select';
	$lens->colorOdd = 'white id=lens-odd';
	$lens->colorEven = 'white id=lens-even';
	$lens->navTableHeader = 'cellspacing="0" cellpadding="2"';
	$lens->layoutTableHeader = 'align="center" border="0" cellspacing="0" cellpadding="0" width="100%" ';
	$lens->gridTableHeader = 'border="0" cellspacing="1" cellpadding="1" width="100%"';
	$lens->detailTableHeader = 'width="100%" border="0" cellspacing="1" cellpadding="1"';
	$lens->border0 = 2;
	$lens->titleFontPrefix = '';
	$lens->titleFontSuffix = '';
	$lens->detailTitleFontPrefix = '<span id=lens-dtitle>';
	$lens->detailTitleFontSuffix = '</span>';
	$lens->detailLeftColor = 'white id=lens-detrow';
	$lens->detailRightColor = 'white class=lens-dright';
	$lens->colorBackground = 'white id=lens-bg';
	$lens->menuHide = 'BOTTOM';
	$lens->filterTopColor = '#f0f0f0 class=lens-nav';
	$lens->css = false;
}


/*---------------------------------------------------------------------------------------*/
// Connections
/*---------------------------------------------------------------------------------------*/

/**
 	Connect with non-persistent database connection and return new phpLens object
*/
function &PHPLensConnect($id,$sql,$dbms,$server=false,$user=false,$pwd=false, $db=false,$lang=PHPLENS_LANG_DEFAULT)
{
	if (func_num_args() == 3) {
	global $PHPLENS_DATABASES;
		if (isset($PHPLENS_DATABASES[$dbms])) {
			$a = $PHPLENS_DATABASES[$dbms];
			$dbms = $a[0];
			$server = @$a[1];
			$user = @$a[2];
			$pwd = @$a[3];
			$db = @$a[4]; 
		}
	}
	$conn = &ADONewConnection($dbms);
	if (!$conn->Connect($server,$user,$pwd,$db)) return false;
	return new PHPLens($id,$conn,$sql,$lang);
}

/**
 	Connect with persistent database connection and return new phpLens object.
*/
function &PHPLensPConnect($id,$sql,$dbms,$server=false,$user=false,$pwd=false, $db=false,$lang=PHPLENS_LANG_DEFAULT)
{
	if (func_num_args() == 3) {
	global $PHPLENS_DATABASES;
		if (isset($PHPLENS_DATABASES[$dbms])) {
			$a = $PHPLENS_DATABASES[$dbms];
			$dbms = $a[0];
			$server = @$a[1];
			$user = @$a[2];
			$pwd = @$a[3];
			$db = @$a[4]; 
		}
	}
	$conn = &ADONewConnection($dbms);
	if (!$conn->PConnect($server,$user,$pwd,$db)) return false;
	return new PHPLens($id,$conn,$sql,$lang);
}

/**
	Reset PHPLensArray by clearing all session variables used.
*/
function PHPLensArrayReset($id)
{
GLOBAL $HTTP_SESSION_VARS;

	$sessarray = "ARRAY_$id";
	GLOBAL $$sessarray;
	
	$HTTP_SESSION_VARS[$sessarray] = '';
}

/**
	Setup phpLen to use session variables to store data instead of database, 
	and return new phpLens object using the session array.
*/
function &PHPLensArray($id,$data,$types=false,$cols=false,$lang=PHPLENS_LANG_DEFAULT)
{
GLOBAL $PHPLENS_CONN,$HTTP_SESSION_VARS;
	
	$sessarray = "ARRAY_$id";
	$colsname = "ARRAYCOLS_$id";
	GLOBAL $$sessarray,$$colsname;
	if (@is_array($HTTP_SESSION_VARS[$sessarray])) {
		$loaded = true;
		$data = $HTTP_SESSION_VARS[$sessarray];
		$$sessarray = $data;
		$cols = $HTTP_SESSION_VARS[$colsname];
		$$colsname = $cols;
	} else
		$loaded =false;
		
	$PHPLENS_CONN[$id] = ADONewConnection('text');

/*
 	$db = &NewADOConnection('text');
 	$db->Connect($array,[$types],[$colnames]);
	
	Parameter $array is the 2 dimensional array of data. The first row can contain the
	column names. If column names is not defined in first row, you MUST define $colnames,
	the 3rd parameter.
	
	Parameter $types is optional. If defined, it should contain an array matching
	the number of columns in $array, with each element matching the correct type defined
	by MetaType: (B,C,I,L,N). If undefined, we will probe for $this->_proberows rows
	to guess the type. Only C,I and N are recognised.
	
	Parameter $colnames is optional. If defined, it is an array that contains the 
	column names of $array. If undefined, we assume the first row of $array holds the 
	column names.
*/
	
	// check for 1-dim array, convert to 2-dim array
	if (is_array($data) && sizeof($data) > 0)  {
		if (!is_array(reset($data))) $data = array($data);
		if (!$cols) {
			$arr = $data[0];
			$keys = array_keys($arr);
			$i = 0;
			$stripkeys = false;
			foreach($keys as $k) {
				if (is_numeric($k)) $cols[] = 'col_'.$k;
				else {
					$stripkeys = true;
					if (preg_match('/[^a-z0-9_]/i',$k)) {
						$cols[] = 'col__'.$i;
					} else	
						$cols[] = $k;
				}
			
				$i += 1;
			} // foreach
			
			if ($stripkeys) {
				foreach($data as $row) {
					$d2[] = array_values($row);
				}
				$data = $d2;
			}
		}
		
		if ($cols) $zcols = $cols;
		else $zcols = $data[0];
		$spEdit = '=LensUpdateArray('."'$id'".',{_PRIMARY_KEY_},{'.implode('}, {',$zcols).'})';
	} else {
		$spEdit = false;
	}
	if (!$loaded) {
		$HTTP_SESSION_VARS[$sessarray] = $$sessarray = $data;
		$HTTP_SESSION_VARS[$colsname] = $$colsname = $cols;
	}
	
	$conn = &$PHPLENS_CONN[$id];
	if (!$conn->Connect($data,$types,$cols)) return false;

	$lens = new PHPLens($id,$conn,'select * from table',$lang);
	$lens->spEdit = $spEdit;
	$lens->keyCol = $cols[0];
	$lens->keyTable = 'table';
	$lens->canEdit = true;
	$lens->_isarray = true;
	return $lens;
}



/*---------------------------------------------------------------------------------------*/
// Debugging and Detection
/*---------------------------------------------------------------------------------------*/

/*
	Detects the browser agent. Returns OPERA, MSIE, GECKO, or NN
*/
function LensBrowserAgent()
{
static $agent;

	if (isset($agent)) return $agent;
	
GLOBAL $HTTP_SERVER_VARS;

	$u = strtoupper($HTTP_SERVER_VARS['HTTP_USER_AGENT']);
	
	if (strpos($u, 'OPERA') !== false) $agent = 'OPERA';
	else if (strpos($u,'MSIE') !== false) $agent = 'MSIE'; 
	else if (strpos($u,'GECKO') !== false) $agent = 'GECKO';
	else if (strpos($u,'KONQUEROR') !== false) $agent = 'KONQ';
	else $agent = 'NN';
	return $agent;
}

/**
	Debugging version of print_r with pre tag formatting.
*/
function print_pre($r,$what='')
{
	if ($what) $what .= ' ';
	print "<pre>$what";
	print_r($r);
	print '</pre>';
}


/*---------------------------------------------------------------------------------------*/
// Formatting and Display
/*---------------------------------------------------------------------------------------*/


// shorten PHP_SELF so the HTML generated is tighter
function PHPLensShortenPHPSELF($PHP_SELF)
{
	if (LensBrowserAgent() != 'NN') return '';
	else return basename($PHP_SELF);
}


// Strip off default <font> tags. Reduces page size by about 5%.
function PHPLensLightFonts(&$lens,$classname='lv',$fsize='x-small')
{
static $SENT;

#text-align:right

if (!isset($SENT)) {
	echo '
<style type="text/css" media="all">
.'.$classname.' {font-size: '.$fsize.'}
.lvbw {font-size:'.$fsize.'; color: white; font-weight: bold}
#lvsubsum {border-top: 1px solid #c0c0c0}
#lvsum {border-top: 2px solid #c0c0c0; border-bottom: 2px solid #c0c0c0}
#lvpagebreak {page-break-after: always}
</style>
';
	$SENT = true;
}

$lens->filterFontPrefix = '';
$lens->filterFontSuffix = '';


## GRID CELLS
$lens->oddHeader = 'class='.$classname;
$lens->evenHeader = 'class='.$classname;
$lens->cellFontPrefix = '';
$lens->cellFontSuffix = '';

## GRID TITLES
$lens->titleHeader='';
$lens->titleFontPrefix = '';
$lens->titleFontSuffix = '';

## SELECTED COLUMN TITLE (when sorted)
$lens->fontSelColPrefix = '';
$lens->fontSelColSuffix = '';

## DETAIL VALUES
$lens->detailFontPrefix = '';
$lens->detailFontSuffix = '';

## DETAIL TITLES/EDIT TITLES/NEW TITLES
#$lens->detailTitleFontPrefix = '';
#$lens->detailTitleFontSuffix = '';

$lens->detailTitleHeader = '';
$lens->detailValueHeader = 'class='.$classname;

## SCROLLING LINKS IN SCROLL AREA  << 1 2 3 4 5 6 7 8 9 10 >>
//$lens->scrollFontPrefix = '';
//$lens->scrollFontSuffix = '';

## CURRENT PAGE SCROLLED TO IN SCROLL AREA
$lens->scrollHiliteFontPrefix = '';
$lens->scrollFontSuffix = '';
}


// Replacement for htmlspecialchars() for double-byte support because 
// double-byte characters include '&', we cannot convert them using 
// htmlspecialchars()
 function LensStrTr($txt)
 {
 static $trtab;
	
	if (!is_array($trtab)) {
		$trtab = get_html_translation_table(HTML_SPECIALCHARS);
		$trtab['&'] = '&';
	}
 	return strtr(preg_replace('/&([b-z]+;)/','&amp;\1',$txt),$trtab);
 }
 
 // Replacement for htmlspecialchars() for double-byte support because 
// double-byte characters include '&', we cannot convert them using 
// htmlspecialchars()
 function LensStrTrNbsp($txt)
 {
 static $trtab;
	
	if (!is_array($trtab)) {
		$trtab = get_html_translation_table(HTML_SPECIALCHARS);
		$trtab['&'] = '&';
	}
	// skip 1. &n as is probably &nbsp; and 2. &a as probably &amp;
 	return strtr(preg_replace('/&([b-mo-z]+;)/','&amp;\1',$txt),$trtab);
 }
 
// format a number for display
function PHPLensFormatNum(&$lens,$n)
{
	if ($lens->fmtThousands) return number_format($n, $lens->fmtDecimalPlaces, $lens->fmtDecimal, $lens->fmtThousands);
	return trim(sprintf("%14.{$lens->fmtDecimalPlaces}f",$n));
} 


// Detect url's in strings and generate anchor tags for these substrings.
//  Use a special convention so we can recognise these
// autoconverted strings quickly by adding 3 spaces between <a and href=...>
// and two spaces after </a  >
function phplens_str2url($s)
{
// the prefix char must not ' or " or the semi-colon in &quot;
// the termination char for a url is whitespace, commas, and < or > 
$h1 = '/([^\'";])(http[s]?\:\/\/\S+\.[^\(\)\[\]\s<,]+)/i'; // http not prefixed by quotes
$h2 = '/([^\/a-z0-9]){1,1}(www\.\S+\.[^\(\)\[\]\s<,]+)/i'; // www.a.com not prefixed by in //
$em = '/\b([a-z0-9\-_]+\@[a-z0-9\-_\.]+\.[a-z0-9\-_]+)\b/i'; // email

// special case beginning of the line
$h11 = '/^(http[s]?\:\/\/\S+\.[^\(\)\[\]\s<,]+)/i';
$h21 = '/^(www\.\S+\.[^\s<,]+)/i';

	$s = preg_replace($em,'<a   href="mailto:\1">$1</a  >',$s);
	$s = preg_replace($h1,'\1<a   href="\2">\2</a  >',$s);
	$s = preg_replace($h11,'<a   href="\1">$1</a  >',$s);
	$s = preg_replace($h2,'\1<a   href="http://\2">\2</a  >',$s);
	return preg_replace($h21,'<a   href="http://\1">\1</a  >',$s);
}

// convert urls generated above back to strings, stripping off anchor tags.
function phplens_url2str($s)
{
 $a1 = '/<a   href[^>]*>/i';
 $a2 = '/<\/a  >/i';
	$s = preg_replace($a1,'',$s);
	$s = preg_replace($a2,'',$s);
	return (strlen($s) == 0) ?  '' : $s;
}


/*	
	The packed compound key format.
		
	Usage for packing a compound key of two fields, the first is a character
		type, and the second is an integer type. We prefix each key with it's
		metatype and a hyphen seperator. The field order should match the order
		of $lens->keyCompound.
		
		LensPackKeys(array('C-FieldValue','I-80'));
		
		Output:
		
		.C-FieldValue.I-80.
*/
function LensPackKeys($keys)
{
	if (!is_array($keys)) return false;
	$s = '.';
	foreach($keys as $v) {
		$s .= str_replace('.','%2E',rawurlencode($v)).'.';
	}
	return $s;
}

/* 
	The reverse of LensPackKeys
*/
function LensUnpackKeys($str,$striptype = false)
{
	if ($str[0] != '.') return false;
	if ($str[strlen($str)-1] != '.') return false;
	$str = explode('.',substr($str,1,strlen($str)-2));
	foreach($str as $k => $v) {
		if ($striptype) $str[$k] = substr(rawurldecode($v),2);
		else $str[$k] = rawurldecode($v);
	}
	return $str;
}

/*
	Code used to sanitize GET/POST data to prevent sql injection attacks
*/
function LensAuditParam($val,$t,$conn,$quote=true,$checkmq=true)
{
		switch($t){
		case 'C':
		case 'X':
			if ($quote) $val = $conn->qstr($val, ($checkmq) ? get_magic_quotes_gpc() : false);
			break;
		case 'D':
			$val = $conn->DBDate(ADOConnection::UnixDate($val));
			if (!$quote) $val = LensStripQ($val);
			break;
		case 'T':
			$val = $conn->DBTimeStamp(ADOConnection::UnixTimeStamp($val));
			if (!$quote) $val = LensStripQ($val);
			break;
		default:
			if (!is_numeric($val)) $val = (float) $val; // convert anything suspicious to a number
			break;
		}
		//print "LensAuditParam quote=$quote val=$val type=$t <br> ";
		return $val;
}

/*
	Javascript to display when in VIEW state. The "lensdr" function stands for
	LENS Delete Record.
*/
function LensRenderViewJS($deltxt)
{
static $rendered;

	if (isset($rendered)) return;
	$rendered = true;
	$txt = addslashes($deltxt);	
	if (LensBrowserAgent() == 'KONQ') $cancelbubble = '';
	else $cancelbubble = 'if (window.event) window.event.cancelBubble = true';
	echo "
<script>
<!--
function lensdr(r) 
{
$cancelbubble
return confirm('{$txt} #'+r+' ?');
}
-->
</script>
";
}

?>