<?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.
*/ 

/*--------------------------------------------------------------------------------------------------*/
//                                        VERSION NUMBER
/*--------------------------------------------------------------------------------------------------*/
define('PHPLENS_VERSION', '3.3.4');

/*--------------------------------------------------------------------------------------------------*/
//                                           CHANGE LOG
/*---------------------------------------------------------------------------------------------------/
=== 3.3.4  1 Nov 2003
	Fixed installer bugs. Especially in template.shtml.

=== 3.3.3  31 Oct 2003
	Added to NOFOCUS to saveOptions, (new property to disable selection of input on NEW/EDIT). 
		eg. $lens->saveOptions = 'NOFOCUS';

	Now sumLens sets 0 correctly when summing cols with zero values. Reported by Laura.
	Now if hot update on a mustfill field, and only 1 record returned, we do not generate
		the blank first popup selection. 
	Data input/validation of when entering $lens->fmtDecimal did not work previously.
	Changed handling of numbers to support European languages where decimal is ','. Added fmtDecimal and fmtDecimalDB.
	Primary key in some areas not urlencoded in anchor tags. Causing problems with keys with
		funny chars such as ' or < >.
	Added additional checks that key column is numeric or string when generating WHERE clause.
	Generalized code to use $conn->Params();
	The sql generated by sqlDetail did not work if it contained a WHERE clause. Fixed.
	The sql used when editing records might not work if the primary key was char with oracle and
		the sql used when editing char records that stored numbers also had problems. Fixed.
	Tested with PHP5 beta 2.
	
=== 3.3.2 
	Now saveOptions property, collections option allow setting of collection name.
	When saving checkboxes/radios and error occurs, the checkboxes/radios were not 
		properly restored. Fixed.
		
=== 3.3.1 2 Oct 2003
	Bug in introduced in 3.3.0 validation fixed.
	
=== 3.3.0 1 Oct 2003
	spNew and spEdit now allow returning error messages (return array($errormsg)).
	Problem with xml support - wrongly stripped off white space. Fixed.
	Fix for  searchlookuplens bugs. Search btn not displayed again on Cancel, 
		primary key field not hidden. Reported by earl.
	Some cancel btns in dynedit did not work. Fixed.
	Search/Filter forms now use GET instead of POST, so you can "Go Back" in browser.
	Installer version check for PHP did not work for initial PHP version allowed. 
		Reported by Luis Ay.
	Redesigned js validation error alert. Formerly:
	
	+----------------------------------+
	|	Field = First Name
	|	Invalid characters in field
	|
	|	First Name:
	|	Johnny Foo$$34R#^
	+----------------------------------+	
	
	Now:
	
	+----------------------------------+
	|	Invalid characters in field
	|	
	|	Field = First Name
	|	
	|	  Johnny Foo$$34R#^
	+----------------------------------+
	
	
=== 3.2.2 26 Aug 2003
	Released to bar council.
	filterDefaults property - only works in FILTER state, not FILTERVIEW.
	Multiple applets in filterState could cause confusion as to which applet the $_GET/$_POST
		vars are refering to - fixed.
	When child editor enabled, and filtering did not return any records, it is possible
		for child editor to be in EDIT when it should be in NEW state. Fixed.
	Now bind parameters also obey filterModifierFn
	
=== 3.2.1 22 Aug 2003
	When border0 set to flat with frames (2), and table widths set to 100%,
		 then the width of details when below grid was not 100% -- fixed.
	Added filterTopColor property
	Added METAPHP for hot updates. Added remoteq directory for MetaPHP support.
	Fixed bug when cellColorLens and overlibLens was used on the same col. 
		The cellColorLens was ignored - reported by david sp.
	The compoundKey was being overwritten on every save in the dyneditor 
		- reported by david sp.
	If firstState was FILTER or FILTERVIEW, after saving in dynedit, 
		did not revert to firstState correctly. Fixed.
	Hot updates did not convert &nbsp; to non-breaking space correctly in javascript.
		Although fixed, i suspect other problems with other &entities; and unicode
		characters still persist.
		
=== 3.2.0/3.1.5 13 Aug 2003
	The detail grid were not hidden properly if showDetails == false and keyVariable set. Fixed.
	Some bugs in lookups involving #Meta*. Fixed.
	Numbers in detail grid are now left-aligned!
	Now &nbsp; is supported as a non-breaking space in lookupLens
	If grouping by alphanumeric field,  sumLens has these problems
		- a. first subtotals after first page is wrong if group name is not in uppercase already
		- b. group change not detected if occurs exactly at end-of-page.
	Added pageBreakHTML property.
	
=== 3.1.4 6 Aug 2003
	Now combo boxes support hotupdates properly, both sending and receiving. 
		Also combo popup is always reset to blank to avoid seeing double.
		Tested combo with IE 5/6, Mozilla 1.4.
	Added ability to display delete icon in edit form. Set $lens->saveOptions = 'DELETE';
	Added $lens->saveOptions = 'HIDETOPBTNS' and 'SAMEROW1COLOR'.
	Removed showNewInEdit property. Changed to use saveOptions = 'NEW'.
	Execution of applet can be deferred with $PHPLENS_DO_NOT_RUN.
	Added inputTypeLens type readonly and property roInputStyle
	Added support for MetaColumns, MetaPrimaryKeys and MetaForeignKeys in phplens_remoteq.php.
	Added sectionLens, keyColClear properties. 
		Set default of keyColClear to true, which has backward compat issues.
	Now defaultLens supports global variables.
	Added pageBreakRows property.
	
=== 3.1.3 11 July 2003
	Release to BCouncil.
	Cleaned up _sqlBind. Also made sqlBind work only with odbc_mssql and oci8.
	Searching for dates with BETWEEN for mssql did not work properly without CAST. Fixed.
	If debug is enabled, search form uses GET method for easy copy and paste.
	If debug is enabled, now lookupLens are shown too, in italics.
	Fixed bug in dynamic editing, hiding of menus did not work properly.
	Changed OS check for MS-Windows to prevent confusion with darWIN (MacOS)
	
=== 3.1.2 23 June 2003

	We now optimize odbc_mssql, using bind parameters.
	Optimizations in filtering for oci8 and odbc_mssql disabled when filterModifierFn is enabled
		to guarantee 100% compatibility...
	Do not validate blank input fields.
	showNewInEdit property (set to false|true)
	keyVariable property (varName;SQL) -- mention that keyColVariable is obsolete...
	Fixed validation of numeric fields bug introduced in 3.1.0, which caused
		setting field to read-only to fail.
	Default value of '0' not properly handled because we use empty(). Fixed.
	Better date processing in javascript - if year is not entered, we default to current year.
		We also validate for numbers between 1-31 for days, 1-12 for months.
	Added details to below grid option in showRecNo property.
	Made nameSpace first class property, which separate set of variable properties when
		using applets.
	Combo box with value/text pairs did not work. Fixed.
	Filtering an empty dataset with child new record form  caused the filter criteria form
		to disappear, with only the new rec form showing. Fixed.
	Experimental sameRowLens and border0.
	Added .cvsignore file to applet directory, to ignore templates_c directory.
	When in FILTERVIEW mode, we no longer switch to new record form when no recs found
	Added noAutoNew property, if true we do not auto-show new record form when no records found - requested by vince.
	
=== 3.1.1 May 2003
	Added $PHPLENS_REPORT_WRITER variable. Set to true to disable editing/create new record.
	ForceType in dynamic editor overwrote previous settings - fixed.
	We now quote field names in search screen.
	We also fix spNew to set unknown fields to null.
	Redirect using redirect properties attempts to use Header redirect even on windows.
	The filterModifierFn did not work properly with numeric fields. Fixed.
	Now searchLookupLens has priority over lookupLens, and it can set the
		value of a user-defined input field.
	Fixed mssql order by non-unique cols bug, when cols are numeric
	The filterLens does not work when exporting if filterLens undefined, 
		so we now automatically define it on creation of applet.
=== 3.1.0
	Added Oracle CLOB support in insert/update.
	New installer.
	Added new property searchLookupLens
		added modes: only in NEW state,  NEW to EDIT, and cancel button
		works with popups, radios and text fields. 
		does not work with checkboxes, because checkboxes do not store actual 
			data values, but array indices. changing behaviour would break compat
			with some apps.
	Allow only digits and +/-/. characters in numeric/date input fields with javascript
	We validate date/time fields, so you can only enter 1-31 for days, 1-12 for mths, etc.
	We also auto-tab date/time fields if we reach maxlength characters. 

	Combo box input type, though available since 1.2, was missing from the docs 
		and dynamic editor. Added!

	keyCompound cannot be cleared from dynamic editor - fixed.
	Generated edit/new templates are more user-friendly now.
	Added new method ResetAll() that also deselects the currently selected record (and clears
		the associated primary key value).
	Added filterTableCols property.
	The random number in the sort urls is set to a fixed length (5 chars) to ensure 
		that ab (apache bench) does not generate length errors.
	New global $PHPLENS_TABLE which holds name of phplens table. Defaults to 'phplens'.
	We now auto-hide (in IE) select tags when in dynamic editing mode, so that select tags
		do not shine thru.

	
=== 3.0.6  17 April 2003
	Added property getFieldsFromTables. When sql select statement returns no fields, then
		we get field info by listing the fields of these tables (comma-separated).
	Tested blob iamge uploads/downloads in safe mode. Added umask(0) when we save 
		a blob image into a temporary file to support safe mode.
	
=== 3.0.5  14 April 2003
	Fixed bug in scrollMaxRecordCount not appearing when only one page of records.
	Redirect() now always use the meta redirect tag for windows to workaround php/iis bug
	Fixed warning for missing timestamp posts.
	
=== 3.0.4  7 April 2003
	We recreate field objects when sqlDetail is defined. Forgot to add isNum parameter.
	We now never shorten $PHP_SELF to '' -- too many problems with powerLens and templates
	Radio buttons for input type in dyneditor did not show due to bug in 3.0.3. Fixed.
	Added groupLens vertical row-spanning if field is visible in grid.
	Scroll to end page number was not saved in session vars. Fixed.
	Testing searchLookupLens for searches in edit/new.
	PHPLensPConnect() and PHPLensConnect() now accepts $PHPLENS_DATABASE array item as 
		database parameter.
	Referer security relaxed, only checks for server address, and not web page.
	Removed assumption that thousands character was ',' when summing, we now check
		language file.
	Title for groupLens did not sort properly when clicked. Fixed.
	Child Editor did not set state back to 'NEW' when inserting new record error occured,
	 but changed it back to 'EDIT' when 'Edit and Create New Record in Details' selected. Fixed.
	
=== 3.0.3 26 March 2003
	Changed some of the navigation bar icons to more 3D look.
	Autoincrement key not passed to eventPostInsertSQL - reported by Earl. Fixed.
	Under certain conditions, saving in dynamic editor did not work... Fixed.
	Primary key in eventPostDeleteSQL was selected record, not deleted one (earl). Fixed.
	Added cancelState property. State to set when an error in creating or editing occurs.
		Defaults to  NEW (when creating) or EDIT (when editing). Should only be changed in 
		an insert or update event function  (eg. eventPreInsertSQL or eventPostUpdateSQL).
		This is a temporary property which is not auto-saved.
	Added is_uploaded_file() check when uploading blob for extra security. -- TODO - DOCUMENT
	Added -2 to eventPreInsertField - cancel and clear all input fields.
	Added another 10% speedup when sumLens enabled.
	Added another 2-3% general speedup to grid rendering - tuned formatcell and powerlens.
	Refactored field mapping code.
	Added forceType to dynamic editor.
	Now if integer/numeric type is forced to date, we assume is Unix timestamp. Note that
		it will use local timezone.
	
=== 3.0.2 18 Mar 2003

	Javascript for delete record confirmation now works with Konqueror.
	Detail grid does not appear when scrolling to end - fixed - reported earl.
	Fixes powerLens and lookupLens corruption for applets - reported jmj.
	Conditional lookups do not work properly in Filter Form - reported by earl. Fixed.
	
=== 3.0.1  17 Mar 2003

	Added detailTitleHeader and detailValueHeader for td tags of details - ** TODO DOCS
	Added PHPLensLightFonts($lens) to reduce font tags, perhaps reducing font size
		by another 5%
	Textarea sizing was incorrect. Fixed.
	ADOdb getrow() did not reset $ADODB_COUNTRECS correctly - fixed.
	Selection of primary key record did not work properly - fixed.
	JoinFields error message fixed. -- Earl
	Implemented URL shortening and we no longer generate </tr> and </td> 
		for non-NN4 browsers. This can reduce page size by 15% when in dynedit mode,
		and perhaps 10% when not.
	NN4 does not work well with #LensBM... in urlParams (scrolls to bottom), so we do
		not use it if urlParams === true.
	Reintroduced rowColorLens in all situations. (disabled in 3.0.0).
	Error msgs for %expr validation working now.
	Property groupLens did not setup SQL order by - fixed.
	Property scrollLinks for applets can now be set to 0 in dynamic editor.
	
=== 3.0.0  12 Mar 2003
	Added overlibInit, overlibLens properties. Requested ajit.
	Added htmlLens properties.
	Upgraded to Smarty 2.4.2
	Fixed misc adodb 3.30 bugs that prevent 'text' driver working.
	Export did not work if templateFilter defined.
	Added new config file, phplens.img.config.inc.php which holds path
		to temporary image/excel-export directory (imageTmpDir property), and this
		is shared with phplens-img.php, in a constant called LENS_IMAGETMPDIR
		Also this breaks LENS_IMG_TEMP_DIR
	Added tdEdit property where tdEdit = 'id=#' will result in td's with
		id=$fieldname in the edit/create record forms. -- requested Earl *** TODO DOCS
	Added new validation method, by formula "% 0 < # && # < 10" -- requested Earl          *** TODO DOCS
	Code tuning - 20% faster. And when canEdit is false and no detail grid - 30% faster 
		(we also disable rowColorLens then).
	Now if no records found, we now only temporarily set curState to NEW so the next
		refresh will show any added records - requested Earl 

==== 2.8.4
	Fixes one minor problem with templateGridHeader. RecNo alignment in header 
	does not work properly.
	
==== 2.8.3
	Added PageNo macro to topCaption also.
	
	Fixed some inconsistencies when using sizeof(sqlMap) when we should use sizeof(sqlNumMap),
	 	causing problems when 2 fields had same name!
	
	Templates with templateGrid and templateGridHeader did not work with editMultiple=true. 
		Reported by earl. Fixed.
	
	Previously templateGrid and templateGridHeader required you to define a table to store
	the grid and header in. We now check if your template data begins with <th or <td. If
	it does, we now generate the correct html to embed the cell data, without requiring
	an enclosing table. This makes aligning of the grid and header templates much much 
	easier.
	
	Session variable keyval not reset when Reset() called. Fixed.
	
	Fixed when child editor set to EDIT and CREATE when no records found, so state 
	reset to NEW (formerly was set to EDIT).
	
==== 2.8.2  6 Feb 2003

	Fixed keyRecNoSelect not defined.
	
	If scrollLinks > 0, then scroll-to-end is optimized because we have the recordcount.
	
	Added support for charsets in builder and gridbuilder with $PHPLENS_CHARSET global variable.

	Added to ADOdb the ADODB_NEVER_PERSIST constant - david sp.
	
	Change PHPLENS_LAST_YEAR and PHPLENS_FIRST_YEAR because we now support dates outside 1904-2038 range.
	
==== 2.8.1 27 Jan 2003
	Tested with Konquerer 1.3 (in order to support Apple's Safari). 
		Added support for hot-updates with Konqueror. This required change of separator from '\t' to
		a magic string ('-v@z-') because Konqueror converts '\t' to '  ' (2 spaces) in URL's.
	
	Added keyRecNoSelect, 
		0 = old behaviour 
		1 = show only exact match in details, 
		2 = show random row in details if not found
	
	Fixed rowColorLens urlParams bugs, and also redesigned hiliting to use {_HILITEROW_}
	
	We did not evaluate php code starting with '=code' in defaultLens when using
		hotupdates. Reported by JMJ. Fixed.
		
	When showFilterForm and firstState=FILTERVIEW, clicking on cancel filter did not work. Fixed.
		
==== 2.8.0  15 Jan 2003
	Added following new properties:
	
		FOR SCROLL LINKS
			scrollLinks;
			scrollTDHeader;
			scrollBgColor;
			scrollFontPrefix;
			scrollFontSuffix;
			scrollHiliteFontPrefix;
			scrollHiliteFontSuffix;
			
		FOR LAYOUT TEMPLATE
			templateLayoutAddFilter;
		
		FOR TABLE FORMATING
			filterRadioCheckBoxTD;
			editNewRadioCheckBoxTD;
			
		FOR EDITING/NEW RECORD
			editHiddenTags
			newHiddenTags
		
		Fixed 
		a. checkboxes in filter form not checked when clicking on browse arrows
		b. templates defined in dynamic editor cannot be deleted
		c. allowEmptyFilter property did not work properly when all checkbox items selected
		
		
=== 2.7.3 30 Dec 2002
	Changed emptyCharIsNull to be column-based. (document**)
	This did not work ($lens->tdLens = "*^$attributes"). Fixed.
	Added $lens->inputLens = "*^$attributes; (document **)

=== 2.7.2
	Added support for postgresql blobs (bytea fields). OID files not supported.
	Misc blob error handling problems fixed, including empty($key) we generate a random $key 
		and if no browse file selected we have better error-handling.
	Added _CAPTION_ for filtering template
	Fixed some excel export problems with groupLens enabled, or if '<' in titles 
		or field names begin/end with _
	Property emptyCharIsNull added.
	Property hideAnchorName - only works when debug is not set.
	Missing url hashes in record number added.
	Changed email regex to allow . (dot) in the userid.
	Fixed problem for field with lookupLens and htmlLens set, but html still
		escaped - fixed. Reported by brian
	
=== 2.7.1 
	Upgraded to Smarty 2.3.1
	Fixed widow handler problem in columns of radios/checkboxes
	Forgot to remove phplens.css from phplens-edit.inc.php. Done.
	Added _ID_ and _CAPTION_ to templates.
	Fixed UI problem with firstState when set to filter. Reported by Neils.
	
=== 2.7.0 3 Dec 2002
	Added some compound key support - now edit, delete, spEdit, and builders support it!
	Fixed some security issues with delete.
	Mustfill is now visible in EDIT mode also.
	Added !! prefix to powerEditLens to indicate that readonly data is not updated!
	Added noTrim property to prevent trimming of data values
	imageAttributes also supports multiple columns, eg. 'col1^width=10;^col2^height=20'; 
	inputTypeLens supports #cols, eg. 'colA^radio^3' to display 3 radio columns for field colA.
	Generate code now works with PHPLensArray 
	if isset($lens->css) and empty($lens->css) then we disable css.
	EvenHeader and oddheader work properly now.
	Added navHeader property.
	Popup settings were not sticky when searching - fixed.
	
=== 2.6.5 29 Nov 2002
	Fixed missing Column Settings when password enabled in dynamic settings.
	Added support for =% and % in powerlens, this strips off &nbsp; automatically, making it easier
		to create anchor tags, etc.
	Some small optimizations for powerLens
	Changed oci8 and mssql - when searching for dates, we search a range now from midnight to midnight,
		 instead of a point in time so it is more intuitive.
	Fixed bugs in searching dates with oci8 also.
	Fixed phplens-dynedit.inc.php to use the correct php tags
	
=== 2.6.4 21 Nov 2002
	Added \. to email regular expression before the @
	Export titles in Excel/CSV instead of field names
	PHP 4.3.0 compat fixes
	Added editTemplate, newTemplate, LayoutTemplate, GridTemplate, GridHdrTemplate and DetailTemplate
		to dynamic editor.
	
=== 2.6.3
	Added lang->filterCaption, newCaption, editCaption to phpLens settings editor.
	Cleaned up phplens-img.php code to better support rtf/pdf files.
	Fixed some validation problems in javascript when o.value and o.options is empty.
=== 2.6.2
todo:	Filter form problems - ajit - cannot duplicate
		Checkbox column arrangement when editing 	
		
	Only use bind parameters with oci8 searching if inputarr array defined. This is because
		a search with bound variables does not work properly with trimmed strings.
	Date masks did not work for AM/PM for 12:01 to 12:59. Fixed.
	When childLens new record enabled, when no record is found, new record will now be
		displayed in the child editor.
	Fixed colorLens and tdLens not being saved in editor for applets.
	Under certain conditions, image blobs did not display correctly. Fixed.
	
=== 2.6.1
	Misc SetLang() bugs fixed.
	Restored old method of setting session vars for PHP 4.0.6 compat when not using nameSpaces.
	SQL saving did not reset =sql properly. fixed.
	Default values '+' not displayed properly in dyn editor- changed to use rawurlencode now.
	When password enabled, childLens dynedit icon missing - fixed.
	Dynamic editor not reentrant with cached javascript lookups. Fixed.
	Added autoSum property.
	
=== 2.6.0
Dynamic Editing
	Changed phpLens column settings to use POST to support large SQLs.
	Auto-resize of sql field in phplens column settings based on sql length>255.
	Added nameSpace and changed session var implementation to use a session array
	Redesigned builder/grid/data.php saving - should fix all save problems
	Added "delete applet" to builder.
	Properties not properly deleted in phpLens editor when non-applet used. Fixed.
	Added tdLens to phplens settings.
	Found bug in IDE that caused &amp; to be converted to &. Added IDE back to builder...
	Changed Column Mover code to use POST instead of GET for scalability.
	
Formatting
	When in editMultiple with popup selects, we now use javascript to generate the select
		tag. This ensures that the file size is reduced as the option tags are downloaded 
		once as javascript and generated for each row on the client browser.
	Added nowrap tag to footers when summing (sumLens).
	Added integerFormat property - boolean indicating integers should be comma-delimited
	Added tdLens property
	
Searching
	New "Find More" checkbox when searching. When enabled, it sets filterAllOr property to true.
	Added betweenTxt - used to indicate ranges
	Added online help,  see top-right corner of search form.
	
Misc
	Added SetLang() method to change language file dynamically. Eg. $lens->SetLang('fr');
	The javascript property, when set to false disables all activities that require
		javascript to operate such as editMultiple generation of popups via js.
	Added pivotCategories, pivotOld and pivot.
	Made default export file name include id to make it more unique.
	Sanitize sort form parameters for security.

=== 2.5.6
Error in phplensfield - renderdetail with xmlLens did not work because incorrect number of parameters. Fixed.
Error in hot updates for new records with default values - did not replace unmatched fields with '' (empty string). Fixed.
Adding support for reporter constants
When groupLens and delete enabled, but edit disabled, actualcol calculations wrong - fixed


=== 2.5.5 
Changed oci8 char/varchar searching to use LIKE when clicking on edit/delete button because of trailing
	blanks problems
Default values not set properly for hotupdates because _joinFields not used. Fixed.
Changed sort form order to conform to showSortCols
Fixed lookupLens handling of 'col^select ...^!VIEW' creating a lookup in VIEW.
Added p1_$this->id as optional replacement to lens_p1 GET parameter
Added nameLens support for default and grid names.

=== 2.5.4	
Added sort filter form. Only available if showSortCols is set, or compat > 2.5
Added oci8 sqlBind for numeric and date fields
With oci8, char/varchar primary key did not work in 2.5.3. Fixed.

=== 2.5.3   4 Sept 2002
Introduced in 2.5.2 a bug - editing might not work in certain situations - fixed.
Removed maxlength restrictions to topCaption and bottomCaption.
Reenabled oci8 searching always uses bind now. We do not use it for saving records due
	to null problems.
filterLikeFn now has 2 new params, the values array, and the input array (for binding).

=== 2.5.2	2 Sept 2002
Added support for "%$sql", "=%$code" and "==%$code" in filterParams
Added attrDateTime property to set tag attributes for date and timestamp input fields when editing
Fixed grid and detail view did not show correctly with lookups on multiple elements stored in one field
Now search of multiple elements in one field works
New =% search operator, which is LIKE '%$str%'
Realize that some searches don't work with text db's
Problem with mysql recordsets displaying only 1 record when lookupLens used. Worked around.

=== 2.5.1
Added compat property. Default is 2.0. Set compat=2.5 if we want filterParams popups to 
	work like powerLens. - Requested ajit
Fixed hot updates (lookupLens) when we have default values, so that new record works nicely.
	- Requested jmj.

=== 2.5.0
Identical to 2.4.12

====2.4.12
Phplens.css updated to change _ to - for class selectors. Optimized jpg for CSS-Marble.
Cleaned up ListCol UI.
Fixed regex for colorLens, added 0-9 support in col names, added support for global variables
Fixed regex for chartParams, added 0-9
Fixed validation messages. Made clearer.

=== 2.4.11
Added showEditNewCaption
Reverted some color schema defaults so no CSS is used for backward compat
Able to have multiple lookupLens depending on curState. Added +VIEW and !VIEW to lookupLens.
Fixed problem when primary key is '0'.

=== 2.4.10 2 Aug 2002
Added PHPLensArray() function. 
Added {_PRIMARY_KEY_} to spEdit. This allows you to read the original primary key if the 
	 primary key value has been changed.
Changed default exportOptions to CSV as Excel appears to have problems with certain data sets.
Fixed some minor builder cosmetic errors.
Added css property and style-sheet support to phplens settings. 
	Tested on NN 4.77, 6.2.1, IE 5.5, Mozilla 1.0.
Reverted EDITSAVE back to EDIT for firstState. 
Added EDITSAVE as separate menu option

=== 2.4.9
Timestamp parsing ignored AM/PM in PHPLENSTimeStampArray. Fixed.
Security audit of number handling - added additional type safety checks when 
		editing and filtering
Number audit for very large numeric strings > 2 Gb, should fix all issues
		with the following exceptions:  charting, and lookup values for 
		checkboxes, radios, etc in filtering and edit/new record.
Display field size in all column setting pages.
Added btnsAlignLeft to align save buttons left for juris.
We null all unreferenced fields in spEdit.
Added fileSessionPath property to save session info in a file rather than in phplens table.
	Not used in applets. Eg. fileSessionPath = '/tmp'; 
	This property is smart enough to attempt reading from phplens table if file not found.

===2.4.8
Added imgTmpDirURL property. Mapping from imgTmpDir to URL. 
	eg. if imgTmpDir = '/htdocs/tmp' then imgTmpDir = '/tmp'
Added new Edit and Create Child Editor

===2.4.7
Added filter name to nameLens.

===2.4.6
We no longer quote redirect urls if javascript: is detected in url.

===2.4.5
Fixed spEdit ordering problems. Fixed spNew/spEdit missing value problems with oracle.
Now we hide errors that powerLens generated by detailLens causes, because some global vars
	are only available in grid powerLens.
We now allow allowSortCols to override blob detection (which prevents sorting on that col).
todo: Add to lookupLens docs ^last param, correct showSortCols docs, review errHideMessages docs
Added signature property
Added support for PHPLENS_LANG_DIR, where you can save language specific properties in one
	central directory for all applets. This makes switching languages much easier. The following
	are ported: topCaption, bottomCaption,nameLens,lookupLens,titleLevel1,titleLevel2,titleLevel3.
	Note that powerLens is not ported.
Strings for checkbox fields not trimmed, causing unchecked problems - fixed.
Collections table not properly updated if multiple fields were collections -fixed.
Added javascript: check in redirect for ajit.
Fixed filterreset to properly reset when firstState=filterview

===2.4.4 12 July 2002
When dynamicly configuring a column refered to by a colorLens/chartLens, 
	the colorLens/chartLens could be modified accidentally - fixed. 
Strip html tags from validation error messages that use javascript.
Made IJURIS_$id a function.
Hot updates column names did not accept digits 1-9. Reported jmj. Fixed.
Added groupDesc property for descending groupLens. Request by ajit.
We now warn users if editMultiple=true and the menus are hidden if $lens->debug>0.
If field is defined in mustFill and not in newLens, it is now ignored.

===2.4.3 9 July 2002
Fixed problems if readOnlyLens undefined
Made inputLens synonym for jsLens - please document!
Added new javascript lens_delrec() for deleting records in order to set window.event.cancelBubble.
	Also added new language field, "txtDeleteRecord"
Fixed problems when deleting widow record on last page - formerly a new record form will appear.
	Now we scroll to first record automatically.
Changed spEdit/spNew so we ignore the return value to make programming easier.

== 2.4.2
spNew and spEdit did not set undefined fields at end of POST array. Fixed. 
DefaultLens does not work when setting default value to '0' because of empty() - fixed to use strlen.
Added redirectOnInsert to support autoincrement id's as the lens_p1 GET parameter.
We display in a HTML comment the current state, so you can search in javascript in
	the browser or in IE WebControl to identify what state you are in:
		 <!-- LENS_".$this->id.'_STATE='.$this->curState." -->
This allows us to open up phpLens (in the IE Web Browser control) from VB/Delphi/VFP to edit a record 
	(set $this->curState = 'EDITSAVE') and detect when
	the record is saved by searching for the string "LENS_{$this->id}_STATE=VIEW -->" in the 
	<b>WebControl.object.document.body.innerHTML</b> property and close the VB/Delphi/VFP window.

Added constant support for LENS_$id_SQLWHERE to applet.inc.php.
Added showRecNo=4 to showGrid=false, showDetails=true.
New to phpLens 2.4.2 is the EDITSAVE state. Set firstState = 'EDITSAVE' when we want 
	to display an EDIT screen in firstState, but after we successfully save, we want switch to VIEW. 
	This works by setting firstState='EDITSAVE'.  
Also if firstState is EDIT and we click on Save and save was successful, we set curState to
	EDITSAVE. This is a state that is otherwise identical to EDIT. To maintain backward
	compatiblity, to detect EDIT state, i suggest using
	<pre> substr($this->curState,0,4) == 'EDIT'</pre>
Now in the dynamic editor, setting Edit Record for firstState sets it to EDITSAVE, and not EDIT.
PowerLens should work properly with editMultiple enabled now.
Changed internal structure of editLens and newLens for performance reasons. 
Property htmlLens was not properly saved in applet mode. Fixed.

== 2.4.1 21 June 2002
Added {nbsp} support in lookupLens
Hot updates which reference readonly cols are parsed correctly now.
Builder did not save applet changes properly because it used new id before saving - fixed.
Fixed hot updates when filtering for first time.
Magic quotes not working in filter options - fixed.
Added sqlWhere property so that you don't have to mess with sql directly to add where criteria
	(omit the word WHERE).
colorLens stopped working due to XHTML conversion from <TD to <td. Fixed.
Added to redirectOnInsert a GET parameter, lens_p1=insertedID, so you can keep track of
	the newly created record, or allow you to switch immediately to edit mode.

== 2.4.0 14 June 2002
Fixed phplens_remoteq.php fingerprint problem - the database name is not configured for first popup	
	if phplensDatabase is undefined. - reported by davids?
$lens->showRecNo = 0 did not hide details. Fixed.
Fixed bugs in LENS_IMG_TEMP_DIR support.
Added imageCacheSecs property - request by jmj - about 30% performance increase over LAN with 6 images.
Added childLens with only new editor - request by jmj. Cannot be combined with editMultiple yet.
Added property editClick to support drilldown editing - modified rowColorLens and
	added template variables {_PRIMARYTYPE_},{_EDITCLICK_} to rowColorLens
Checkboxes in search screens did not work due to previous patch for 'exact matches'- fixed.
Added support for ! in searches meaning NOT LIKE - request by Shaun
	
== 2.3.0
Fixed PHPLENSAPPLET definition bug - thanks to jmj.
Removed from builder/run.php and builder/index.php the PHPLENSAPPLET definition also.
Now we check the length and crc value of each field before we update a record in editMultiple mode.
Upgraded popcalendar xp to version 5.8 to support Mozilla 1.0. This adds 1 file: img/ipopeng.htm

== 2.2.7 
titleColor property   "ColName^ColSpan^TitleColor; "
Added support for LENS_IMG_TEMP_DIR constant in phplens.config.inc.php and this will be the 
	default for imageTmpDir property and phplens-img.inc.php.
More problems with editMultiple and readOnlyLens and powerEditLens combined - fixed.
Issues with editMultiple and _CANEDIT_ fixed.
Fixed xmlLens and editMultiple problems.
Now the spEdit/spNew/sql code autogenerated by phpLens correctly reflects mustFill, 
	and readOnlyLens  properties.
Upgraded to Smarty 2.1.1

== 2.2.6 30 May 2002
Fixed xml parsing error handling to be more generic.
Added ability to override popup calendar with own implementation with
 $lens->showCal = 'MyCalendar';

and using the following javascript (which you adapt to call your own calendar...)
 <script>
// zdoc		 is the document object
// ctrlname	 is the name of the control, starting with zdoc
// range	 normally range is set to null, but in the future, will be
//				 an array in this format [RangeBeginDate, RangeEndDate {,disabledDate}]
//    			
function MyCalendar(zdoc,ctrlname,range)
{
var od,om,oy,d

	od = eval(ctrlname+'_d');
	om = eval(ctrlname+'_m');
	oy = eval(ctrlname+'_y');
	
	// now we have 3 text objects which hold y/m/d
	//now call your calendar and set the values...

}
</script>
== 2.2.5 30 May 2002
When editMutiple set only first row readonlys are set. Other rows are read-write - fixed - reported
	by ajit.

== 2.2.4 29 May 2002
Haslindah found minor problem in core2 with generation of primary keys in urls. Fixed.

== 2.2.3 29 May 2002
Fix for multibyte chars in when in edit mode.
Fixed spEdit with editMultiple as some fields are not added to substitution list during crc check - reported by ajit.
todo: add comment about autoGenerateKey in postInsertSQL

== 2.2.1 

Patch powerEditLens to fix variable parsing problem - reported by david s.
Added new icon to filter/search form - suggested by david s.
Fixed readonly+mustfill field configured as checkbox will not work when creating new record
	- reported by david s. Fixed.
If readonly field and spEdit defined, field value when editing is corrupted.
	- reported by david s. Fixed.
Export with the filter form visible did not work - fixed.
Implemented _CANEDIT_ and _CANDELETE_ security checking. Also put in docs.
Alternative syntax for separators for defaultLens "=(\1\2)columna\2aaaa\1columnb\2bbbbb";
	eg. the separators are defined as 1 char values in =( )

== 2.2.0
Added exportLens, exportOptions properties. Default is to export all records to excel. To only 
	export current page, set exportOptions = 'CURPAGE'. To export CSV instead of excel, use
	exportOptions = 'CSV'. To change export file name, use exportOptions="NAME^export-\$DATE.xls".
	The $DATE in the file name will be replaced with the current date in Y-m-d format.
Implemented avgLens for averaging columns.
Fixed crc32 problem when having checkbox/multiple select and editMultiple = true. Reported by ajit.
New search did not reset page back to first page previously - fixed. Reported by david s.
Added gridReadOnlyLens property -ajit.
Fixed subtle bug when the search screen failed to return any records, sometimes the search screen
	was unable to redraw properly because no field info was available under some unusual conditions.
	Reported by vincent.
Added setting number of grid columns to phplens settings.
Added better XML/XHTML support in grid.
	
== 2.1.3 13 May 2002
Used empty() check for filter/search values. Fails with '0'. Changed to use strlen(). Reported by david s.
Added check when filtering for exact match for popups/checkboxes.
Removed srand() from phplens-edit.inc.php.
Type checking in phplens_remoteq.php did not work. Fixed. Reported by david s.

== 2.1.2 9 May 2002
Added $lens->lang->filterCaption. Default is &nbsp; for compat with old versions.

== 2.1.1 6 May 2002
Added additional check for invalid field names in NEW/EDIT mode.
Added exif support for getimagesize. Now if exif available, will set height and width attributes for
	img tags for blobs.
Fixed some bugs in saving applet settings.

== 2.1.0
Changed field phplens.id to char(40). This will allow support for md5 generation of id's 
	and longer id's.
Added sqlEditNew,sqlFilter,sqlDetail to generated code - request by Jose M.
PhpLens applets no longer use phplens table.
Added property applet=true/false for easier applet detection.
Fixed bug in editMultiple and lookups - reported by JMJ.
Todo: improve applet docs

== 2.0.8
	Allowed GET variables to be used in filtering, so you can define your own search criteria.
	Allow you to redefine the banned tags DEFINE.
	
== 2.0.7
	When we autogenerate code, the persist property remains sticky and is not forgotten.
	Added titleLevel1, titleLevel2, titleLevel3 properties to allow multi-level titles.
	Fixed some problems with oracle upload of blobs, and generalized phplens-img.php for windows.
	1 character was deleted from beginning of html when using htmlLens to auto-generate urls
		due to a regular expr error.
	Fixed bug when all menu items hidden, but navUserButtons is enabled, we still hide 
		the menus formerly - reported by JMJ.
	
== 2.0.6 5 April 2002
	For new records, if mustFill and readonly set for a field, lookupLens did not work 
		- fixed - reported by david sp.
	Rawurldecode validation property if prefix and suffix set to / /. This is because ^ is very
		common regular expression.
	Dates did not work properly when editMultiple is set. Fixed.
	Added crc32 check when editMultiple = true, enabling updates of only data that has changed.
	Added persist property - for connections. This defaults to false. This affects backwards compat.
	Setting javascript focus did not work properly in edit screen when spEdit set. Fixed.
	Fix doubling of dates when spEdit set.
	GuessDate() did not work properly with YYYY-m-d format. Fixed.
	
== 2.0.5
	Fixed regular expression handling of '+' in validation property. Reported by Laura.
	Applets use non-persistent connections by default now. Also fixed in gridbuilder. Reported by d spiegel.
	
== 2.0.4
	Rewrote parts of spNew and spEdit.
	Fixed editMultiple when bottomMenu hidden.
	Changed multiple column support to auto-size when pageSize >= 1000.
	
== 2.0.3
	Fixed 2 bugs reported by d spiegel
		1. spEdit/spNew stopped working with SQL
		2. when lookupLens select statement returns no records, input fields are corrupted - fixed.
	
	Removed print statement in spNew - reported by Jose M.
	
	Added warning to IDE. We will remove this feature in phpLens 2.1.
	
== 2.0.2
	Upgraded to Smarty 2.0.1. Accidentally set force_compile to true in 2.0.0. Fixed.
	
== 2.0.1
	Removed extra space in front of record number. In narrow columns, it was causing
	    wrap around to two lines.

== 2.0.0

	Added debugDie property. Will print out SQL generated by phpLens and then die. Useful
		for debugging sql queries that are taking too long and hanging the system.
		
	canNew, mustFill and readOnly settings combined did not work properly - fixed.
	
	Fixed problem with search screen popups displaying string "Array" instead of text.
	


---------------------------------------------------
OLDER CHANGES ARE ARCHIVED IN phplens-changelog.php
---------------------------------------------------
*/

/*--------------------------------------------------------------------------------------------------*/
//                                        FUNCTION DEFINITIONS
/*--------------------------------------------------------------------------------------------------*/


//---------------------------------------------------------
// Finds the DOCUMENT_ROOT - works with Apache, IIS and PWS
function PHPLENS_RootPath()
{
GLOBAL $HTTP_SERVER_VARS;

	if (isset($HTTP_SERVER_VARS['DOCUMENT_ROOT'])) { // APACHE and PWS
		$_p_file = (str_replace('\\\\','/',$HTTP_SERVER_VARS['DOCUMENT_ROOT'])); // compat for php4.02 on windows
		return (str_replace('\\','/',$_p_file));
	}
	if (isset($HTTP_SERVER_VARS['APPL_PHYSICAL_PATH'])) { // IIS
		$_p_file = (str_replace('\\\\','/',$HTTP_SERVER_VARS['APPL_PHYSICAL_PATH'])); // compat for php4.02 on windows
		return (str_replace('\\','/',$_p_file));
	}
	global $PHP_SELF; // iis cgi
 	$p = @$HTTP_SERVER_VARS['PATH_TRANSLATED'];
	if ($p) {
		$p = dirname(str_replace('\\\\','\\',$p));
		return  substr($p,0,strlen($p) - strlen(dirname($PHP_SELF)));
	}
			
	return '';
} //function

//----------------------------------------------------------------------------
// Define code for coloring rows. You should modify this if you want to color 
// based on some other criteria.
//
// onMouseOverColor	The color to display when the mouse is over a row.
//						Defaults to #FF8080, a shade of pink.
// id				The $lens->id property
// recno			The record number that you are currently processing
// isSelected		Is this record the current selected record (boolean)
// selColor			The $lens->colorSelect property
// oddColor			The $lens->colorOdd property
// evenColor		The $lens->colorEven property
// hasDetails		Details grid/editor visible
// primary			Primary key value
// primary_type		ADOdb metatype for primary key, eg. C for char, N for numeric, I for integer
// editClick		When true, clicking on a row will cause that row to be edited.
//
// The default rowColorLens is
// $lens->rowColorLens = '=LensRowColor("#FF8080",
//				{_LENSID_},{_RECNO_},{_HILITEROW_},
//				{_SELECTC_},{_ODDC_},{_EVENC_},{_HASDETAILS_},
//				{_PRIMARY_},{_PRIMARYTYPE_},{_EDITCLICK_})';
//
function LensRowColor($onMouseOverColor,$id,$recNo,$isSelected,$selColor,$oddColor,$evenColor,
	$hasDetails,$primary=false,$primary_type=false,$editClick=false)
{
GLOBAL $PHP_SELF;

	$color = ($recNo%2)? $oddColor : $evenColor;
	if (LensBrowserAgent() === 'OPERA') $js = '';
	else if($hasDetails) {
		if ($isSelected) $color = $selColor;
		$primary = urlencode($primary);
		$js =<<<DOC
 onclick="window.location='$PHP_SELF?lens_no_$id=$recNo&p=$primary#LensBM_$id'" 
 onmouseover="this.style.backgroundColor='$onMouseOverColor'" 
 onmouseout="this.style.backgroundColor=''"
DOC;
	} else {
		$js = '';
		
		if ($editClick && $primary !== false) {
			$js =<<<DOC
 onclick="window.location='$PHP_SELF?phplens_$id=e&lens_p1=$primary&rn_$id=$recNo&t=$primary_type'" 
 onmouseover="this.style.backgroundColor='$onMouseOverColor'" 
 onmouseout="this.style.backgroundColor=''"
DOC;
		}

	}
	return $color.$js;
}

/*--------------------------------------------------------------------------------------------------*/
//                                        INITIAL SETUP
/*--------------------------------------------------------------------------------------------------*/


//----------------------------------------------------------------------
// Set the PHPLENS directory - everything revolves around this directory
if (!defined('PHPLENS_DIR')) define('PHPLENS_DIR',dirname(__FILE__));

//--------------------------------------------------------------
// The following must be the first file loaded, so we do it here
include_once(PHPLENS_DIR.'/config/phplens.config.inc.php');
@include_once(PHPLENS_DIR.'/config/phplens.img.config.inc.php');

/*--------------------------------------------------------------------------------------------------*/
//                                        CONSTANT DEFINITIONS
/*--------------------------------------------------------------------------------------------------*/

//------------------------------------------------------------------------------------------------
// MD5 salt used for fingerprinting stuff - best place to define this is in phplens.config.inc.php
//   and please change this to something random and not easily guessed.
if (!defined('PHPLENS_MD5_SALT')) define('PHPLENS_MD5_SALT','MOVE THIS SALT TO PHPLENS.CONFIG.INC.PHP');

//-------------------------------------------------------------------------------
// Define constants for important subdirectories, such as the template engine dir
if (!defined('SMARTY_DIR')) define('SMARTY_DIR', PHPLENS_DIR.'/smarty/');

//------------------------
// Where we store applets 
if (!defined('APPLETS_DIR')) { // new to phplens 1.2
	define('APPLETS_DIR', PHPLENS_DIR.'/builder/applets');
	
	define('PHPLENS_MENU_COLOR','#FF9933');
	define('PHPLENS_MENUFONT_COLOR','white');
	define('PHPLENS_BKGD_COLOR','white');
	define('PHPLENS_SIDE_COLOR','#FFFFCC');
	define('PHPLENS_MENU2_COLOR','#FFCC99');
}


//---------------------------------------------------------
// This is the class used to create templates, basicly a 
// wrapper around Smarty currently. 
$PHPLensTemplateClass = 'PHPLensTemplate';


// PHPLENS table name
if (!isset($PHPLENS_TABLE)) $PHPLENS_TABLE = 'phplens';

//---------------------------------------------------
// Where the above $PHPLensTemplateClass can be found
define('PHPLensTemplateInclude',PHPLENS_DIR.'/phplens-template.inc.php');

//-------------------------------------------
// prefix for certain important GET variables
define('LENSIDPREFIX','phplens_');

//---------------------
// Error severity codes
if (!defined('LENSERROR')) {
define('LENSERROR_SEVERE',4);
define('LENSERROR',3);
define('LENSWARNING',2);
define('LENSNOTICE',1);
}

//--------------------------------------------------
// No of items before showing save and cancel at top
define('LENS_SHOW_TOP_MIN_ITEMS',6);

//------------------------------------------------------------------------------------
// normally columns displayed in Choose Grid/Detail/Edit/New Columns use sql ordering. 
// However if the number of columns exceeds this threshold, we sort alphabetically.
define('PHPLENS_SORTALPHA_COLS',25);

define('NBSP', '&nbsp;');
define('PHPLENS_MAX_ROWS',999999); // 999,999
define ('PHPLENS_MAX_PAGESIZE',9999); // 9,999

//-------------------------------------------------------------------
// Set of tags not allowed in phpLens data entry for security reasons
if (!defined('PHPLENS_BANNED_TAGS')) define('PHPLENS_BANNED_TAGS', '/<\/*((SCRIPT)|(META)|(DIV)|(APPLET)|(OBJECT)|(EMBED)|(INPUT)|(TEXTAREA)|(IFRAME)|(FRAME)|(SPAN))/i');
// Removed from banned tags: (TABLE)|(T[RDH])|

//-------------------------------------------------------------------------
// max length of phplens $id -- must match sizeof(field phplens.id in phplens table)-2
define('PHPLENS_MAX_ID_LEN',38); 

//--------------------------------------------------------------
// sets the number of fields to show if no gridLens is defined
if (empty($INIT_GRID_FIELDS )) $INIT_GRID_FIELDS = 5;


if (empty($LENS_PIVOT_SLICES)) $LENS_PIVOT_SLICES=10;

//--------------------------------------------------------
// The default <SELECT MULTIPLE> tag has a height set to
//    SIZE= sqrt(#rows)+1, or 6, whichever is higher.
// If you prefer a fixed SIZE, then define the following...
#define('LENS_MULTIPLE_SELECT_SIZE',6);


/*
Regular Expression for Email Validation

com         commercial organization
edu         educational institution
gov         government
int         international organization
mil         U.S.military
net         networking organization
org         

ICANN approved 
.info for general use, 
.biz for businesses, 
.name for individuals,
.pro for professionals, 
.museum for museums, 
.coop for business cooperatives, and
.aero for the aviation industry."
*/
if (!defined('PHPLENS_EMAIL_REGEX')) {
	define ('PHPLENS_EMAIL_REGEX',
	## based on http://developer.apple.com/internet/_javascript/validate_source.html 
	## this javascript regex is run on the browser client, it is not a PHP regex!
	'^([^ @\r\n\t\(\)\<\>\,\;\:\\\"\[\]]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,6}|[0-9]{1,3})(\]?)$'
	);
}

//-----------------
// Year Validation
define('PHPLENS_FIRST_YEAR',1900); // first legal year for data entry validation
define('PHPLENS_LAST_YEAR',2099); // last legal year for data entry validation

//--------------------------------------------------------------
// Number of characters a line should have for data entry.
// Used to calculate the number of checkboxes/radio buttons to 
// have in a line, based on the maximum length of the text label.
// So if the longest text label is 20 chars, we will fit 3 checkboxes
// into a line when LENS_INPUT_WIDTH = 64. We still limit to max of 16 items 
// per line. Note that this algorithm has a widow reducing feature
// that will reduce the number of columns used if it can, so the above
// is only 90% accurate (a widow is a dangling table cell).
$LENS_INPUT_WIDTH=64;

//----------------------------------------------------------------------
// Multiuser warning timer in secs. If different client edits browser
// screen in last 5 minutes, we warn user. This is not available for applets
define('LENS_MULTIEDIT_TIMER',300);

//--------------------------------------------------------------
// required for compatibility with older code that uses phpLens 
function PHPLENS_FixYear($y)
{
	return adodb_year_digit_check($y);
}
/*--------------------------------------------------------------------------------------------------*/
//                                       LOAD CORE LIBRARIES
/*--------------------------------------------------------------------------------------------------*/

require_once(PHPLENS_DIR.'/phplens-main.inc.php');


?>