RUSSYSDEV: eiseIntra
Instant administrative backend for your application

eiseIntra core

Authentication, form elements display, data handling routines

Version: 2.3
Package: eiseIntra

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 property $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 property $usrID

ID of current user.

Category: Authentication

public property $conf

Configuration array. See description at eiseIntra::$defaultConf

Category: Configuration

public property $local

This property is set to ‘Local’ when local language is selected by the user

Category: i18n

static property $defaultConf

Default configuration. Exact configuration parameters list is:

  • ‘dateFormat’ - date format, default is “d.m.Y”
  • ‘prgDate’ - regular expression for input validation/converion
  • ‘prgDateReplaceTo’ - replace parameter for preg_replace() for dates, to convert dates from local format to ISO
  • ‘timeFormat’ - time format, default is “H:i” (24-hours time), both are according to PHP date() format function
  • ‘prgTime’ - regular expression for input validation
  • ‘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
  • ‘cachePreventorVar’ - Query string parameter for cache prevention in link elements with CSS and JSS. E.g.
  • ‘cookiePath’ - (isset($eiseIntraCookiePath) ? $eiseIntraCookiePath : '/')
  • ‘cookieExpire’ - see eiseIntra::getCookiePath() function for details
  • ‘UserMessageCookieName’ - for cookie used to store user messages, default is ‘eiMsg’
  • ‘defaultPage’ - the page that user see right after authentication.
public static $defaultConf = array(
        'versionIntra'=>EISEINTRA_VERSION
        , 'dateFormat' => "d.m.Y" // 
        , 'timeFormat' => "H:i" // 
        , 'decimalPlaces' => "2"
        , 'decimalSeparator' => "."
        , 'thousandsSeparator' => ","
        , 'language' => 'rus'
        , 'logofftimeout' => 360 //6 hours
        , 'addEiseIntraValueClass' => true
        , 'keyboards' => 'EN,RU'
        , 'dataActionKey' => 'DataAction'
        , 'dataReadKey' => 'DataAction'
        , 'cachePreventorVar' => 'nc'
        , 'system' => 'nc'
        , 'cookiePath' => 'nc'
        , 'cookieExpire' => 'nc'
        , 'useBootstrap' => false
        , 'strAttrib' => ''
        , 'context' => ''
        , 'auto_translate'=>true
        , 'collect_keys'=>false
//       , 'flagSetGlobalCookieOnRedirect' = false
        , 'selItemMenu' => null
        , 'selItemTopLevelMenu' => null
        , 'defaultPage' => 'about.php'
        , 'pass_hash' => 'md5'
        , 'frame' => false
    );

Category: Configuration

static property $arrKeyboard

Array with keyboard layouts. Key is layout code, value is string with characters in the order of keyboard keys.

static $arrKeyboard = array(
        'EN' =>   'qwertyuiop[]asdfghjkl;\'\\zxcvbnm,./QWERTYUIOP{}ASDFGHJKL:"|ZXCVBNM<>?'
        , 'RU' => 'йцукенгшщзхъфывапролджэёячсмитьбю/ЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЁЯЧСМИТЬБЮ?'
    );

Category: Data Handling i18n

public function __construct()

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

Parameters:

  • $oSQL (eiseSQL) - MySQL connection object.
  • $conf (array) - associative array with configuration options. Defaults are set at eiseIntra::$defaultConf

Category: Authentication Configuration

public function decodeAuthString()

Function decodes authstring login:password using decrypt() method

Parameters:

  • $authstring (string) - Encoded string

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

Category: Authentication

public function encodeAuthString($login, $password)

Function encodes authstring login:password using encrypt() method.

Parameters:

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

Returns: string Encoded authentication string.

Category: Authentication

public function getEncryptionKey()

This function returns combination of global variable $eiseIntraKey
stored at eiseIntra’s inc_config.php and server variable EISINTRA_KEY that can be set in Nginx or Apache config. Key length is set to 128-bit (32 bytes/chars).

If concatentated key length is less that 32 bytes, all remaining places are padded with zeros (0).

When both keys are not set, function returns false and eiseIntra::encrypt() and eiseIntra::decrypt() are forced to work only as base64 encoder/decoder.

Returns: string Key or false, if both key parts are empty.

public function encrypt($encrypt)

Function encrypts a string with symmetric encryption using the key obtained from getEncryptionKey() method and current encoding algorithm (now RIJNDAEL_256 and mcrypt). In case mcrypt is missed in PHP or encryption key is empty, it encodes string with base64.

Parameters:

  • $encrypt (string) - String to be encrypted.

Returns: string Encrypted string.

Category: Authentication

public function decrypt($decrypt)

Function decrypts a string with symmetric decryption using the key obtained from getEncryptionKey() method and current encoding algorithm (now RIJNDAEL_256 and mcrypt). In case mcrypt is missed in PHP, it encodes string with base64.

Parameters:

  • $encrypt (string) - String to be encrypted.

Returns: string Encrypted string.

Category: Authentication

public function password_hash($pass)

This function returns password hash according to hashing method specified in $conf[‘pass_hash’].

Parameters:

  • $pass (string) - The password, the string to be encrypted.

Returns: string Hash of given string.

Category: Authentication

public function password_verify($pass, $hash)

This function verifies the password across the hash according to hashing method specified in $conf[‘pass_hash’].

Parameters:

  • $pass (string) - The password.
  • $hash (string) - Hash string to be compared with.

Returns: string Hash of given string.

Category: Authentication

public function Authenticate()

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.

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.

Category: Authentication

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 getUserRoles($usrID = null)

This function fills in $arrUsrData[‘roles’] and $arrUsrData[‘roleIDs’] arrays. Can be overriden for virtual roles.

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.

Parameters:

  • $usrID (string) - user ID to get role membership info. If set, this function doesn’t touch $intra->arrUsrData['roles'] and $intra->arrUsrData['roleIDs']

Returns: array with role IDs as keys and role titles are values.

Category: Authentication Authorization

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 an exception. 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.

Returns: array $intra->arrUsrData

Category: Authentication Authorization

public function topLevelMenu()

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.

Parameters:

  • $arrItems = array()
  • $options = array()

Category: Navigation

public function menu($target = null)

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

Parameters:

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

Returns: string HTML with menu structure

Category: Navigation

public function menuItem($rw)

This method is called before each menu item <li> closure. You can add custom menu items/submenus in your own app overriding this method in the inherited class.

Parameters:

  • $rw (string) - row info from stbl_page for current <li>

Returns: string HTML with submenu structure

Category: Navigation

public function actionMenu()

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.

  • ‘id’ (string) - (optional) HTML attribute “id” content
  • ‘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.

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”.

Category: Navigation

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.

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

Category: Configuration

public function redirect()

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 $(document).ready() 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.

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.

Category: Navigation

public function backref($urlIfNoReferer=null)

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

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

Category: Navigation

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

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

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 (variant) - data to be transmitted

Category: Data Output

public function file($name, $type, $pathOrData)

Function outputs binary stuff to the user.

Parameters:

  • $name (string) - file name in UTF-8
  • $type (string) - MIME-type of the content
  • $pathOrData (variant) - if realpath() returns true for this variable, system will read the file. Otherwise it outputs the data as is.

Category: Data Output

public function batchStart($conf = array())

This function outputs necessary stuff to start batch data operation script. WARNING: this function closes existing session using session_write_close(), so avoid changing $_SESSION variables in your batch processing script.

Parameters:

  • $conf = array()

Category: Batch run

public function batchEcho($string)

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

Parameters:

  • $string

Category: Batch run

public function setUserMessage($strMessage, $conf = array())

This function sets user message to the cookie.

Parameters:

  • $strMessage (string) - with user message
  • $conf (array) - param

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

Parameters:

  • $rolID (int) - role ID

Returns: array of user ID’s

Category: Authentication Authorization

public function checkLanguage()

This function initialize what language to use: local or global

Category: 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.”

Parameters:

  • $key

Category: i18n

public function addTranslationKey($key)

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

Parameters:

  • $key

Category: i18n

public function readSettings()

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

Category: Configuration

public function setting()

This function is to read or write system variable values stored in stbl_setup.

Parameters:

  • $stpVarName (string) - system setup variable name, e.g. ‘docLifeTime’
  • $stpCharValue (string) - value for this system setup variable

Returns: variant if param $stpVarValue is omitted it returns current setting value, otherwise it returns null in case of successful value set or throws an exception if settings variable doesn’t exist in the system

public function field()

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.

Parameters:

  • $title
  • $name=null
  • $val_in=null
  • $conf=array()

Category: Forms

public function fieldset()

This function returns HTML for single fieldset

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

Category: Forms

public function form()

This function returns HTML for the form.

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.

Category: Forms

public function showTextBox()

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

Parameters:

  • $strName
  • $strValue
  • $arrConfig=Array()

Category: Forms

public function showTextArea()

This function returns HTML for the <textarea>.

Parameters:

  • $strName
  • $strValue
  • $arrConfig=Array()

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.

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

Category: Forms

public function showCombo()

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.

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

Category: Forms

public function showCheckBox()

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

Parameters:

  • $strName
  • $strValue
  • $arrConfig=Array()

Category: Forms

public function showRadio()

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

Parameters:

  • $strName
  • $strValue
  • $arrConfig=Array()

Category: Forms

public function showRadioByArray()

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

Parameters:

  • $strRadioName
  • $strValue
  • $arrConfig

Category: Forms

public function showAjaxDropdown()

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

Parameters:

  • $strFieldName
  • $strValue
  • $arrConfig

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.

Parameters:

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

Returns: bool

Category: Forms

public function loadJS()

Function that loads JavaScript files basing on GLOBAL $arrJS

Category: Data Output

public function loadCSS()

Function that loads CSS files basing on GLOBAL $arrCSS

Category: Data Output

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.

Parameters:

  • $dataAction (variant) - string or array of possible <input name=DataAction> 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.

Category: Navigation Data Handling

public function dataRead()

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.

Parameters:

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

Returns: variant value that return user function.

Category: Data Handling

public function getDateTimeByOperationTime()

This function returns date and time string basing on operation date and time string. If operation day start time is greater than operation day end time, and time passed less than operation day end time, then date will be incremented by one day.

For example, if operation day starts at 07:30 and ends at 01:30 next day, then operation time ‘01:00’ will be considered as next day time. If operation date is ‘2024-06-30’, then returned date and time will be ‘2024-07-01 01:00:00’.

Parameters:

  • $operationDate (string) - date in ‘Y-m-d’ format
  • $time (string) - time in ‘H:i:s’ format

Returns: string date and time in ‘Y-m-d H:i:s’ format

Category: Data Output

public function showDatesPeriod()

This function returns date period string basing on start and end dates. If both dates are equal, only one date will be returned.

Parameters:

  • $trnStartDate
  • $trnEndDate
  • $precision = ‘date’

Category: Data Output

static function confVariations()

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

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

Category: Utilities

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.

Parameters:

  • $src (string) - Original user input

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

Category: i18n Useful stuff

static function debug($to_echo)

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

Parameters:

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

Category: Debug

protected 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

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

Version: 2.0beta
Package: eiseIntra

static property $arrIntraDataTypes

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

public static $arrIntraDataTypes = array(
    'integer' => array('integer', 'int', 'number', 'smallint', 'mediumint', 'bigint')
    , 'real' => array('real', 'double', 'decimal', 'float')
    , 'money' => array('money')
    , 'boolean' => array('boolean', 'tinyint', 'bit')
    , 'text' => array('text', 'varchar', 'char', 'tinytext', 'text', 'mediumtext', 'longtext')
    , 'binary' => array('binary', 'varbinary', 'tinyblob', 'blob', 'mediumblob', 'longblob')
    , 'date' => array('date'), 'time' => array('time'), 'datetime' => array('datetime')
    , 'timestamp' => array('timestamp')
    , 'FK' => array('int', 'integer', 'varchar', 'char', 'text')
    , 'PK' => array('int', 'integer', 'varchar', 'char', 'text')
    , 'activity_stamp' => array('datetime', 'timestamp')
);

public function formatByType2PHP()

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

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

Category: Data formatting

public function formatByType2SQL()

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

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.

Category: Data formatting

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.

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

Category: Data Output

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.

Parameters:

  • $sqlReadyValue (string) -

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

Category: Data formatting

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.

Parameters:

  • $val (string) - user data.

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

Category: Data formatting

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

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

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.

Category: Data formatting

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.

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

Category: Data formatting

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’]).

Parameters:

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

Returns: string - converted date/time value

Category: Data formatting

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.

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.

Category: Data formatting

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.

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.

Category: Data formatting

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.

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.

Category: Data formatting

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 (‘##’).

Parameters:

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

Category: Database routines

public function getDataFromCommonViews()

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

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

Category: Database routines

public function arrPHP2SQL($arrSrc, $types = array())

This function recursively converts data in associative array according to type definition supplied in $types parameter. Suitable for situations when you need locale-indepedent json.

Parameters:

  • $arrSrc
  • $types = array()

public function arrSQL2PHP($arrSrc, $types = array())

This function also recursively converts data in associative array according to type definition supplied in $types parameter. Suitable for situations when you need to convert data according to your user locale.

Parameters:

  • $arrSrc
  • $types = array()

public function getSQLFields($tableInfo, $data)

This function returns SQL for field values. It can be used either in UPDATE or in INSERT … SET queries.

Parameters:

  • $tableInfo
  • $data

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()

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.

Parameters:

  • $type
  • $field = ‘’

static function getDecimalPlaces()

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.

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.

Category: Data formatting

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.

Version: 2.0beta
Package: eiseIntra

public property $arrIntra2DBTypeMap

This array maps intra data types into MySQL data types

public $arrIntra2DBTypeMap = array(        
        "integer"=>'int(11)',
        "real"=>'decimal(16,4)',
        "boolean"=>'tinyint(4)',
        "text"=>'varchar(1024)',
        "binary"=>'blob',
        "date"=>'date',
        "time"=>'time',
        "datetime" => 'datetime'
        );

public property $arrDBTypeMap

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

public $arrDBTypeMap = array(        
        "integer"=>array(MYSQLI_TYPE_SHORT
          , MYSQLI_TYPE_LONG
          , MYSQLI_TYPE_LONGLONG
          , MYSQLI_TYPE_INT24
          , MYSQLI_TYPE_YEAR),
        "real"=>array(MYSQLI_TYPE_DECIMAL
          , MYSQLI_TYPE_NEWDECIMAL
          , MYSQLI_TYPE_FLOAT
          , MYSQLI_TYPE_DOUBLE),
        "boolean"=>array(MYSQLI_TYPE_BIT
          , MYSQLI_TYPE_TINY
          , MYSQLI_TYPE_CHAR),
        "text"=>array(MYSQLI_TYPE_ENUM
          , MYSQLI_TYPE_SET
          , MYSQLI_TYPE_VAR_STRING
          , MYSQLI_TYPE_STRING
          , MYSQLI_TYPE_GEOMETRY),
        "binary"=>array(MYSQLI_TYPE_TINY_BLOB
          , MYSQLI_TYPE_MEDIUM_BLOB
          , MYSQLI_TYPE_LONG_BLOB
          , MYSQLI_TYPE_BLOB),
        "date"=>array(MYSQLI_TYPE_DATE
          , MYSQLI_TYPE_NEWDATE),
        "time"=>array(MYSQLI_TYPE_TIME
          , MYSQLI_TYPE_INTERVAL),
        "datetime" => array(MYSQLI_TYPE_DATETIME),
        "timestamp" => array(MYSQLI_TYPE_TIMESTAMP)
        );

public function __construct()

Performs connect to the database with parent constructor.

WARNING! method connect() only make some adjustments

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

Category: Database routines
Throws: eiseSQLException object when connect fails

public function connect()

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

Parameters:

  • $host = NULL
  • $user = NULL
  • $password = NULL
  • $database = NULL
  • $port = NULL
  • $socket = NULL

public function selectDB($dbname=’‘)

Another backward-compatibility function Do not use.

Parameters:

  • $dbname=’’

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.

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%'

Category: Database routines Data formatting

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.

Parameters:

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

Returns: string

Category: Database routines Data formatting

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

Parameters:

  • $query

Returns: MySQL resource

Category: Database routines

public function n($mysqli_result)

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

Parameters:

  • $mysqli_result (object) -

Returns: int

Category: Database routines

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()

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()

Category: Database routines

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()

Parameters:

  • $mysqli_result (variant) - MySQL result object.

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

Category: Database routines

public function ff($result_or_query)

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

Parameters:

  • $result_or_query (variant) - MySQL result object or SQL query.

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

Category: Database routines

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.

Returns: int - last insert id.

Category: Database routines

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.

Returns: int - number of records affected.

Category: Database routines

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()

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()

Category: Database routines

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.

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

Category: Debug

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.

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’
  • ‘name’ - table name without “tbl_” prefix,
  • ‘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.

Category: Database routines