RUSSYSDEV: eiseIntra
Instant administrative backend for your application

eiseIntra core

Authentication, form elements display, data handling routines

Package: eiseIntra
Version: 2.0beta

class eiseIntra

eiseIntra is the core class that encapsulates routines for authenication, form elements display, data handling, redirection and debug.

This class extends eiseIntraData as base class.

public function __construct($oSQL = null, $conf = Array())

Constructor receives eiseSQL object with database connection as input parameter and performs object initialization with configuration options supplied in $conf array.

Category: Authentication Initialization

Parameters:

  • $oSQL (eiseSQL) - MySQL connection object.
  • $conf (array) - associative array with configuration options. Defaults are:
    • ‘dateFormat’ - date format, default is “d.m.Y”
    • ‘timeFormat’ - time format, default is “H:i” (24-hours time), both are according to PHP date() format function
    • ‘decimalPlaces’ - default decimal places, “2” by default
    • ‘decimalSeparator’ - decimal seprator, default is “.”
    • ‘thousandsSeparator’ - default is “,”
    • ‘language’ - local language, default is ‘rus’
    • ‘logofftimeout’ - log off timeout in minutes, default is 360 //6 hours
    • ‘addEiseIntraValueClass’ - setting for for display true
    • ‘keyboards’ - available keyboard variations (default are ‘EN,RU’)
    • ‘system’ - eiseIntra path, last slash stripped (default is ltrim(dirname($_SERVER['PHP_SELF']), '/')
    • ‘dataActionKey’ - ‘DataAction’, GET or POST key for data update or retrieval
    • ‘dataReadKey’ - ‘DataAction’, GET or POST key for data update or retrieval
    • ‘flagSetGlobalCookieOnRedirect’ - see eiseIntra::getCookiePath() function for details, default is false
    • ‘cookiePath’ - (isset($eiseIntraCookiePath) ? $eiseIntraCookiePath : '/')
    • ‘cookieExpire’ - see eiseIntra::getCookiePath() function for details
    • ‘UserMessageCookieName’ - for cookie used to store user messages, default is ‘eiMsg’

public function decodeAuthString($authstring)

Function decodes authstring login:password using current encoding algorithm (now base64).

Category: Authentication

Parameters:

  • $authstring (string) - Encoded string

Returns: array [string $login, string $password]

public function encodeAuthString($login, $password)

Function encodes authstring login:password using current encoding algorithm (now base64).

Category: Authentication

Parameters:

  • $login (string) - Login
  • $password (string) - Password

Returns: string Encoded authentication string.

public function Authenticate($login, $password, $method=”LDAP”, $options=array())

Function that checks authentication with credentials database using selected $method. Now it supports the following methods:

  1. LDAP - it checks credentials with specified GLOBAL $ldap_server with GLOBAL $ldap_domain
  2. database (or DB) - it checks credentials with database table stbl_user
  3. mysql - it checks credentials of MySQL database user supplied with $login and $password parameters. Together with authentication this Function returns true when authentication successfull, otherwise it returns false and $strError parameter variable becomes updated with authentication error message.

LDAP method was successfully tested with Active Directory on Windows 2000, 2003, 2008, 2008R2 servers.

Category: Authentication

Parameters:

  • $login (string) - login name
  • $password (string) - password
  • $method (string) - authentication method. Can be ‘LDAP’, ‘database’(equal to ‘DB’), ‘mysql’
  • $options (array) - Array
    • ‘flagNoSession’ (boolean) - Use true when you need one-time authentication without $_SESSION modification.
    • ‘dbhost’ (string) - Database host, used only with ‘mysql’ authentication method.
    • ‘dbname’ (string) - Database name. Default database to be selected with ‘mysql’ authentication method.

Returns: boolean authentication result: true on success, otherwise false.

public function session_initialize()

This function intialize session with session cookes placed at path set by $this->conf[‘cookiePath’] configuration variable.

Category: Authentication

public function logout()

This function quits user session.

Category: Authentication

public function checkPermissions()

This function checks current user’s permissions on currently open script. Also it checks session expiration time, and condition when user is blocked or not in the database. Script name is obtained from $_SERVER['SCRIPT_NAME'] global variable. Permission information is collected from stbl_page_role table and calculated according to user role membership defined at stbl_role_user table. Permissions are calulated in the following way:

  • if at least one user’s role is permitted to do something, it means that this user is permitted to to it.

If user has no permissions to ‘Read’ the script, function throws header Location: login.php and stops the script. When ‘Read’ permissions are confirmed for the user, function updates $intra->arrUsrData property. Click on this link to see full description.

NOTE: Role membership information is collected from stbl_role_user table basing on rluInsertDate timestamp, it should not be in the future. It is useful when some actions should be temporarily delegated to the other user in case of vacations, illness etc.

Page permissions can be set with eiseAdmin’s GUI at < database >/Pages menu. Role membership can be set by system’s GUI at system’s Setting/Access Control menu or /Roles menu of eiseAdmin.

Category: Authentication Authorization

Returns: array $intra->arrUsrData

public function topLevelMenu($arrItems = array(), $options = array())

This method returns content of top-level “jumper” menu as drop-down list. “Jumper” menu content goes with an associative array passed as parameter to this function.

Category: Navigation

public function menu($target = null)

This method returns system menu <ul> HTML for menu structure.

Category: Navigation

Parameters:

  • $target (string) - base target for all <a href="..."> inside menu

Returns: string HTML with menu structure

public function actionMenu($arrActions = array(), $flagShowLink=false)

This method returns HTML for “action menu” - the menu that displayed above the functional part of the screen. Menu content is set by $arrActions parameter, the set of associative arrays with menu items. Menu item definition array consists of the following properties: array[] - menu item set. No nested menu items, no dropdowns in this version.

  • ‘title’ (string) - Menu item title
  • ‘action’ (string) - Menu item HREF attribute content. If it starts with ‘javascript:’ JS call will be encapsulated under ONCLICK attribute.
  • ‘targer’ (string) - (optional) TARGET attribute content
  • ‘class’ (string) - (optional) CLASS attribute content All these attributes are related to A element that correspond to given menu item.

Category: Navigation

Parameters:

  • $arrActions (array) - (See above)
  • $flagShowLink (boolean) - The flag that defines is there a need to show ‘Link’ menu element on the right, in case when page opened within a frame. FALSE by default.

Returns: string HTML for “action menu”.

public function requireComponent($components)

This method includes specified $components into your PHP code by calling corresponding include() PHP functions and filling out $arrJS and $arrCSS arrays.

Category: Initialization

Parameters:

  • $components (variant) - Array or string with eiseIntra’s component name. Name set can be the following:
    • base - core components, they’re included by default
    • batch - JavaScripts necessary to run batches
    • list - eiseList
    • grid - eiseGrid
    • actions - entity flow routines

public function redirect($strMessage, $strLocation, $arrConfig = array())

This method adds HTTP header “Location” that redirects user to URL/URI specified in $strLocation, with text message to be shown on this page, specified in $strMessage parameter.

Message will be shown on eiseIntra enabled page, using $('body').eiseIntra('showMessage') function that will fire right after $('window').load() event.

Message will be saved for display using cookies. By default cookie path is the path part of $strLocation URL. If $intra->conf[‘flagSetGlobalCookieOnRedirect’] is TRUE, cookie path will be set by global constant $this->conf[‘cookiePath’].

This property can be overriden for this function with the $arrConfig[] parameter member ‘flagSetGlobalCookieOnRedirect’ = TRUE/FALSE. It can be useful when you need to redirect user from project subdirectory to the script placed at the root one, for example:

$intra->redirect('Operation successfull', '/myproject/item_form.php?itemID=12345'); 
// normal redirect within the project
$intra->redirect('Bye-bye, see you later', '/byebye.php', array('flagSetGlobalCookieOnRedirect'=>true)); 
// when $this->conf['cookiePath']='/' and you redirect user to the root dir of your web server.

Category: Navigation

Parameters:

  • $strMessage (string) - Message content.
  • $strLocation (string) - header(‘Location: {}’) parameter
  • $arrConfig (array) - Array with one usable boolean property: flagSetGlobalCookieOnRedirect. See above.

Returns: nothing, script execution terminates.

public function backref($urlIfNoReferer)

This method returns proper ‘Back’ reference for this button in Action Menu. If $_SERVER[‘HTTP_REFERER’] doesn’t contain current URI, it set a cookie with referring page.

Otherwise, it use this cookie value, and if it’s absent, it returns $urlIfNoReferer parameter.

It works like this: when user arrives to given form via hyperlink in list or other form, or whatever that leaves HTTP_REFERER header, it returns this value and saves a cookie with that URL, with this form path. When user saves data on this form it appears back without this HTTP header and ‘Back’ button needs proper value. It takes it from cookie (if it exists) or from specified parameter.

$arrActions[] = array('title'=>'Back', 'action'=>$intra->backref('myitems_list.php')); 
// it will return user to the item list by default

Category: Navigation

Parameters:

  • $urlIfNoReferer (string) - URL(URI) for ‘Back’ reference in case when there’s no $_SERVER[‘HTTP_REFERER’] or $_SERVER[‘HTTP_REFERER’] leads from itself.

Returns: string URL

public function json($status, $message, $data=null)

Function outputs JSON-encoded response basing on intra specification and terminates the script.

Category: Data output

Parameters:

  • $status (string) - response status. ‘ok’ should be set in case of successfull execution
  • $message (string) - status message to be displayed to the user
  • $data (varian) - data to be transmitted

public function batchStart()

This function outputs necessary stuff to start batch data operation script.

Category: Output Batch run

public function batchEcho($string)

This function outputs data at batch data operation script, adds htmlspecialchars() and flushes output buffer.

Category: Data output Batch run

public function getUserMessage()

This function retrieves user message from the cookie and deletes the cookie itself.

Returns: string with user message

public function getRoleUsers($rolID)

This method returns array of role users by role ID

Category: Authentication Authorization

Parameters:

  • $rolID (int) - role ID Returns: array of user ID’s

public function checkLanguage()

This function initialize what language to use: local or global

Category: Initialization i18n

public function translate($key)

An analog of industrial standard __() function, $intra->translate() translates simple words/phrases to local language according to the system dictionary oridinarily located in < sys dir >/common/lang.php and included at auth.php. Now it supports sprintf() formatting, so it can translate phrases with format strings like “Item #%s is updated.”

Category: i18n

public function addTranslationKey($key)

This is service method that turns on translation key collection for further dictionary fill in (lang.php)

Category: i18n

public function readSettings()

This function reads stbl_setup table into $intra->conf[] array.

Category: Initialization

public function field( $title, $name=null, $value=null, $conf=array() )

This function returns HTML for single field If parameter $title is specified, it returns full HTML with container, label and input/text If parameter $name is specified it returns HTML for input/text according to $value parameter else it returns HTML specified in $value parameter.

Category: Forms

public function fieldset($legend=null, $fields=’’, $conf = array())

This function returns HTML for single fieldset

Category: Forms

Parameters:

  • $legend (string) - contents of <legend> tag
  • $fields (HTML) - HTML with fields
  • $conf (array) - array with configuration data, with following possible members:
    • id - contents of ‘id’ attribute of <fieldset> tag
    • class - contents of ‘class’ attribute of <fieldset> tag
    • attr - string of extra attributes to be added to <fieldset> tag
    • attr_legend - string of extra attributes to be added to <fieldset><legend> tag

public function form($action, $dataAction, $fields, $method=’POST’, $conf=array())

This function returns HTML for the form.

Category: Forms

Parameters:

  • $action (string) - Stands for ACTION attribute of FORM tag
  • $dataAction (string) - value of DataAction form input
  • $fields (HTML) - form inner HTML
  • $method (string) - METHOD attribute of form tag
  • $conf (array) - form configuration data array, contains the following possible members:
    • class - contents of CLASS attribute of FORM tag, all listed classes will be added to default class list (eiseIntraForm eif-form) on the right
    • attr - extra attributes to be added to FORM element
    • id - contents of ID attribute of FORM element
    • flagDontClose - if set to TRUE, <FORM> tag is not closed in function output.

public function showTextBox($strName, $strValue, $arrConfig=Array())

This function returns HTML for the text box <input type="text">.

Category: Forms

public function showTextArea($strName, $strValue, $arrConfig=Array())

This function returns HTML for the <textarea>.

Category: Forms

public function showButton($name, $value, $arrConfig=array())

showButton() method returns <input type="submit"> or <button> HTML. Input type should be specified in $arrConfig['type'] member.

Category: Forms

Parameters:

  • $strName (string) - button name and id, can be empty or null
  • $strValue (string) - button label
  • $arrConfing (array) - configuration array. The same as for any other form elements. Supported input types ($arrConfig[‘type’] values) are:
    • submit - <input type="submit" class="eiseIntraActionSubmit"> will be returned
    • delete - method will return <button class="eiseIntraDelete">
    • button (default) - <button> element will be returned Returns: HTML string

public function showCombo($strName, $strValue, $arrOptions, $confOptions=Array())

This method returns HTML for <select> form control. Element id and name are set with $strName parameter. Selected element will be chosen accorging to $strValue. Option values and this variable will be converted being casted to strings. Empty element (with empty value) will be added if $confOptions[‘defaultText’] option is set. $arrOptions array can have nested arrays. In this case <optgroup> tag will be added. Option group title can be set via $confOptions[‘optgroups’] option array. See below. $confOptions is configuration array, it can have the following options:

  • FlagWrite (boolean) If true, usable <select> element will be shown. Otherwise, it will be <div> with chosen option text and hidden <input> with existing value.
  • class (string) contents of <select class="{...}"> attribute. Specified classes will be added to the end of class list.
  • strAttrib (string) Additional <select> element attributes string, e.g. ` data-xx=”YY” aria-role=”nav” class=”my-gorgeous-class”`. Classes will be merged with ‘class’ option content.
  • required (boolean) If TRUE, ‘required’ HTML attribute will be added for form validation.
  • defaultText (string) If specified, <option> with empty value will be added to the beginning of dropdown list, option text will be taken from this conf option value. If ‘auto_translate’ $intra option is TRUE, this value will be translated.
  • deletedOptions (array) Array of option values to be marked as deleted with <option class="deleted">
  • optgroups (array) Array of <optgroup> titles. If $arrOption array member is array, it will search for <optgroup> tag title in this conf option array by the same key.
  • indent (array) Array of integer values for options text indent.
  • href (string) If you’d like to show hyperlink when combobox is read-only, this option value will be used as <a href="{...}">
  • target (string) HREF target.

Category: Forms

Parameters:

  • $strName (string) - Input name and id
  • $strValue (string) - Field falue
  • $arrOptions (array) - Options array where key is <option value=""> and array element value is option text
  • $arrOptions (variant) - (optional) Array with configuration options for <select> element. See above.

Returns: string HTML

public function showCheckBox($strName, $strValue, $arrConfig=Array())

This function returns HTML for the < input type=”checkbox” >.

Category: Forms

public function showRadio($strName, $strValue, $arrConfig=Array())

This function returns HTML for the < input type=”radio” >.

Category: Forms

public function showRadioByArray($strRadioName, $strValue, $arrConfig)

This function returns HTML for the < input type=”radio” >, basing on arrays

Category: Forms

public function showAjaxDropdown($strFieldName, $strValue, $arrConfig)

This function returns HTML for the AJAX-based autocomplete inputs. They download data from the server while user inputs the text.

Category: Forms

public function isEditable($flagToForce = null)

This method returns True if user permissions allow to edit the data. It is possible either if FlagWrite is positive at current page or FlagCreate or FlagUpdate are too. Perissions may be forced to allow editing or deny it by setting $flagToForce parameter to True or Flase correspondingly. If it’s not set or null it meaningless.

Category: Forms

Parameters:

  • $flagToForce (bool) - Flag to force permissions.

Returns: bool

public function loadJS()

Function that loads JavaScript files basing on GLOBAL $arrJS

Category: Initialization

public function loadCSS()

Function that loads CSS files basing on GLOBAL $arrCSS

Category: Initialization

public function dataAction($dataAction, $funcOrObj=null)

Data handling hook function. If $_GET or $_POST [‘DataAction’] array member fits contents of $dataAction parameter that can be array or string, user function $function_name will be called and contents of $_POST or $_GET will be passed as parameters.

Category: Navigation Data handling

Parameters:

  • $dataAction (variant) - string or array of possible values that $function should handle.
  • $funcOrObj (variant) - callback function name or object which method should be invoked. Function should get $_POST or $_GET as first parameter.

Returns: variant value that return user function.

public function dataRead($dataReadValues, $function)

Data read hook function. If $query[‘DataAction’] array member fits contents of $dataReadValues parameter that can be array or string, user function $function_name will be called and contents of $query parameter will be passed. If $query parameter is omitted, function will take $_GET global array.

Category: Navigation Data output

Parameters:

  • $dataReadValues (variant) - string or array of possible values that $function should handle.
  • $function (string) - callback function name.
  • $query (array) - associative array data query

Returns: variant value that return user function.

static function confVariations($conf, $variations)

Static functions that returns first occurence of configuration array $conf key variations passed as $variations parameter (array). Made for backward compatibility.

Category: Utilities

Parameters:

  • $conf associative (configuration) array
  • $variations enumerated array of variations

Returns: $conf array value of first occurence of supplied key variations. NULL if key not found

static function getFullHREF($iframeHREF)

This function returns external reference to the script inside <iframe>. This href will load all iframe surrounding, including menu and $iframeHREF will be inside this <iframe>

Parameters:

  • $iframeHREF (string) - URL of the page inside the <iframe>

static function getKeyboardVariations($src)

function to obtain keyboard layout variations when user searches something but miss keyboard layout switch

It takes multibyte UTF-8-encoded string as the parameter, then it searches variations in static property self::$arrKeyboard and returns it as associative array.

Category: i18n Useful stuff

Parameters:

  • $src (string) - Original user input

Returns: array Associative array of possible string variations, like array('EN'=>'qwe', 'RU'=>'йцу')

static function buildLess()

This function rebuilds style.css for selected theme using style.less located in the same folder as style.css. REMEMBER TO chmod a+w to this folder!

Category: Utilities

static function debug($to_echo)

This function dumps $to_echo variable using var_export() or simply echoes it, with stack trace ahead

Category: Debug

Parameters:

  • $to_echo (variant) - variables to dump
  • $flagStackTrace (boolean) - if last parameter set to TRUE, function adds stack trace

private function getCookiePath($strLocation, $arrConfig = array())

This function returns cookie path for given location. In case when flagSetGlobalCookieOnRedirect it returns $this->conf[‘cookiePath’] constant. Otherwise it returns path part of location URL.

Category: Initialization

Parameters:

  • $strLocation (string) - header(‘Location: {}’) parameter
  • $arrConfig (array) - Array with one usable boolean property: flagSetGlobalCookieOnRedirect. See above.

Returns: string A cookie path.

public variable $arrUsrData

Array with data of currently logged user:

  • all user data from stbl_user table:
    • usrID - user ID
    • usrName - user name
    • usrNameLocal - user name in local language
    • usrPass - user password (password hash)
    • usrFlagDeleted - is user account deleted or not
    • usrPhone - user’s office phone
    • usrEmail - user’s email address
    • usrEmployeeID - employee table’s ID
    • usrGUID - user GUID
    • usrCN - canonical name of the user
    • usrMobile - user’s mobile phone
    • usrInsertBy - user ID who added the user
    • usrInsertDate - when user was added
    • usrEditBy - user ID who changed the user
    • usrEditDate - when user record was changed
  • pagID - database page ID
  • pagTitle (string) - page title in English
  • pagTitleLocal (string) - page title in local language
  • FlagRead (string*) - always ‘1’
  • FlagCreate (string*) - ‘0’ or ‘1’, as set in database
  • FlagUpdate (string*) - ‘0’ or ‘1’, as set in database
  • FlagDelete (string*) - ‘0’ or ‘1’, as set in database
  • FlagWrite (string*) - ‘0’ or ‘1’, as set in database
  • array roles - array of role titles in currently selected language. Example: ['Managers', 'Users']
  • array roleIDs - array of role IDs. Example: ['MNG', 'USR']

(*) - type is ‘string’ because of PHP function mysql_fetch_assoc()’s nature. It fetches anything like strings despite actual data type in the database.

For more details on how and when this data is obtained, please proceed to eiseIntra::checkPermissions().

Category: Authentication

public variable $usrID

ID of current user.

Category: Authentication

class eiseIntraData

eiseIntraData is the class that encapsulates data handling routines

Data types definition and conversion SQL <-> PHP output data conversions SQL query result conversion to JSON or Array (result2JSON()) Reference table routines (getDataFromCommonViews()) Archive/Restore routines etc

Package: eiseIntra
Version: 2.0beta

public function formatByType2PHP($type, $value, $decPlaces = null)

This function formats data for user-friendly output according to user data type provided in $type parameter.

Category: Data formatting

Parameters:

  • $type (string) - data type, according to eiseIntra::$arrUserDataType
  • $value (variant) - data as it’s been returned from the database or calculated in PHP
  • $decPlaces (int) - number of decimal places

Returns: string

public function formatByType2SQL($type, $value, &$thisType = ‘‘)

This function formats data to SQL-query friendly value, not escaped, without quotes.

Category: Data formatting

Parameters:

  • $type (string) - any data type supperted by SQL server
  • $value (variant) - value to be formatted
  • $thisType (string) - detected eiseIntra data type from $arrIntraDataTypes, this parameter is set by ref.

Returns: string - The value formatted.

public function result2JSON($rs, $arrConf = array())

This function returns SQL result as JSON string or array, in format that can be understood by eiseIntra’s JavaScript fill() methods. Output format is a bit more complex than just list of rows as dictionaries. It also contains some features that scipt interpret for data display:

  • read/write permissions for given field in given tuple
  • text representation for field if it’s foregn key value with reference to some disctionary
  • HREF for a field, if any. For example, we have a following result: [{a: b, c: d, e: f, e_text: f_text}, {a: b1, c: d1, e: f1, e_text: f_text1}]. In the simiplest case, by default, it will be formatted in the following way: [{a: {v: b }, c: {v: d}, e: {v: f, t: f_text} }, {a: {v: b1 },{c: {v: d1}}, e: {v: f1, t: f_text1} }] - as you can see data value is places under “v” key, and text represntation that originally comes with “_text” suffix is placed under “t” key for field “e”. More through output cofiguration can be set with $arrConf parameter of this function.

Category: Data read

Parameters:

  • $rs (resource) - SQL server resource handle
  • $arrConf (array) - confiration array. Here is detailed description of each feature:
    • ‘flagAllowDeny’ (string) - when set to ‘deny’, ‘arrPermittedFields’ contains only editable fields, and vice-versa when it’s set to ‘allow’ (default)
    • ‘arrPermittedFields’ (array) - this function can add ‘rw’ property with values ‘rw’ or ‘r’ property for each field in a record and it will force JavaScript function fill() to make correcspoding fields editable or not. If this array is empty and ‘flagAllowDeny’ is set to ‘allow’ this property is omitted. For example, if $arrConf['arrPermittedFields'] == ['c'] and $arrConf['flagAllowDeny'] == 'allow' ‘c’ field will be prenected in the following way: {c: {v: ‘d’, rw: ‘r’}}.
    • ‘fields’ (array) - the array with fields configuration data. Developer can customize output of decimal fields by setting ‘decimalPlaces’ or ‘minDecimalPlaces’ values. Also user can specify href ‘href’ asnd its ‘target’ for this fields. HREFs can be formed dynamically with data from the same record. To proceed with is you need to specify field name in square brackets. Example: if $arrConf['fields']['c']['href'] == '/page.php?a=[a]' and $arrConf['fields']['c']['target'] == '_blank' it will return {c: {v: d, h: '/page.php?a=b', tr: '_blank'}}
    • ‘flagEncode’ (boolean) - When true, function returns JSON-encoded string, otherwise it returns an array.

Returns: array (default) or string when $arrConf[‘flagEncode’]==True

public function unq($sqlReadyValue)

This function unquotes SQL value previously prepared to be added into SQL code by functions like $oSQL->e(). Same exists in eiseSQL class.

Category: Data formatting

Parameters:

  • $sqlReadyValue (string) -

Returns: string $sqlReadyValue without quotes, or NULL if source string is ‘NULL’ (case-insensitive)

public function decPHP2SQL($val, $valueIfNull=null)

This function converts decimal value from user input locale into SQL-friendly value. If $val is empty string it returns $valueIfNull string or ‘NULL’ string.

Category: Data formatting

Parameters:

  • $val (string) - user data.

Returns: variant - double value converted from original one or $valueIfNull if it’s set or ‘NULL’ string otherwise.

public function decSQL2PHP($val, $decimalPlaces=null)

This function converts data fetched from SQL query to string, according to $intra locale settings.

Category: Data formatting

Parameters:

  • $val (variant) - Can be either integer, double or string (anyway it will be converted to ‘double’) as it’s been obtained from SQL or calculated in PHP.
  • $decimalPlaces (integer) - if not set, $intra->conf[‘decimalPlaces’] value will be used.

Returns: string decimal value.

public function dateSQL2PHP($dtVar, $precision=’date’)

This function converts date value as it’s been fetched from SQL (‘YYYY-MM-DD’ or any strtotime()-parseable format) into string accoring to $intra locale settings ($intra->conf[‘dateFormat’] and $intra->conf[‘timeFormat’]). If $precision is not ‘date’ (e.g. ‘time’ or ‘datetime’) it will also adds a time component.

Category: Data formatting

Parameters:

  • $dtVar (string) - Date/time value to be converted
  • $precision (string) - precision for date conversion, ‘date’ is default.

Returns: string - converted date or date/time value

public function datetimeSQL2PHP($dtVar)

This function converts date value as it’s been fetched from SQL (‘YYYY-MM-DD’ or any strtotime()-parseable format) into string accoring to $intra locale settings ($intra->conf[‘dateFormat’] and $intra->conf[‘timeFormat’]).

Category: Data formatting

Parameters:

  • $dtVar (string) - Date/time value to be converted

Returns: string - converted date/time value

public function datePHP2SQL($dtVar, $valueIfEmpty=”NULL”)

This function converts date value received from user input into SQL-friendly value, quoted with single quotes. If origin value is empty string it returns $valueIfEmpty parameter or ‘NULL’ if it’s not set. Origin value is checked for compliance to date format using regular expression $intra->conf[‘prgDate’]. Also $dtVar format accepts output formatted as ‘YYYY-MM-DD’ string. If $dtVar format is wrong it returns $valueIfEmpty or ‘NULL’ string.

Category: Data formatting

Parameters:

  • $dtVar (string) - origin date value
  • $valueIfEmpty (variant) - value to be returned if $dtVar is empty or badly formatted.

Returns: string - Converted value ready to be added to SQL query string.

public function datetimePHP2SQL($dtVar, $valueIfEmpty=”NULL”)

This function converts date/time value received from user input into SQL-friendly string, quoted with single quotes. If origin value is empty string it returns $valueIfEmpty parameter or ‘NULL’ if it’s not set. Origin value is checked for compliance to date format using regular expression $intra->conf[‘prgDate’] and $intra->conf[‘prgTime’]. Time part is optional. Function also accepts ‘YYYY-MM-DD[ HH:MM:SS]’ string. If $dtVar format is wrong it returns $valueIfEmpty or ‘NULL’ string.

Category: Data formatting

Parameters:

  • $dtVar (string) - origin date value
  • $valueIfEmpty (variant) - value to be returned if $dtVar is empty or badly formatted.

Returns: string - Converted value ready to be added to SQL query string.

public function getTableInfo($dbName, $tblName)

getTableInfo() funiction retrieves useful MySQL table information: in addition to MySQL’s ‘SHOW FULL COLUMNS …’ and ‘SHOW KEYS FROM …’ it also returns some PHP code that could be added to URL string, SQL queries or evaluated. See description below. Currently it uses eiseSQL::getTableInfo() function.

Parameters:

  • $dbName (string) - database name
  • $tblName (string) - table name

Returns: array - see more in eiseSQL::getTableInfo() function documentation

public function getSQLValue($col, $flagForArray=false)

getSQLValue() function returns ready-to-eval PHP code to be used in SQL queries. Currently kept for backward compatibility.

Category: Data formatting

Parameters:

  • $col (array) - array in the same format as it’s been received from eiseSQL::getTableInfo() function. ‘Field’ member is obilgatory.
  • $flagForArray (boolean) - when set to true, it uses not $_POST[$col[‘Field’]] but $_POST[$col[‘Field’]][$i]. It is useful when we need to dispatch data list.

Returns: string PHP code that could be evaluated in SQL query.

public function getMultiPKCondition($arrPK, $strValue)

This tiny function composes WHERE SQL condition for multiple column primary key. It’s assumed that column values are delimited with double-hash (‘##’).

Category: Database routines

Parameters:

  • $arrPK (array) - Primary key array, as returned by eiseSQL::getTableInfo() function, in ‘PK’ array member.
  • $strValue (string) - double key value

public function getDataFromCommonViews($strValue, $strText, $strTable, $strPrefix, $flagShowDeleted=false, $extra=’’, $flagNoLimits=false)

This function reads data from SQL views or tables that’s used as foreign key references. This function is widely used in eiseIntra as the data source for

Category: Data read

Parameters:

  • $strValue (string) - value to search for; when it’s specified, the function searches for records by primary key.
  • $strText (string) - text to search for - when we try to find match by text with LIKE %..%, e.g. for AJAX autocomplete list.
  • $strTable (string) - table or view name
  • $strPrefix (string) - 3-4-letters table field prefix. When set, it expects $strTable to have columns named as ID, Title, TitleLocal and FlagDeleted. When this parameter is empty, it expects this view to have 'optValue', 'optText', 'optTextLocal' and 'optFlagDeleted' columns. Otherwise it throws an exception from MySQL side.
  • $flagShowDeleted (boolean) - when true, values are not filtered with ‘*FlagDeleted=0’
  • $extra (string) - some extra criteria, pipe(‘ ’)-delimited string. Table/view should contain fields named like ‘extra’, ‘extra1’, ‘extra2’…
  • $flagNoLimits (boolean) - when false, it returns only first 30 matching records. Otherwise it reutrns all matched records.

Returns: resource with data obtained from the database

static function getBasicDataType($type)

This function returns basic data type for provided $type variable. It can be as any MySQL data type as input type used in eiseIntra.

Parameters:

  • $type (string) - input type parameter, e.g. ‘select’ or ‘money’

Returns: string - basic type from keys of eiseIntraData::$arrBasicTypes. If basic type’s not found it returns ‘text’.

static function getIntraDataType($type, $field = ‘‘)

This function returns Intra type from key set of $arrIntraDataTypes array above. It takes $type and $field name as parameters, and it can be as Intra types as SQL data types returned by fetch_fields() or getTableInfo() functions.

static function getDecimalPlaces($val, $minPlaces = 0)

eiseIntra::getDecimalPlaces() gets actual number of digits beyond decimal separator. It reads original float or string value with “.” (period symbol) as delimiter and returns actual number of decimal places skipping end zeros.

Category: Data formatting

Parameters:

  • or (string) - float $val - origin number

Returns: int - number of decimals. If $val is not numberic (i.e. it doesn’t fit is_numeric() PHP function) it returns NULL.

static variable $arrIntraDataTypes

$arrIntraDataTypes defines basic type set that is used for conversion of data obtained from the database into user-specific locale.

class eiseSQL

eiseSQL is the class for object wrapper for database access functions. Currently it extends PHP’s built-in mysqli class but also it adds some useful shortcuts for most popular functions. Also in contains built-in profiler and some functions to profile your SQL query sequence.

Package: eiseIntra
Version: 2.0beta

public function __construct ($dbhost, $dbuser, $dbpass, $dbname, $flagPersistent=false)

Performs connect to the database with parent constructor.

WARNING! method connect() only make some adjustments

Throws: eiseSQLException object when connect fails
Category: Database routines

Parameters:

  • $dbhost (string) - hostname/ip
  • $dbuser (string) - database user
  • $dbpass (string) - password
  • $dbname (string) - database name to use
  • $flagPersistent (boolean) - when true, PHP tries to establish permanent connection

public function connect($host = NULL, $user = NULL, $password = NULL, $database = NULL, $port = NULL, $socket = NULL)

Dummy. Needed for some backward compatibility. Do not use.

public function selectDB($dbname=’‘)

Another backward-compatibility function Do not use.

public function e($str, $usage=”for_ins_upd”)

Method e() escapes source string for SQL query using mysql_escape_string() and put escaped string into single quotes. Please used it to prevent from SQL injections.

Category: Database routines Data formatting

Parameters:

  • $str (string) - string to be escaped
  • $usage (string) - (optional) - if set to something different from ‘for_ins_upd’, source string will be escaped for double-sided LIKE, e.g. echo $oSQL->('qq', 'search')=>LIKE '%qq%'

public function unq($sqlReadyValue)

This function strips single quotes from both ends of the string. If string is word ‘NULL’, it returns NULL.

Parameters:

  • $sqlReadyValue (string) - value to be “unquoted”

Returns: string

public function secure($arg)

This function first quotes the string using eiseSQL::e() function, then it strips quotes with eiseSQL::unq(). So it secures the string from any SQL injection.

Category: Database routines Data formatting

Parameters:

  • $arg (string) - value to be “secured”

Returns: string

public function q($query)

This method executes SQL query and returns MySQL resource. Also it collects all necessary data for query profile:

  • query text
  • execution time
  • number of records affected
  • number of records returned
  • call stack

Category: Database routines Useful stuff

Returns: MySQL resource

public function n($mysqli_result)

This method returns number of rows obtained within MySQL result object. Actually it returns $mysqli_result->num_rows property.

Category: Database routines

Parameters:

  • $mysqli_result (object) -

Returns: int

public function f($mysqli_result_or_query)

This method fetches a row from MySQL result or SQL query passed as a parameter. If you’d like to reduce amount of code and you need to obtain only one record - just pass SQL query directly to this method. So it is a little bit more than wrapper around MySQL result::fetch_assoc()

Category: Database routines Useful stuff

Parameters:

  • $mysqli_result_or_query (variant) - it could be MySQL result object or a string with SQL query.

Returns: associative array with field names as keys, like MySQL result::fetch_assoc()

public function fa($mysqli_result)

This method fetches a row from MySQL result as an enumerated array. So it is just a wrapper around MySQL result::fetch_array()

Category: Database routines

Parameters:

  • $mysqli_result (variant) - MySQL result object.

Returns: enumerated array, like MySQL result::fetch_array()

public function ff($mysqli_result)

This method fetches field information from MySQL result as MySQL result::fetch_fields(). It is actually a wrapper around it.

Category: Database routines

Parameters:

  • $mysqli_result (variant) - MySQL result object.

Returns: array, like MySQL result::fetch_fields()

public function i()

This method returns autoincremental ID value after last INSERT ... query in current connection. It is a wrapper over MySQLi::insert_id property.

Category: Database routines

Returns: int - last insert id.

public function a()

This method returns number of rows affected by last INSERT ..., UPDATE ... or DELETE ... query in current connection. It is a wrapper over MySQLi::affected_rows property.

Category: Database routines

Returns: int - number of records affected.

public function d($mysqli_result_or_query)

This method fetches first value of first row from MySQL result or SQL query passed as a parameter. If you’d like to reduce amount of code and you need to obtain only one record - just pass SQL query directly to this method. So it is a little bit more than wrapper around MySQL result::fetch_assoc()

Category: Database routines Useful stuff

Parameters:

  • $mysqli_result_or_query (variant) - it could be MySQL result object or a string with SQL query.

Returns: associative array with field names as keys, like MySQL result::fetch_assoc()

public function startProfiling()

Use this method to start or reset profiling process in your MySQL script. It drops all counters and set $oSQL->flagProfiling=true

Category: Debug

public function showProfileInfo()

This function outputs profile info to current standard output. Use it for brief investigation of what’s going on within your SQL query sequence.

Category: Debug

public function getProfileInfo()

This function returns profiling as the list of associative arrays for each query.

Category: Debug

Returns: enumerable array of associative arrays:

  • ‘query’ - query executed
  • ‘affected’ - number of rows affected
  • ‘returned’ - number of rows returned
  • ‘backtrace’ - debug_backtrace() on execution point
  • ‘time’- number of microseconds

public function getTableInfo($tblName, $dbName=null)

getTableInfo() funiction retrieves useful MySQL table information: in addition to MySQL’s ‘SHOW FULL COLUMNS …’ and ‘SHOW KEYS FROM …’ it also returns some PHP code that could be added to URL string, SQL queries or evaluated. See description below.

Category: Data read Database routines Useful stuff

Parameters:

  • $tblName (string) - table name
  • $dbName (string) - database name (optional), if not set it returns information for table with $tblName in current database

Returns: array:

  • ‘hasActivityStamp’ - flag, when true, it means that table has *InsertBy/*InsertDate/*EditBy/*EditDate fields.
  • ‘columns’ - dictionary with field data with field names as keys, as returned by 'SHOW FULL COLUMNS ...':
    • ‘Field’ - field name,
    • ‘Type’ - data type as set in the database,
    • ‘DataType’ - data type in terms of eiseIntra (e.g. ‘PK’),
    • ‘PKDataType’ - data type of primary key (e.g. ‘integer’),
    • ‘Collation’ - data collation,
    • ‘Null’ - ‘YES’ or ‘NO’ when field can be nulled or not,
    • ‘Key’ - key feature, whether it’s foreign on primary,
    • ‘Default’ - deafult value,
    • ‘Extra’ - ‘auto_increment’ or other stuff,
    • ‘Privileges’ - currency use privileges (e.g. ‘select,insert,update,references’),
    • ‘Comment’ - field comment,
  • ‘keys’ - list of keys that consists of associative arrays, as returned by MySQL 'SHOW KEYS FROM ...'
  • ‘PK’ - list of primary key columns
  • ‘PKtype’ - one of the following values: ‘auto_increment’, ‘GUID’ or ‘user_defined’
  • ‘prefix’ - 3-4 letter column name prefix,
  • ‘table’ - table name,
  • ‘columns_index’ - associative array of columns with names as keys and names as values. Kept for backward compatibility.
  • ‘PKVars’ - PHP sentence to obtain primary key variable from $_GET or _POST. Example: '$bltID = (isset($_POST[\'bltID\']) ? $_POST[\'bltID\'] : $_GET[\'bltID\'] );
  • ‘PKCond’ - SQL sentence for WHERE condtition to obtain single record by primary key. Example: 'bltID = ".(int)($bltID)."'
  • ‘PKURI’ - PHP string that can be added to URL string. Example: 'bltID=".urlencode($bltID)."',
  • ‘type’ - object type. Can be ‘view’ or table’,
  • ‘Comment’ - table comment.

public variable $arrIntra2DBTypeMap

This array maps intra data types into MySQL data types

public variable $arrDBTypeMap

This array maps intra data types into MySQL binary data types constants