Skip to content

Instantly share code, notes, and snippets.

@teresko
Last active August 29, 2015 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save teresko/d23c66e4a5ca23e748e4 to your computer and use it in GitHub Desktop.
Save teresko/d23c66e4a5ca23e748e4 to your computer and use it in GitHub Desktop.
<?php
/**
* System kernel
*/
// include technical utility functions
include_once ADMIN_DIR.'/tech/func/stringleftright.php';
include_once ADMIN_DIR.'/tech/func/arrayerrorlog.php';
include_once ADMIN_DIR.'/tech/func/sqltimeerrorlog.php';
include_once ADMIN_DIR.'/tech/func/json_decode_array.php';
// include abstract link class
include_once ADMIN_DIR.'/kernel/kernel_link.php';
include_once ADMIN_DIR.'/pages/myERGO/myERGOfront.php';
include_once ADMIN_DIR.'/pages/myERGO/myERGOInside.php';
include_once ADMIN_DIR.'/pages/myERGO/MyErgoCore.php';
/**
* @abstract Main system control functions
*/
final class kernel {
// Kernel constants
public $iwVersion = "0.0"; // Current IW version (set from defination IWVERSION)
public $kernelVersion = "1.0"; // Current kernel version
public $apiVersion = "0.0"; // Current API version
public $phpVersion = "5.0"; // MIN php version
// Kernel variables
public $kernel; // Pointer on self (on kernel)
public $mode; // Kernel mode
public $adminDIR; // Aministartion root directory
public $siteID; // Current site ID
public $siteURL; // Site root URL
public $siteDIR; // Site root directory
public $site; // Array with site fields
private $myERGOfront;
private $myERGOInside;
// Kernel constructor
// [ private ]
// $siteID - ID of current site
// RETURN: void
function __construct($siteID = "admin") {
$this->beginMS = microtime(); // Set BEGIN microtime [for debug]
$this->define_anonymous_user();
// Check ADMIN directory exist and
// and set $this->adminDir variable
if (!defined('ADMIN_DIR') || !is_dir(ADMIN_DIR)) $this->error("kernel", 1, array("dir" => ADMIN_DIR));
$this->adminDIR = ADMIN_DIR;
// Set kernel variables
$this->kernel = $this;
// Detect site and get site data
$this->site = $this->getSiteData($siteID);
$this->siteURL = $this->site["url"];
$this->mode = $this->site["mode"];
$this->siteID = $this->site["ID"];
$this->siteDIR = $this->site["dir"];
// Load configuration
$this->cfg = $this->loadConf();
// Detect OS and set kernel variable $osType
$this->osType = $this->detectOS();
// Set InterWeb version variable from IWVERSION defination
if (defined("IWVERSION")) $this->iwVersion = IWVERSION;
// Check version numbers [IW, kernel, API]
if (!$this->checkVersion(phpversion(), $this->phpVersion)) {
$this->error("kernel", 2, array("currentVersion" => phpversion(), "minVersion" => $this->phpVersion));
}
// Create site connector
$this->db = $this->dbcon->create($this->site["dbScheme"]);
$this->db->loadQuerys("kernel.sql", true);
}
/**
* Sets up online anonymous user login and id constants
*/
private function define_anonymous_user() {
if (!defined('PD_USER_ANONYMOUS_ONLINE_ID')) define('PD_USER_ANONYMOUS_ONLINE_ID', 1000000000);
if (!defined('PD_USER_ANONYMOUS_ONLINE_LOGIN')) define('PD_USER_ANONYMOUS_ONLINE_LOGIN', 'online_anonymous');
}
// atgriež informāciju par lietotāju
function userInfo(){
$ret = '';
// online polišu masīvs
$sesPolIdArr = $this->session->get('onlinePolisesIdMasivs');
if(!empty($sesPolIdArr)){
$sesPolIdArr = json_decode($sesPolIdArr, true);
if(is_array($sesPolIdArr) && count($sesPolIdArr) > 0){
$sesPolIdArr = 'Sesijas online polišu id saraksts: '.implode('; ', $sesPolIdArr);
}else{
$sesPolIdArr = '';
}
}else{
$sesPolIdArr = '';
}
$ret = trim(
trim((isset($_SERVER['HTTP_USER_AGENT'])?$_SERVER['HTTP_USER_AGENT']:'[server-HTTP_USER_AGENT nav uzstādīts]<br>')).'<br/>'
. trim('ID - '.(isset($_COOKIE['PHPSESSID'])?$_COOKIE['PHPSESSID']:'[cookie-PHPSESSID nav uzstādīts]')).'<br/>'
. trim($sesPolIdArr).'<br/>'
);
while(strpos($ret, '<br/><br/>') !== false)$ret = str_replace('<br/><br/>', '<br/>', $ret);
while(right($ret, 5) == '<br/>')$ret = substr($ret, 0, strlen($ret) - 5);
return $ret;
}
// pārbauda, vai ir izsaukums no servera konsoles
private function checkConsoleCall(){
$srvAddr = '['.trim($_SERVER['SERVER_ADDR']).']';
$cliAddr = '['.trim($_SERVER['REMOTE_ADDR']).']';
if($srvAddr !== '[]' && $cliAddr != '[]'
&& $srvAddr == $cliAddr)return true;
return false;
}
// pārbauda skripta izsaukšanas veidu
// normal - parasts izsaukums: izpilde ar visiem lietotāju ierobežojumiem, tiek atgriezts html
// silent - izsaukums no servera konsoles: izpilde ar administratora tiesībām, netiek atgriezts html
private function checkCallMode(){
$this->callMode = 'normal';
// pārbauda ievades parametru
if(isset($_REQUEST['query'])){
$q = $_REQUEST['query'];
// pārbauda, vai ir PNG BASE64 izsaukšanas veids
$s = 'pdimg/';
if($this->callMode == 'normal')if(strpos($q, $s) !== false){
$i = strpos($q, $s);
$this->callMode = 'pngbase64';
$_REQUEST['query'] = substr($q, $i + strlen($s));
}
// pārbauda, vai ir silent izsaukšanas veids
if($this->callMode == 'normal')if($q == 'silent' || substr($q, 0, 7) == 'silent/'){
if($this->checkConsoleCall()){ // atļauts tikai no servera konsoles
if(!isset($_SERVER['HTTP_USER_AGENT'])){
$_SERVER['HTTP_USER_AGENT'] = $this->kernel->msg->get('misc->kernel->useragent2');
}
$this->callMode = 'silent';
$_REQUEST['query'] = trim(trim(substr($q, 6)), '/');
}
}
// check if called reversing
if ($this->callMode == 'normal' && ($q == 'revers' || substr($q, 0, 7) == 'revers/')) include ADMIN_DIR.'/kernel/code/revers/check.php';
// check if its user process serving
if (substr($q, 0, 12) == 'user_process') {
$this->callMode = 'user_process';
$_REQUEST['query'] = trim(trim(substr($q, 12)), '/');
}
// check online check payment status
if (substr($q, 0, 4) == 'ocps') {
$this->callMode = 'ocps';
$_REQUEST['query'] = trim(trim(substr($q, 4)), '/');
}
// check pctool serving
if (substr($q, 0, 6) == 'pctool') {
$this->callMode = 'pctool';
}
// check version copy status checking
if (substr($q, 0, 17) == 'versioncopystatus') {
$this->callMode = 'versioncopystatus';
}
// get latest jQuery
if (substr($q, 0, 10) == 'js/jQuery-') {
$this->callMode = 'jQuery';
}
// check framework request
if (strpos($q, '/FWa/') !== false) {
$this->callMode = 'FWa';
}
// check service request
if (substr($q, 0, 7) == 'service') {
$this->callMode = 'service';
}
}
}
// check whether it is development environment
public function is_dev_env(){
if (isset($this->sistemasParametri['sistema-vide'])
&& $this->sistemasParametri['sistema-vide'] == 10) {
return true;
}
return false;
}
/**
* Generate page content
* @param array $params array with kernel parameters
* @return string generated page content
*/
private function show_get_user() {
// log out online anonymous or online anonymous partner user
$sess_iw_user = $this->session->get('__IW_USER');
if (isset($sess_iw_user['ID']) // user is logged in
&& $sess_iw_user['ID'] >= PD_USER_ANONYMOUS_ONLINE_ID // online anonymous user
) $this->user->logout();
// register last action id
$this->atlauts_polises_nr_pedejais_action_id();
// check current user id and set it to kernel
// no idea why login function doesnt set kernel->userID by itself so we set it here
$this->userID = $this->get_current_user_id();
$this->user->get();
}
public function show($params = array()) {
// check resource versioning
if(isset($this->sistemasParametri['resource-version-include'])
&& $this->sistemasParametri['resource-version-include'] == 10){
define('RESOURCE_VERSION', true);
}else{
define('RESOURCE_VERSION', false);
}
// check call mode
$this->checkCallMode();
// perform content execution depending on system functionality
$checkPendulum = false;
switch ($this->callMode) { // process call mode
case 'user_process':
$q = explode('/', $_REQUEST['query']);
$reqParams = array_shift($q);
$out = $this->user_process->request_process($reqParams);
break;
case 'ocps': // online check payment status
$out = $this->online_check_payment_status->check($_REQUEST['query']);
break;
case 'pctool':
$out = $this->pctool->request();
break;
case 'versioncopystatus':
$out = $this->pe->pe_obj_ver_copy_check->get_status();
break;
case 'jQuery':
header('content-type: application/x-javascript');
$out = file_get_contents($this->get_latest_jquery());
break;
case 'FWa':
$out = $this->processFrameworkActivity();
break;
case 'service':
$out = $this->services->call();
break;
default:
$out = false;
$checkPendulum = true;
}
if (substr_count($_SERVER['REQUEST_URI'], "ee/health_insurance_information") ) {
if (substr_count($_SERVER['REQUEST_URI'], "ee/health_insurance_information?cardnr=") ) {
include "./pages/admin/healthInsuranceInformation/HealthInsuranceInformation.php";
$healthInsuranceInformation = new HealthInsuranceInformation($this);
$this->online_sistemas_statuss();
$this->online_nolasit_parametrus();
$this->online_relog_anonymous_user(false);
$this->checkSession();
$cardnr = $_GET['cardnr'];
$out = $healthInsuranceInformation->findInfo($cardnr);
} else {
include "./pages/admin/healthInsuranceInformation/HealthInsuranceInformation.php";
$healthInsuranceInformation = new HealthInsuranceInformation($this);
$out = $healthInsuranceInformation->createHTML();
}
}
if ($out === false) { // if call mode did not process anything then process normaly
switch($this->sistemasParametri['sistema-funkcija']){
case 10: // portal functionality
/*
// log out online anonymous or online anonymojus partner user
$sess_iw_user = $this->session->get('__IW_USER');
if (isset($sess_iw_user['ID']) // user is logged in
&& $sess_iw_user['ID'] >= PD_USER_ANONYMOUS_ONLINE_ID // online anonymous user
) $this->user->logout();
// register last action id
$this->atlauts_polises_nr_pedejais_action_id();
*/
$this->show_get_user();
// continue
$out = $this->showMode($this->mode, $params);
break;
case 20: // online functionality
if ($this->callMode != 'pngbase64') {
// skip status and parameter check if its picture request
$this->online_sistemas_statuss();
$this->online_nolasit_parametrus();
}
$this->online_relog_anonymous_user($this->online_partner->get_id_user());
$this->checkSession();
// check call mode
if ($this->callMode == 'pngbase64') {
// picture request
$out = $this->software_handled_picture->serve($_REQUEST['query']);
$checkPendulum = false;
} else if ($this->callMode == 'revers' && $this->doReverse !== false) {
// reversing request
include ADMIN_DIR.'/kernel/code/revers/run.php';
$out = $this->reversOut;
$checkPendulum = false;
} else {
// usual request
$out = $this->online_izveidot_lapas_attelojumu();
if ($this->callMode == 'silent')
{
$out = '';
}
}
break;
default:
$out = '<h1>'.$this->kernel->msg->get('misc.kernel.incorrectRequest').'</h1>';
}
}
$this->endMS = microtime();
return $out;
}
/**
* Get class function to load dynamic module for kernel
* @param string $objName object class name to load
* @return object pointer to class; return null on error
*/
function __get($objName) {
// try Load dynamic module from disk
if (!isset($this->$objName)) {
switch ($objName) {
case 'frameworks': // product engine frameworks
$fName = ADMIN_DIR.'/pd/dz/frameworks/frameworks.php';
break;
default: // regular kernel module
$fName = strtr($objName, array("." => "", "~" => "", "/" => "", "\\" => ""));
$fName = dirname(__FILE__)."/modules/".$fName.".php";
}
if (!is_readable($fName)) {
return null;
}
// load claass
$this->loadClass($fName, $objName);
$this->$objName = new $objName($this);
}
// Return pointer on object
return $this->$objName;
}
// Load Extended kernel class
// and check exist class in system
// $fileName - file name of extended kernel class on disk [with path from KERNEL directory]
// $className - class name [for exist check]
// [ private ]
// RETURN: true, if function detect error then generate system error
public function loadClass($fileName = "", $className = "") {
if (class_exists($className, false))
{
return true;
}
if (!is_readable($fileName))
{
$this->error("kernel", 4, array("file" => $fileName, "name" => $className));
return false;
}
include_once($fileName);
if (!class_exists($className, false))
{
$this->error("kernel", 5, array("file" => $fileName, "name" => $className));
return false;
}
return true;
}
// Kernel SYSTEM ERROR function
// Run when need process supernumerary situation
// [ public ]
// $errorNr - Error number
// $param - Error extended parametrs
// RETURN: not exit
public function error($errorBlock = "kernel", $errorNr, $param = array()) {
$msgStr = false;
// Static array with errors
$staticError[0] = "Unknown error";
$staticError[1] = "Can't load file with ERRORS<br/>\nFile: {file}";
// Try load error file and sreate $this->errors variable
if (!isset($this->errors)) {
$fName = $this->adminDIR . "/kernel/errors.php";
if (!is_readable($fName)) {
$msgStr = $staticError[1];
$param = array("file" => $fName);
} else {
include_once($fName);
if (!isset($error) || !is_array($error) || !count($error)) {
$msgStr = $staticError[0];
} else $this->errors = $error;
}
}
// If can't find error message, then get message "Unknown error"
if (!$msgStr)
if (isset($this->errors[$errorBlock][$errorNr]))
$msgStr = $this->errors[$errorBlock][$errorNr];
else $msgStr = $staticError[0];
// Parse extended parametrs
if (is_array($param)) foreach($param as $key => $val) {
// replace real ADMIN dir on sign : "[ADMIN dir]", for securety
$val = preg_replace("/^".preg_quote($this->adminDIR,'/')."(.+)$/i", "[ADMIN dir]\\1", $val);
$msgStr = str_replace("{".$key."}", $val, $msgStr);
}
// Create string with error message
$str = "<html>\n";
$str .= "<head>\n<title>InterWeb - system error [$errorNr]</title>\n</head>\n";
$str .= "<body>\n<b style='color:red;font-size:20'>\n";
$str .= "CRYTICAL SYSTEM ERROR<br/>\n";
$str .= "BLOCK: $errorBlock<br/>\n";
$str .= "NR: $errorNr<br/>\n";
$str .= $msgStr . "<br/>\n";
$str .= "</b>\n</body>\n</html>";
print $str;
exit();
}
// Check current versions
// $curVer - current version
// $needVer - needed version
// RETURN: true | false
public function checkVersion($curVer, $needVer) {
if (version_compare($curVer, $needVer) < 0) return false;
return true;
}
// Configuration file loader.
// [ private ]
// RETURN: array with configuration | false
private function loadConf() {
include $this->adminDIR.'/cfg/identity.php';
$this->sistemasParametri = $sistemasParametri;
$fName = $this->adminDIR."/cfg/cfg.php";
if (!is_readable($fName))
$this->error("kernel", 3, array("file" => $fName));
$cfg = array();
include_once $fName;
if (!isset($cfg) || !is_array($cfg) || !count($cfg))
$this->error("kernel", 3, array("file" => $fName));
return $cfg;
}
// Detect Operation system (WINDOWS or LINUX)
// [ private ]
// RETURN: OS type:
// 0 - Linux (*-nix)
// 1 - Windows
private function detectOS() {
$str = php_uname();
// BEGIN ERROR CHANGE 2010.05.20
// replaced EREGI() with STRISTR() because of EREGI() is deprecated on version 5.0+ of PHP
if (stristr($str, "WIN") !== false) return 1; // Windows OS
// END ERROR CHANGE
return 0; // Linux, (*-nix), other (if error)
}
// Get unique ID (for one process)
// [ public ]
// $type: FALSE - get one load UID
// TRUE - get uniq UID
// RETURN: ID - uniq ID of process
public function getUID($type = true) {
static $processUID = 0;
$processUID++;
if ($type) {
$retID = time().$processUID.rand(1000,9999);
return $retID;
}
return $processUID;
}
// Get unique ID
// [ public ]
// $name: name of stream ID (default - empty, empty is a global ID)
// $clear: FALSE - not check date
// INT - check expire date
// "d" - Every day clear
// "w" - Every week clear
// RETURN: ID - uniq ID of system [for site]
public function getID($name = false, $clear = false) {
if ($clear) {
switch(trim(strtoupper($clear))) {
case "D":
$clear = mktime(0, 0, 0, date("m"), date("d"), date("Y"));
break;
case "W":
$dt = time() - 6 * 24 * 60 * 60;
$clear = mktime(0, 0, 0, date("m", $dt), date("d", $dt), date("Y", $dt));
break;
case "M":
$clear = mktime(0, 0, 0, date("m"), 1, date("Y"));
break;
case "Y":
$clear = mktime(0, 0, 0, 1, 1, date("Y"));
break;
}
}
$this->db->query('LOCK TABLES `__iw_ID` WRITE');
$this->db->transaction("GETID");
//ZR657 UPDATED SQL
if (!$name) $name = "";
$result = $this->db->queryID("getID", array("name" => addslashes($name)));
if ($result && $row = $result->getRow()) {
$ID = $row["ID"];
if (!$clear) {
$date = date("Y-m-d H:i:s", time());
$nextID = $ID + 1;
} else {
if ($clear > $this->kernel->api->datetime->db2ut($row["date"])) {
$date = date("Y-m-d H:i:s", time());
$ID = 1;
$nextID = 2;
} else {
$date = $row["date"];
$nextID = $ID + 1;
}
}
//ZR657 UPDATED SQL
$stat = $this->db->queryID("updateID", array(
"name" => addslashes($name),
"date" => $date,
"ID" => $nextID));
if (!$stat) {
$this->db->rollback("GETID");
$this->db->query('UNLOCK TABLES');
return false;
}
} else {
//ZR657 UPDATED SQL
$stat = $this->db->queryID("createID", array(
"name" => addslashes($name),
"date" => date("Y-m-d H:i:s", time()),
"ID" => 1));
if ($stat) {
$ID = 1;
} else {
$this->db->rollback("GETID");
$this->db->query('UNLOCK TABLES');
return false;
}
}
$this->db->commit("GETID");
$this->db->query('UNLOCK TABLES');
return $ID;
}
// Detect site and get site data
// [ private ]
// $siteID - ID of current site
// RETURN: FALSE | Array with site data
private function getSiteData($siteID = 0) {
if (!$siteID)
$this->error("kernel", 7,
array("siteID" => $siteID));
$fName = $this->adminDIR."/cfg/sites.php";
if (!is_readable($fName))
$this->error("kernel", 7,
array("siteID" => $siteID));
$sites = array();
include_once $fName;
// If not found array 'sites'
if (!isset($sites) || !is_array($sites) || !count($sites))
$this->error("kernel", 7,
array("siteID" => $siteID));
// If not found key of siteID in array $sites
if (!isset($sites[$siteID])) {
if (in_array($siteID, $sites)) {
$site = array();
} else $this->error("kernel", 7,
array("siteID" => $siteID));
} else $site = $sites[$siteID];
$site["ID"] = $siteID;
if (!isset($site["name"])) $site["name"] = $siteID;
if (!isset($site["url"])) $site["url"] = "/";
if (!isset($site["mode"])) $site["mode"] = "admin";
if (!isset($site["dbScheme"])) $site["dbScheme"] = "default";
if (!isset($site["dir"]) || !is_dir($site["dir"])) {
if (isset($_SERVER["DOCUMENT_ROOT"]))
$rootDIR = $_SERVER["DOCUMENT_ROOT"]."/";
else $rootDIR = $this->adminDIR."/../"; // If admin in "admin" directory
$siteDIR = realpath($rootDIR.$site["url"]);
$site["dir"] = $siteDIR;
}
return $site;
}
// Execute mode file
// $mode - what file of mode execute
// $kjernelParams - parametrs from kernel execute
// RETURN: FALSE | string with template content
private function showMode($mode = false, $kernelParams = array()) {
if (!$mode) $this->error("kernel", 13);
$fName = $this->adminDIR."/kernel/modes/".$mode.".php";
if (!is_readable($fName))
$this->error("kernel", 14, array("file" => $fName));
$out = "";
include $fName;
return $out;
}
// Online
private function checkSession(){
$this->session->setLastAccessTime();
if(isset($_REQUEST)){
if(isset($_REQUEST['action'])){
$action = $_REQUEST['action'];
if ($action=='logout') $this->user->logout();
}
}
}
private function getSessionTimeoutScript(){
$html = '';
// timeout var iestāties tikai pēc veiksmīga getoffer izsaukuma
if(isset($this->dz->ins->inslp['insparam']['global']['TURN.ON.TIMEOUT.FUNCTION'])
&& $this->dz->ins->inslp['insparam']['global']['TURN.ON.TIMEOUT.FUNCTION'] == 1){
$sessTimeout = intval($this->sistemasParametri['portals-online-inactivity-timeout']);
$displWarningTime=intval($this->sistemasParametri['portals-online-inactivity-display-warning']);
$sessTimeoutWarningInMilis = ($sessTimeout-$displWarningTime)*1000;
$sessTimeoutInMilis = ($sessTimeout)*1000;
$redirectURL = dirname($_SERVER['SCRIPT_NAME']);
$focusInterval = round($sessTimeoutWarningInMilis/3*100,0);
$html.="<div id=\"app-popups\">";
$html.="<div style=\"display:none\" id=\"popup-timeout-msg-background\"class=\"popup-background\"></div>";
$html.="<div style=\"display:none\" id=\"popup-timeout-msg\" class=\"popup-container\">";
$html.="<div id=\"popup-timeout-msg-title\" class=\"popup-title\"></div>";
$html.="<div id=\"popup-timeout-msg-content\" class=\"popup-content\">";
$html.="<div id=\"popup-timeout-msg-content-txt\" class=\"popup-content-text\"></div>";
$html.="<div class=\"popup-content-text\"><input id=\"popup-timeout-msg-content-btn\" class=\"popup-content-button-red\" type=\"button\" value=\"OK\" name=\"btnOK\"/></div>";
$html.="</div>";
$html.="</div>";
$html.="</div>"."\n";
$html.="<script type=\"text/javascript\">"."\n";
$html.="var popupTimer1;"."\n";
$html.="var popupTimer2;"."\n";
$html.="function callPopupTimer1(){"."\n"
."return setInterval(\"showTimeoutMsgPopup(1, '".$this->kernel->msg->get('misc.kernel.timeoutMsg1')." ".($displWarningTime/60)." ".$this->kernel->msg->get('misc.kernel.timeoutMsg2')."', 'OK', '',popupTimer1,'clearInterval(popupTimer2);"
."popupTimer2=callPopupTimer2();')\",".$sessTimeoutWarningInMilis.");}"."\n";
$html.="function callPopupTimer2(){return setInterval(\"showTimeoutMsgPopup(2, '".$this->kernel->msg->get('misc.kernel.timeoutMsg3')."', '".$this->kernel->msg->get('misc.kernel.timeoutMsg4')."', '".$redirectURL."',popupTimer2,'')\",".$sessTimeoutInMilis.");}"."\n";
$html.="popupTimer1=callPopupTimer1();"."\n";
$html.="popupTimer2=callPopupTimer2();"."\n";
$html.="var IE = document.all?true:false;"."\n";
$html.="if (!IE) document.captureEvents(Event.MOUSEMOVE);"."\n";
$html.="document.onmousemove = getMouseXY;"."\n";
$html.="var tempX = 0;"."\n";
$html.="var tempY = 0;"."\n";
$html.="if(top.document.activeElement)if(top.document.activeElement.id)setNonRestoreFields(top.document.activeElement.id);"."\n";
$html.="function getMouseXY(e) {clearInterval(popupTimer2);clearInterval(popupTimer1);popupTimer1=callPopupTimer1();popupTimer2=callPopupTimer2();}"."\n";
$html.="function getActiveElem() {var objLocTemp = top.document.activeElement;"."\n"
."if(top.activeElemOnl != objLocTemp.id){clearInterval(popupTimer2);clearInterval(popupTimer1);popupTimer1=callPopupTimer1();popupTimer2=callPopupTimer2();setNonRestoreFields(top.document.activeElement.id);}else{setNonRestoreFields(top.document.activeElement.id);}}"."\n";
$html.="setInterval(getActiveElem, ".$focusInterval.");"."\n";
$html.="</script>";
}
return $html;
}
public function checkSystem() {
$this->connectionToDis = $this->kernel->api->dis->getCurrentUserAuthorizedChannelCode();
if ($this->connectionToDis == false || $this->db == false) {
return false;
}
return true;
}
public function fetchConfigParameter( $name )
{
$sql = "SELECT konfigValue FROM ergo.portalkonfig where konfigName = '$name'";
if ($this->kernel->db)
{
$result = $this->kernel->db->query($sql);
if ($result && $result->numRows())
{
$neaktT = $result->getRows();
return $neaktT[0]['konfigValue'];
}
}
return null;
}
public function isTimeout() {
$session = $this->kernel->session;
if (isset($_REQUEST['query']) && substr_count($_REQUEST['query'], 'iportal/logout') > 0)
{
$session->set("lastActivitationTimeOnline", false);
return true;
}
$last_activity = $session->get("lastActivitationTimeOnline");
if ( $last_activity === false )
{
$this->timeOut = false;
return false;
}
$limit = (int)$this->fetchConfigParameter('onlineTimeout');
if ( $limit )
{
$range = $last_activity + $limit;
$now = time();
$unlocked = true;
if ( isset($_SESSION['onlineTick']) )
{
$lock = (int)$this->fetchConfigParameter('onlineLockTime');
$activity = $now - $_SESSION['onlineTick'];
if ( $activity > $lock )
{
$unlocked = false;
unset($_SESSION['onlineTick']);
}
}
if ( $now < $range && $unlocked )
{
$session->set("lastActivitationTimeOnline", $now);
$_SESSION['onlineTick'] = $now;
return false;
}
}
$session->set("lastActivitationTimeOnline", false);
$this->timeOut = true;
return true;
}
private function wasClosed()
{
return false;
}
public function online_izveidot_lapas_attelojumu() {
if ('iportal/login' == $this->getQueryPath() && !$this->checkSystem()) {
if (isset($_REQUEST['query'])) {
unset($_REQUEST['query']);
}
if (isset($_SERVER['QUERY_STRING'])) {
unset($_SERVER['QUERY_STRING']);
}
}
if (($this->isTimeout() || $this->wasClosed() || $this->ir_online_apturets() == true) && isset($_SESSION['AUTHORIZED']) && $_SESSION['AUTHORIZED'] === true) {
$this->olnProdukts = true;
$this->olnAuthorized = true;
return $this->izveidot_landing_attelojumu();
} else if (isset($_SESSION['AUTHORIZED']) && $_SESSION['AUTHORIZED'] === true) {
$this->kernel->session->set("lastActivitationTimeOnline", time());
unset($_SESSION['AUTHORIZATION_SERVICE']);
$GLOBALS['label'] = 'myer';
return $this->izveidot_landing_attelojumu4MyERGOInside();
} else {
// izveido online lapas attēlojumu
return $this->izveidot_landing_attelojumu();
}
}
private function getSpecifiedLoginTarget( $query, $allowed = array(), $fallback = '' )
{
$index = strrpos( $query , '/');
$target = substr($query , $index + 1);
if ( in_array( strtolower( $target ), $allowed) === false )
{
return $fallback;
}
return '/' . $target;
}
private function is_login_page_request($fullQuery) {
// exceptions to links that are requests to login page
// link=[language]/iportal/login/go - passing through redirect to bank login page
if (strpos($fullQuery, '/iportal/login/go/') !== false) {
return false;
}
// links that are requests to login page
if (
substr($fullQuery, 0, strlen($this->olnValoda.'/iportal/login')) == $this->olnValoda.'/iportal/login' // [language]/iportal/login
|| substr($fullQuery, 0, strlen($this->olnValoda.'/login')) == $this->olnValoda.'/login' // [language]/login
|| substr($fullQuery, 0, strlen('iportal/login')) == 'iportal/login' // iportal/login
|| substr($fullQuery, 0, strlen('login')) == 'login' // login
) {
return true;
}
// fresh myergo link also must be taken as login form
if ($this->onlineCurrentHost == $this->hostMyErgo && strlen($fullQuery) < 1) {
return true;
}
// normal links
return false;
}
private function assignOnlineDefaults()
{
$this->olnValoda = 'lv';
$this->olnProdukts = false;
$this->olnInstance = false;
$this->olnInstancesParametrs = false;
$this->olnQuery = array();
}
private function online_nolasit_parametrus() {
// check session
if (!is_object($this->session)) {
$this->session->get();
}
// read the query
$fullQuery = '';
if(isset($_REQUEST['query'])){
$q = trim(strtolower($_REQUEST['query']));
if(!empty($q)){
$fullQuery = $q;
$q = explode('/', $q);
}else{
$q = array();
}
}
// read current location
$currentProt = !empty($_SERVER['HTTPS'])?'https://':'http://';
$currentHost = trim($_SERVER['HTTP_HOST'], ' /');
$this->onlineCurrentHost = $currentHost;
$currentDir = trim(dirname($_SERVER['SCRIPT_NAME']), ' /');
$this->olnLinkReference = $currentProt.$currentHost.'/'.$currentDir;
// check direct redirect *REDIR1*
//if (($i = strpos($fullQuery, '/sessionredirect/')) !== false) {
//
// // it is direct redirect with session id
// $redirectUrl = trim($this->olnLinkReference.'/'.substr($fullQuery, 0, $i), ' /');
// $this->header_redirect($redirectUrl, true);
//
//}
// get myergo link
// get system parameter for site to redirect to
$map = array(
10 => 'dev',
20 => 'devtest',
30 => 'accept',
40 => 'prod',
);
$paramName = false;
$environmentId = (int)$this->sistemasParametri['sistema-vide'];
if ( array_key_exists($environmentId, $map))
{
$paramName = $map[$environmentId];
}
if ($paramName !== false) {
// get myergo host name
$this->hostMyErgo = $this->getSystemParam('online-mansergo-redirect-'.$paramName, '');
// get online hostname
$this->hostDefault = $this->getSystemParam('online-default-redirect-'.$paramName, '');
// development environment
if ($this->sistemasParametri['sistema-vide'] == 10)
{
$map = array(
'10.10.10.15' => array(
'online' => 'online.ergo.o12',
'mansergo' => 'www.mansergo.o12',
),
'10.10.10.12' => array(
'online' => 'online.ergo.o12',
'mansergo' => 'www.mansergo.o12',
),
'10.10.10.100' => array(
'online' => 'online.ergo.mt',
'mansergo' => 'mansergo.mt',
),
'127.0.0.1' => array(
'online' => 'online.ergo.mt',
'mansergo' => 'mansergo.mt',
),
'10.10.10.102' => array(
'online' => 'online.ergo.mt',
'mansergo' => 'mansergo.mt',
),
);
if ( array_key_exists( $_SERVER['SERVER_ADDR'], $map) )
{
$this->hostDefault = $map[$_SERVER['SERVER_ADDR']]['online'];
$this->hostMyErgo = $map[$_SERVER['SERVER_ADDR']]['mansergo'];
}
}
}
// nolasa online pieprasījuma parametrus
// uzstāda noklusētos parametrus
$this->assignOnlineDefaults();
// apstrādā pieprasījuma parametrus
$fullQuery = '';
if(isset($_REQUEST['query'])){
$q = trim(strtolower($_REQUEST['query']));
if(!empty($q)){
$fullQuery = $q;
$q = explode('/', $q);
}else{
$q = array();
}
}
// pievieno pieprasījuma parametrus
$i = 0;
// valoda
if (isset($q[$i])) {
$this->olnValoda = $q[$i];
}
// apskatās, vai valoda tiek atbalstīta
if($this->olnValoda != 'lv'){
// uzstāda noklusēto valodu
$this->olnValoda = 'lv';
}
$_SESSION['KERNEL-olnValoda'] = $this->olnValoda;
// indicator if need to redirect
$redirectUrl = false;
// check if it is login page request
if ($this->is_login_page_request($fullQuery) === true) {
$loginFormRequest = true;
} else {
$loginFormRequest = false;
}
// check if user is authorized
if (isset($_SESSION['AUTHORIZED']) && $_SESSION['AUTHORIZED'] === true) {
$userAuthorized = true;
} else {
$userAuthorized = false;
}
// check if it is already login form
if ($currentHost == $this->hostMyErgo && strpos($fullQuery, 'iportal/login') !== false) {
$insideLoginForm = true;
} else {
$insideLoginForm = false;
}
// if user is authorized and host is not myergo then redirect to same link with myergo
if ($userAuthorized === true && $currentHost == $this->hostDefault) {
$redirectUrl = $currentProt.$this->hostMyErgo.'/'.$currentDir.'/'.$fullQuery;
}
// if user is not authorized, and it is not login form request, and it is not bank call then redirect same link to default host
if ($userAuthorized === false && $currentHost == $this->hostMyErgo && $loginFormRequest === false && strpos($fullQuery, 'iportal/login/go/') === false) {
$redirectUrl = $currentProt.$this->hostDefault.'/'.$currentDir.'/'.$fullQuery;
}
// if user is not authorized, and it is login form request from myergo then redirect to login form
if ($userAuthorized === false && $currentHost == $this->hostMyErgo && $loginFormRequest === true && $insideLoginForm === false) {
$redirectUrl = $currentProt.$this->hostMyErgo.'/'.$currentDir.'/'.$fullQuery.'/'.$this->olnValoda.'/iportal/login';
}
// if user is not authorized, and it is login form request from default then redirect to login form
if ($userAuthorized === false && $currentHost == $this->hostDefault && $loginFormRequest === true && $insideLoginForm === false) {
$redirectUrl = $currentProt.$this->hostMyErgo.'/'.$currentDir.'/'.$fullQuery;
}
// if it is logout for then redirect to online
if ($userAuthorized === false && $currentHost == $this->hostMyErgo && strpos($fullQuery, '/logout') !== false) {
$redirectUrl = $currentProt.$this->hostDefault.'/'.$currentDir;
}
// check if need redirection
if ($redirectUrl !== false) {
// create direct redirect with session id
// sessionredirect is then catched, made session, and redirected again without that parameter
$this->header_redirect($redirectUrl, false);
}
// produkts
$i++;
if (isset($q[$i])) {
$this->olnProdukts = $q[$i];
}
$i++;
if (isset($q[$i])) {
$this->olnProdukts .= '/'.$q[$i];
}
// check claim subproduct
$this->onlineProductSubCode = '';
if (isset($q[$i + 1])) { // there is one more parameter
if (in_array($this->olnProdukts, array('claim/health', 'claim/octa'))) { // only these product have subproducts
if (in_array($q[$i + 1], array('select', 'private', 'enterprise'))) { // only thse substring are allowed to be subproducts
$i++;
$this->onlineProductSubCode = $q[$i];
}
}
}
// atlasa produkta definīcijas idi pēc produkta online linka nosaukuma
$sql = 'select i.idi idi,x.kodspro kods from pdsarpro p inner join pdsardefxpro x on x.kodspro = p.kods'
.' inner join pdnobji i on i.id = x.iddef where upper(p.olnlinkname) = upper("'.$this->olnProdukts.'") and irOnlineProd = 1';
if ($this->kernel->db) {
$r = $this->kernel->db->query($sql);
if ($r && $r->numRows()) {
$r = $r->getRows();
if(is_array($r) && isset($r[0]) && isset($r[0]['idi'])){
// produkta idi ir atrasts
$this->olnProduktaIdi = $r[0]['idi'];
}else{
$this->olnProduktaIdi = false;
}
}
}
// instance vai starpnieka pazīme
$i++;
if (isset($q[$i])) {
if ($q[$i] == 'partner') {
// process online partner web module request
$this->online_partner->start($q, $i);
} else {
// continue processing usual request
$this->olnInstance = (int)$q[$i];
// instances parametrs
$i++;
if (isset($q[$i])) {
$this->olnInstancesParametrs = trim($q[$i]);
}
// lauka id
$i++;
if (isset($q[$i])) {
if ($this->olnInstancesParametrs == 'fwa') {
// framework activity
$this->olnLaukaID = $q[$i];
} else {
// normal activity
$this->olnLaukaID = (int)$q[$i];
}
}
}
}
// check framework activity
if ($this->olnInstancesParametrs == 'fwa') {
$this->frameworkActivity = $this->olnLaukaID;
unset($this->olnInstancesParametrs);
unset($this->olnLaukaID);
} else {
unset($this->frameworkActivity);
}
// apstrādā atgriezuma formas datus
$this->apstradat_atgriezuma_formas_datus();
// vai ir jāpalaiž produkts
if(in_array($this->snippetForm['run'], $this->snippetForm['prodArr'])){
// jāpalaiž produkts no atgriezuma formas
$this->olnProdukts = $this->snippetForm['runSaites'][$this->snippetForm['run']];
}else{
// nepareizi parametri - neko nedara
$this->snippetForm['run'] = false;
}
}
private function header_redirect($locationUrl, $checkDevEnv) {
if ($checkDevEnv === false || !$this->is_dev_env()) {
$locationUrl = str_replace('://', '@:@/@/@', $locationUrl);
while (strpos($locationUrl, '//') !== false) {
$locationUrl = str_replace('//', '/', $locationUrl);
}
$locationUrl = str_replace('@:@/@/@', '://', $locationUrl);
header('Location: '.$locationUrl);
exit;
}
}
private function izveidot_landing_attelojumu() {
$foo = '';
if ( strpos($_SERVER['REQUEST_URI'], 'iportal/logout') !== false )
{
$foo = '<div id="bad-puppy" style="height: 200px;"">
<h2 style="text-align: center; font: normal 20px Verdana; padding-top: 60px;">Paldies, ka izmantojāt portālu Mans ERGO! <br>
Uz tikšanos!</h2>
</div>
<script>
$("#bad-puppy").delay(4000).slideUp(1000);
</script>';
}
$this->myERGOfront = new myERGOfront($this);
if (isset($_SESSION['CUSTID']))
{
$this->myERGOfront->logout();
}
$tmpl = $this->tmpl->createFromFile($this->adminDIR.'/online/landing.tmpl');
$tmpl->vars['ENVDEVTEST'] = $this->html_landing_envdevtest();
$tmpl->vars['START'] = dirname($_SERVER['SCRIPT_NAME']);
$tmpl->vars['CALC-START'] = $this->olnLinkReference.'/'.$this->olnValoda.'/calc';
$tmpl->vars['LANDINGHEADER'] = $this->izveidot_landing_header_attelojumu();
$tmpl->vars['LANDINGNAVIGATIONBAR'] = $this->izveidot_landing_navigation_bar_attelojumu();
$tmpl->vars['LANDINGMAIN'] = '<div id="mainarea">'. $foo . $this->izveidot_landing_main_attelojumu().'</div>';
$tmpl->vars['LANDINGLEFT'] = $this->izveidot_landing_left_attelojumu();
$tmpl->vars['LANDINGRIGHT'] = '<div id="rightcol">'.$this->izveidot_landing_right_attelojumu().'</div>';
$tmpl->vars['TIMEOUTSCRIPT'] = $this->getSessionTimeoutScript();
$tmpl->vars['LANDINGONLINENEWS'] = '';
$tmpl->vars['CALC'] = $tmpl->vars['PIRKT'] = '';
switch ($this->getQueryPath()) {
case "calc":
case "calc/kasko":
case "calc/octa":
$tmpl->vars['CALC'] = 'selected';
break;
default:
$tmpl->vars['PIRKT'] = 'selected';
}
$this->addProductPaths($tmpl);
// šis template mainīgais jāaizpilda pēc produkta apstrādes
$tmpl->vars['BRIAPTHTML'] = $this->ir_online_bri_apt_html();
$tmpl = $this->jsInclude($tmpl);
// make the html
return $tmpl->get();
}
private function jsInclude($tmpl) {
// frameworks css include
if (isset($this->runtimeFrameworkName)) {
// add frameworks css
$tmpl->vars['FRAMEWORKSCSS'] = '<link href="online/css/'.$this->runtimeFrameworkName.'.css" rel="stylesheet">';
} else {
$tmpl->vars['FRAMEWORKSCSS'] = '';
}
// javascript include
// iw.js must be divided into global, portal, online, and subgroups over several files
// currently its left as is
$tmpl->vars['JSIWJS'] = '<script type="text/javascript" src="js/iw.js"></script>';
if (isset($this->runtimeFrameworkName)) {
// frameworks js
$tmpl->vars['JSPDJS'] = '<script type="text/javascript" src="js/uploader-requirements.js"></script>';
$tmpl->vars['JSPDVEIDNE'] = '';
$tmpl->vars['FRAMEWORKSJS'] = '<script type="text/javascript" src="online/js/frameworks.js"></script>'
.'<script type="text/javascript" src="online/js/'.$this->runtimeFrameworkName.'.js"></script>'
;
$tmpl->vars['JSJQUERY'] = '<script type="text/javascript" src="js/jQuery-'.date('Y').'-'.date('m').'.js"></script>';
} else {
// normal js
$tmpl->vars['JSPDJS'] = '<script type="text/javascript" src="js/pdjs.js"></script>'
.'<script type="text/javascript" src="js/pdjs.exe.v3.v4.v5.js"></script>'
.'<script type="text/javascript" src="js/pdjs.exe.v1.js"></script>'
.'<script type="text/javascript" src="js/pdjs.exe.v2.js"></script>'
;
$tmpl->vars['JSPDVEIDNE'] = '<script type="text/javascript" src="js/pdveidne.js"></script>';
$tmpl->vars['FRAMEWORKSJS'] = '';
$tmpl->vars['JSJQUERY'] = '<script type="text/javascript" src="online/js/jquery-1.6.4.min.js"></script>';
}
return $tmpl;
}
private function izveidot_landing_attelojumu4MyERGOInside() {
//*
//$this->izveidot_landing_main_attelojumu();exit;
$query = $this->getQueryPath();
$language = $this->olnValoda;
$template = $this->tmpl;
$dblink = $this->db->handle;
$dis = $this->api->dis;
$kernel = $this;
$config = array(
'sys' => $this->sistemasParametri,
'cfg' => $this->cfg,
);
$this->myERGOInside = $core = new myERGOInside($this);
$this->myERGOfront = new myERGOfront($this);
require ADMIN_DIR . '/pages/myERGO/bootstrap.php';
exit;
}
private function html_landing_envdevtest() {
if (in_array($this->sistemasParametri['sistema-vide'], array(40))) return '';
return $this->tmpl->createFromFile($this->adminDIR.'/online/landing-envdevtest-warning.tmpl')->get();
}
public function getPolicyBar() {
return $this->izveidot_landing_left_banner_attelojumu();
}
private function izveidot_landing_left_attelojumu(){
$tmpl = $this->tmpl->createFromFile($this->adminDIR.'/online/landing-left.tmpl');
$tmpl->vars['CA-NOTEIKUMI'] = $this->getSystemParam('link-apdr-nosac', 'DEF.Ceļ.0');
$tmpl->vars['IP-NOTEIKUMI'] = $this->getSystemParam('link-apdr-nosac', 'DEF.Īpa.0');
$tmpl->vars['OCTA-NOTEIKUMI'] = $this->getSystemParam('link-apdr-nosac', 'DEF.Oct.22');
$tmpl->vars['OCTA-MENU-OPEN'] = $tmpl->vars['OCTA-BUY-SELECTED'] =
$tmpl->vars['CA-MENU-OPEN'] = $tmpl->vars['CA-BUY-SELECTED'] =
$tmpl->vars['IP-MENU-OPEN'] = $tmpl->vars['IP-BUY-SELECTED'] =
$tmpl->vars['IP-MENU-OPEN'] = $tmpl->vars['IP-BUY-SELECTED'] =
$tmpl->vars['KASKO-MENU-OPEN'] = $tmpl->vars['KASKO-CAL-SELECTED'] =
$tmpl->vars['HEALTH-CLAIM-SELECTED'] = $tmpl->vars['HEALTH-MENU-OPEN'] =
'';
$tmpl->vars['OCTA-MENU-SHOW'] =
$tmpl->vars['CA-MENU-SHOW'] =
$tmpl->vars['IP-MENU-SHOW'] =
$tmpl->vars['KASKO-MENU-SHOW'] =
$tmpl->vars['HEALTH-MENU-SHOW'] =
'js-show';
switch ($this->getQueryPath()) {
case 'policy/octa':
$tmpl->vars['OCTA-MENU-OPEN'] = 'open';
$tmpl->vars['OCTA-MENU-SHOW'] = '';
$tmpl->vars['OCTA-BUY-SELECTED'] = 'selected';
break;
case 'policy/travel':
$tmpl->vars['CA-MENU-OPEN'] = 'open';
$tmpl->vars['CA-MENU-SHOW'] = '';
$tmpl->vars['CA-BUY-SELECTED'] = 'selected';
break;
case 'policy/property':
$tmpl->vars['IP-MENU-OPEN'] = 'open';
$tmpl->vars['IP-MENU-SHOW'] = '';
$tmpl->vars['IP-BUY-SELECTED'] = 'selected';
break;
case 'calc/kasko':
$tmpl->vars['KASKO-MENU-OPEN'] = 'open';
$tmpl->vars['KASKO-MENU-SHOW'] = '';
$tmpl->vars['KASKO-CAL-SELECTED'] = 'selected';
break;
case 'calc/octa':
$tmpl->vars['OCTA-MENU-OPEN'] = 'open';
$tmpl->vars['OCTA-MENU-SHOW'] = '';
$tmpl->vars['OCTA-CALC-SELECTED'] = 'selected';
break;
case 'claim/health':
$tmpl->vars['HEALTH-MENU-OPEN'] = 'open';
$tmpl->vars['HEALTH-MENU-SHOW'] = '';
$tmpl->vars['HEALTH-CLAIM-SELECTED'] = 'selected';
break;
case 'claim/health/select':
case 'claim/health/enterprise':
case 'claim/health/private':
$tmpl->vars['HEALTH-MENU-OPEN'] = 'open';
$tmpl->vars['HEALTH-MENU-SHOW'] = '';
$tmpl->vars['HEALTH-CLAIM-SELECTED'] = 'selected';
break;
case 'claim/octa/select':
$tmpl->vars['OCTA-MENU-OPEN'] = 'open';
$tmpl->vars['OCTA-MENU-SHOW'] = '';
$tmpl->vars['OCTA-CLAIM-SELECTED'] = 'selected';
break;
}
$tmpl->vars['PARTNERINFO'] = $this->izveidot_landing_left_partner_info_attelojumu();
$tmpl->vars['BANNER'] = $this->izveidot_landing_left_banner_attelojumu();
$this->addProductPaths($tmpl);
$tmpl->vars['SHOWHEALTHMENU'] = 'display:block;';
return $tmpl->get();
}
public function kernelPoliciesPage()
{
}
/**
* Get banner html code
* @return string
*/
public function izveidot_landing_left_banner_attelojumu() {
$tmpl = $this->tmpl->createFromFile($this->adminDIR.'/online/landing-left-banner.tmpl');
$image_tmpl = $this->tmpl->createFromFile($this->adminDIR.'/online/landing-left-banner-image.tmpl');
$flash_tmpl = $this->tmpl->createFromFile($this->adminDIR.'/online/landing-left-banner-flash.tmpl');
$bannersDir = $this->adminDIR.'/online/images/lv/banners/';
$setLink = function($lnk = '') use ($image_tmpl, $flash_tmpl){
if (empty($lnk)) {
$image_tmpl->vars['LINK-START'] = $image_tmpl->vars['LINK-END'] = $flash_tmpl->vars['LINK'] = '';
} else {
$image_tmpl->vars['LINK-START'] = '<a href="'.$lnk.'" target="_blank">';
$image_tmpl->vars['LINK-END'] = '</a>';
$flash_tmpl->vars['LINK'] = '?clicktag='.$lnk;
}
};
$setLink();
$qPath = $this->getQueryPath();
if (stripos($qPath, 'policy/octa') !== false) {
$filename = trim($this->getSystemParam('online-banner-filename', 'DEF.Oct.22'));
if ($filename == '' || !file_exists($bannersDir.$filename)) {
return '';
}
$setLink($this->getSystemParam('online-banner-link', 'DEF.Oct.22'));
} elseif (stripos($qPath, 'policy/travel') !== false) {
$filename = trim($this->getSystemParam('online-banner-filename', 'DEF.Ceļ.0'));
if ($filename == '' || !file_exists($bannersDir.$filename)) {
return '';
}
$setLink($this->getSystemParam('online-banner-link', 'DEF.Ceļ.0'));
} elseif (stripos($qPath, 'policy/property') !== false) {
$filename = trim($this->getSystemParam('online-banner-filename', 'DEF.Īpa.0'));
if ($filename == '' || !file_exists($bannersDir.$filename)) {
return '';
}
$setLink($this->getSystemParam('online-banner-link', 'DEF.Īpa.0'));
} elseif (stripos($qPath, 'calc/kasko') !== false) {
$filename = trim($this->getSystemParam('online-banner-filename', 'DEF.Kas.2'));
if ($filename == '' || !file_exists($bannersDir.$filename)) {
return '';
}
$setLink($this->getSystemParam('online-banner-link', 'DEF.Kas.2'));
} else {
$filename = trim($this->getSystemParam('online-banner-filename'));
if ($filename == '' || !file_exists($bannersDir.$filename)) {
return '';
}
$setLink($this->getSystemParam('online-banner-link'));
}
$image_tmpl->vars['FILE-NAME'] = $flash_tmpl->vars['FILE-NAME'] = trim($filename);
if(pathinfo($filename, PATHINFO_EXTENSION) == 'swf' ){
$tmpl->vars['FLASH-BANNER'] = $flash_tmpl->get();
$tmpl->vars['IMAGE-BANNER'] = '';
} else {
$tmpl->vars['FLASH-BANNER'] = '';
$tmpl->vars['IMAGE-BANNER'] = $image_tmpl->get();
}
return $tmpl->get();
}
/**
* @return string
*/
public function izveidot_landing_left_partner_info_attelojumu() {
if (!$this->online_partner->is_set) return '';
$tmpl = $this->tmpl->createFromFile($this->adminDIR.'/online/landing-left-partner-info.tmpl');
$tmpl->vars['PARTNERLOGO'] = '';
$tmpl->vars['PARTNERINFO'] = $this->online_partner->info;
if ($this->online_partner->logo_pic == '') return $tmpl->get();
$logoTmpl = $this->tmpl->createFromFile($this->adminDIR.'/online/landing-left-partner-info-img.tmpl');
$logoTmpl->vars['PARTNERLOGO'] = $this->online_partner->logo_pic;
$tmpl->vars['PARTNERLOGO'] = $logoTmpl->get();
return $tmpl->get();
}
public function izveidot_landing_right_attelojumu() {
return $this->izveidot_landing_right_attelojumuByQueryPath($this->getQueryPath());
}
public function izveidot_landing_right_attelojumuByQueryPath($queryPath) {
if ( isset($_SESSION['AUTHORIZED'])
&& $_SESSION['AUTHORIZED'] === true
&& (
strpos( $queryPath, 'claim') !== false
|| strpos( $queryPath, 'policy') !== false
|| strpos( $queryPath, 'calc') !== false
)
)
{
$tmpl = $this->tmpl->createFromFile($this->adminDIR.'/online/landing-right-nohelp.tmpl');
}
else{
$tmpl = $this->tmpl->createFromFile($this->adminDIR.'/online/landing-right.tmpl');
}
$tmpl->vars['LISTITEM'] = $this->olnProdukts? '' : '<li>'.$this->kernel->msg->get('misc.kernel.policyType').'</li>';
$tmpl->vars['PHONE'] = $this->getSystemParam('telefons', $this->olnDefIekIdi);
$tmpl->vars['EMAIL'] = $this->getSystemParam('epasts-info', $this->olnDefIekIdi);
$tmpl->vars['3display'] = '';
$tmpl->vars['HEADER'] = 'Kā iegādāties apdrošinā- šanas
polisi internetā?';
$tmpl->vars['HELP'] = file_get_contents($this->adminDIR.'/online/html/product-help.html');
switch($queryPath) {
case 'policy/octa':
$tmpl->vars['MOREINFO'] = file_get_contents($this->adminDIR.'/online/html/octa-more-info.html');
break;
case 'policy/travel':
$tmpl->vars['MOREINFO'] = file_get_contents($this->adminDIR.'/online/html/travel-more-info.html');
break;
case 'policy/property':
$tmpl->vars['MOREINFO'] = file_get_contents($this->adminDIR.'/online/html/property-more-info.html');
break;
case 'calc/kasko':
$tmpl->vars['HELP'] = file_get_contents($this->adminDIR.'/online/html/kasko-help.html');
$tmpl->vars['MOREINFO'] = '';
break;
case 'iportal/landing':
if (isset($_SESSION['AUTHORIZED']) && $_SESSION['AUTHORIZED'] === true) {
$tmpl->vars['MOREINFO'] = '';
$tmpl->vars['HEADER'] = '';
$tmpl->vars['HELP'] = '';
$tmpl->vars['display'] = 'display:none';
$tmpl->vars['2display'] = 'display:none';
} else {
$tmpl->vars['MOREINFO'] = '';
$tmpl->vars['HEADER'] = $this->myERGOfront->getTextFromDsLaukXproXvalXveids('LAU.myh.0', $this->olnValoda);
$tmpl->vars['HELP'] = $this->myERGOfront->getTextFromDsLaukXproXvalXveids('LAU.myc.0', $this->olnValoda);
}
break;
case 'iportal/userinfo':
$tmpl->vars['MOREINFO'] = '';
$tmpl->vars['HEADER'] = $this->myERGOfront->getTextFromDsLaukXproXvalXveids('LAU.myh.1', $this->olnValoda);
$tmpl->vars['HELP'] = $this->myERGOfront->getTextFromDsLaukXproXvalXveids('LAU.myc.1', $this->olnValoda);
$tmpl->vars['2display'] = 'display:none';
$tmpl->vars['3display'] = 'display:none';
break;
default:
$tmpl->vars['HELP'] = file_get_contents($this->adminDIR.'/online/html/general-help.html');
$tmpl->vars['MOREINFO'] = '';
}
switch(true) {
case strpos( $queryPath , 'iportal/login') !== false:
$tmpl->vars['HEADER'] ='„Mans ERGO” <br>priekšrocības';
$tmpl->vars['HELP'] = file_get_contents($this->adminDIR.'/online/html/mansergo-help.html');
break;
}
// if ($this->checkSystem()) {
return $this->myERGOfront->getLogInRightSideHTML().$tmpl->get();
// } else {
// return $tmpl->get();
// }
}
private function online_sistemas_statuss() {
// atlasa online sistēmas statusu
$sql = 'select apturStat "0", apturesTeksts "1", bridinTeksts "2", bridStat "3" from portalworkonline';
if ($this->kernel->db) {
$r = $this->kernel->db->query($sql);
if ($r && $r->numRows()) {
$r = $r->getRows();
if(is_array($r) && isset($r[0])){
$this->onlineStatuss = $r[0];
$this->onlineStatuss[0] = '['.$this->onlineStatuss[0].']';
$this->onlineStatuss[1] = trim($this->onlineStatuss[1]);
$this->onlineStatuss[2] = trim($this->onlineStatuss[2]);
$this->onlineStatuss[3] = '['.$this->onlineStatuss[3].']';
}else{
$this->onlineStatuss = false;
}
}
}
}
/**
* Logs in the specified user.
* By default logs in an anonymous user.
* @param int $userId optional user id for login
*/
public function online_relog_anonymous_user($userId) {
// check if anonymous userid is defined
$this->define_anonymous_user();
// user id must be 1000000000 or higher for online anonymous
if ((int)$userId < PD_USER_ANONYMOUS_ONLINE_ID) $userId = PD_USER_ANONYMOUS_ONLINE_ID;
// check if user needs to be reloged
$u = $this->get_current_user_id();
if ($u != $userId){
// log out existing user
if ($u > 0) {
$this->session->remove('dis_session_key');
$this->user->logout();
}
// log in new user
$l = $this->user->get_login($userId);
$r = $this->user->login($l);
}
// check current user id and set it to kernel
// no idea why login function doesnt set kernel->userID by itself so we set it here
$this->userID = $this->get_current_user_id();
$this->user->get();
}
/**
* Gets currently logged in user id from session variable
* @return int user id, 0 if none
*/
public function get_current_user_id() {
$s = $this->session->get('__IW_USER');
if (!isset($s['ID'])) $s['ID'] = 0;
return $s['ID'];
}
/**
* Returns array of session var names to preserve
*/
private function session_vars_to_preserve() {
return array(
'snippetForm-autKods-Txt',
'snippetForm-autKods',
'online_partner_data',
);
}
/**
* Loads given session vars into an array
*/
private function session_vars_preserve() {
$a = $this->session_vars_to_preserve();
$r = array();
foreach ($a as $i => $n) $r[$n] = $this->session->get($n);
$this->session_vars_restorable = $r;
}
/**
* Restores session vars from an array
* @param array $a session vars array
*/
private function session_vars_restore() {
if (!isset($this->session_vars_restorable)) $this->session_vars_restorable = array();
foreach ($this->session_vars_restorable as $n => $v) $this->session->set($n, $v);
$this->session_vars_restorable = array();
}
public function ir_online_apturets(){
$ret = false;
if(isset($this->onlineStatuss) && $this->onlineStatuss !== false
&& isset($this->onlineStatuss[0]) && $this->onlineStatuss[0] == '[0]')$ret = true;
return $ret;
}
private function ir_online_polise_saveoffer(){
// pārbaude, vai tekošajai polisei ir saveoffer
// no mainīgā, kas jau iepriekš ir uzstādīts produkta apstrādē
return(isset($this->olnInstanceIrSaveOffer) && !empty($this->olnInstanceIrSaveOffer));
}
private function ir_online_polise_sakta(){
// pārbaude, vai tekošā polise ir sākta
return(isset($this->olnInstance) && !empty($this->olnInstance));
}
public function onlineError($text = null){
$ret = '';
if($this->connectionToDis === false || $this->db === false || (isset($this->timeOut) && $this->timeOut == true)){
$tmpl = $this->tmpl->createFromFile($this->adminDIR.'/online/landing-bri-apt.tmpl');
if (isset($text)) {
$tmpl->vars['BRIAPTTEKSTS'] = $text;
} else if (isset($this->timeOut)){
$tmpl->vars['BRIAPTTEKSTS'] = 'Sesija ir apturēta. Lai atjaunotu sesiju, autorizējieties atkārtoti!';
} else {
if ($this->olnAuthorized === true) {
$this->olnAuthorized === false;
$tmpl->vars['BRIAPTTEKSTS'] = 'Šobrīd nav iespējams turpināt darbu ar portālu mansERGO. Lūdzu, pēc brīža pamēģiniet vēlreiz vai sazinieties ar ERGO pārstāvi pa tālr. 67081948(darba dienās no 8:30 – 17:00!)';
} else {
$tmpl->vars['BRIAPTTEKSTS'] = 'Šobrīd nav iespējams pieslēgties portālam mansERGO. Lūdzu, pēc brīža pamēģiniet vēlreiz vai sazinieties ar ERGO pārstāvi pa tālr. 67081948(darba dienās no 8:30 – 17:00!)';
}
}
$laiks = 0;
$tmpl->vars['BRIAPTLAIKS'] = '0';//$laiks;
$ret = $tmpl->get();
}
return $ret;
}
private function ir_online_bri_apt_html(){
$ret = '';
// ja tekošā polise ir saveoffer vai tālāk, vai nav atvērts konkrēts produkts, tad ļauj lietotājam izpildīties
if(
!$this->ir_online_polise_saveoffer() // tekošās polises saveoffer
&& isset($this->olnProdukts) && $this->olnProdukts !== false && !empty($this->olnProdukts) // ir produkts
){
if($this->ir_online_apturets()){
$tmpl = $this->tmpl->createFromFile($this->adminDIR.'/online/landing-bri-apt.tmpl');
if($this->ir_online_polise_sakta()){
$tmpl->vars['BRIAPTTEKSTS'] = $this->apstradat_portala_restes($this->onlineStatuss[1]); // apturēšanas paziņojums
$laiks = 0;
}else{
$tmpl->vars['BRIAPTTEKSTS'] = $this->apstradat_portala_restes($this->onlineStatuss[2]); // lapa slēgta
$laiks = 0;
}
$tmpl->vars['BRIAPTLAIKS'] = '0';//$laiks;
$ret = $tmpl->get();
}
}
if ($ret == '') {
$ret = $this->onlineError();
}
return $ret;
}
function online_reg_proc_action($polID, $action){
// izpilda tikai online gadījumā
if($this->sistemasParametri['sistema-funkcija'] == 20){
// izmaina vai pievieno sesijas datus par tekošo darbību ar polisi
$sessID = session_id();
$polID = (int)$polID;
$policyType = trim(substr(isset($this->olnProdukts)?$this->olnProdukts:'',0,45));
$action = trim(substr($action,0,45));
$sql = '/*online reg proc action*/insert into portaluserprocstatonline(sessID,polID,policyType,action,procStart)'
.'values("'.mysql_real_escape_string($sessID).'",'.$polID.',"'.mysql_real_escape_string($policyType).'","'.mysql_real_escape_string($action).'",now())'
.'on duplicate key update action="'.mysql_real_escape_string($action).'",procStart=now()';
$r = $this->kernel->db->query($sql);
$this->online_reg_proc_cleanup();
}
}
function online_reg_proc_cleanup(){
// iztīra visus vecos ierakstus no datubāzes
$sql = '/*online reg proc cleanup*/delete from portaluserprocstatonline where procStart < now() - interval 30 minute';
$r = $this->kernel->db->query($sql);
}
public function kernelProducedOnlinePage()
{
return $this->izveidot_landing_main_attelojumu();
}
private function izveidot_landing_main_attelojumu(){
$tmpl = $this->tmpl->createFromFile($this->adminDIR.'/online/landing-main.tmpl');
$tmpl->vars['LANDINGMAINREKLAMA'] = '';
$tmpl->vars['LANDINGMAINREKLAMAPROD'] = '';
$tmpl->vars['LANDINGMAINPRODUKTS'] = '';
$tmpl->vars['LANDINGCALCSNIPPET'] = '';
$tmpl->vars['LANDINGMAINMYERGO'] = '';
$izsauktProduktu = false;
$izsauktReklamu = true;
//if($this->ir_online_apturets()){
// $this->olnProdukts = false;
//}
if ($this->olnProdukts !== false) {
switch (trim($this->olnProdukts.'/'.$this->onlineProductSubCode, '/')) {
case 'claim':
$tmpl->vars['LANDINGMAINPRODUKTS'] = $this->pe->oci_product_list->show();
$izsauktReklamu = false;
break;
case 'claim/health/select':
$tmpl->vars['LANDINGMAINPRODUKTS'] = $this->pe->oci_product_list->show('OC_HEALTH');
$izsauktReklamu = false;
break;
case 'claim/octa/select':
$tmpl->vars['LANDINGMAINPRODUKTS'] = $this->pe->oci_product_list->show('old_OCTA');
$izsauktReklamu = false;
break;
default:
$izsauktProduktu = true;
$tmpl->vars['LANDINGMAINPRODUKTS'] = $this->izveidot_landing_main_produkts_attelojumu();
if(empty($tmpl->vars['LANDINGMAINPRODUKTS'])){
// produkts neko neatgrieza - rāda kļūdu
$tmpl_kluda = $this->tmpl->createFromFile($this->adminDIR.'/online/landing-lapa-nav-atrasta.tmpl');
$tmpl->vars['LANDINGMAINPRODUKTS'] = $tmpl_kluda->get();
} else {
// produkts kaut ko atgrieza - reklāmu nerāda
$izsauktReklamu = false;
}
}
}
if($izsauktReklamu === true){
$tmpl->vars['LANDINGMAINMYERGO'] = $this->myERGOfront->getLogInMainArea();
if (empty($tmpl->vars['LANDINGMAINMYERGO'])) {
$tmpl->vars['LANDINGMAINREKLAMA'] = $this->izveidot_landing_main_reklama_attelojumu();
if($this->sistemasParametri['online-attelot-landing-kalkulatorus'] == 10){
$tmpl->vars['LANDINGMAINPRODUKTS'] .= $this->izveidot_landing_main_calcsnippet_attelojumu();
}
} else {
if ($this->ir_online_apturets()) {
// šis template mainīgais jāaizpilda pēc produkta apstrādes
$this->olnProdukts = true;
$tmpl->vars['LANDINGMAINMYERGO'] = '';
$tmpl->vars['LANDINGMAINREKLAMA'] = $this->izveidot_landing_main_reklama_attelojumu();
if($this->sistemasParametri['online-attelot-landing-kalkulatorus'] == 10){
$tmpl->vars['LANDINGMAINPRODUKTS'] .= $this->izveidot_landing_main_calcsnippet_attelojumu();
}
}
}
}
return $tmpl->get();
}
private function izveidot_landing_header_attelojumu() {
$tmpl = $this->tmpl->createFromFile($this->adminDIR.'/online/landing-header.tmpl');
$tmpl->vars['START'] = dirname($_SERVER['SCRIPT_NAME']);
$tmpl->vars['OLNPATH'] = (substr($this->hostDefault,0,4)=='http'?'':'https://').rtrim($this->hostDefault, '/'); // rtrim($this->olnLinkReference, '/');
return $tmpl->get();
}
private function izveidot_landing_navigation_bar_attelojumu() {
$tmpl = $this->tmpl->createFromFile($this->adminDIR.'/online/landing-navigation-bar.tmpl');
$tmpl->vars['START'] = dirname($_SERVER['SCRIPT_NAME']);
if ( $this->myERGOfront->allowMyERGO() && ( isset($_SESSION['AUTHORIZED']) === false || $_SESSION['AUTHORIZED'] === false))
{
$block = $tmpl->getBlock('BLOCK:AUTH');
$block->vars['STARTMANSERGO'] = dirname($_SERVER['SCRIPT_NAME']).'/'.$this->olnValoda.'/iportal/login';
$block->vars['STARTMANSERGO'] = str_replace('//', '/', $block->vars['STARTMANSERGO']);
$block->parse();
}
$tmpl->vars['OLNLANGUAGE'] = $this->olnValoda;
$tmpl->vars['OLNPATH'] = rtrim($this->olnLinkReference, '/');
return $tmpl->get();
}
private function izveidot_landing_main_breadcrumbs_attelojumu(){
if ( empty($this->olnProdukts) ) return '';
$prod = end(explode('/', $this->olnProdukts));
return "Produkta ceļš priekš $prod";
}
function apstradat_atgriezuma_formas_datus(){
// inbefore atgriezums = snippet
// apstrādā atgriezuma formas datus
if(!isset($this->snippetForm))
{
$this->snippetForm = array();
}
// restore session data
$v = $this->kernel->session->get('snippetForm-autKods');
if (!empty($v))
{
$this->snippetForm['autKodsHtml'] = $v;
}
$v = $this->kernel->session->get('snippetForm-autKods-Txt');
if (!empty($v))
{
$this->snippetForm['autKodsTxt'] = $v;
}
$this->snippetForm['run'] = false;
// reseto atgriezumu formas javascript
$this->snippetForm['js'] = '';
// derīgie produkti
$this->snippetForm['prodArr'] = array('KASKO_OLN', 'OCTA_OLN');
// produktu saites, kas tiks izmantotas, lai izsauktu noteiktu produktu
$this->snippetForm['runSaites'] = array('KASKO_OLN' => 'calc/kasko', 'OCTA_OLN' => 'policy/octa');
// produktu aizpildāmie lauki lauks atgriezuma formā => lauka sadaļu ceļš produkta formā
// uzmanību - lauka sadaļu ceļa galā jāliek idi nevis id
$this->snippetForm['runLauki'] = array(
// kasko
'KASKO_OLN' => array(
// transportlīdzekļa nr lauks
array('CALCSNIPPETTLNR', '{SADCELS[61059716,61060235;61060237,61059752;75703270,61059860;61059862,61061749;61061751]IDI[LAU.Reģ.9]}'),
// personas koda / apliecības lauks
array('CALCSNIPPETREGNR', '{SADCELS[61059716,61060235;61060237,61059752;75703270,61059860;61059862,61061749;61061751]IDI[LAU.Apl.3]}'),
// autorizācijas koda lauks
array('CALCSNIPPETAUTKODS', '{SADCELS[61092862,61092864;61092866]IDI[LAU.kod.1]}'), // sadaļu ceļš ir kā no galvenās sadaļas nevis produkta
// autorizācijas koda uzglabāšanas lauks
array('@snippetForm-autKods-Txt', '{SADCELS[61092862,61092864;61092866]IDI[LAU.gko.0]}'), // sadaļu ceļš ir kā no galvenās sadaļas nevis produkta
),
// octa
'OCTA_OLN' => array(
// transportlīdzekļa nr lauks
array('CALCSNIPPETTLNR', '{SADCELS[61045789,61045915;61045917,61045918;61045920,61045930;61045932]IDI[LAU.Reģ.7]}'),
// personas koda / apliecības lauks
array('CALCSNIPPETREGNR', '{SADCELS[61045789,61045915;61045917,61045918;61045920,61045930;61045932]IDI[LAU.Apl.0]}'),
// autorizācijas koda lauks
array('CALCSNIPPETAUTKODS', '{SADCELS[61092862,61092864;61092866]IDI[LAU.kod.1]}'), // sadaļu ceļš ir kā no galvenās sadaļas nevis produkta
// autorizācijas koda uzglabāšanas lauks
array('@snippetForm-autKods-Txt', '{SADCELS[61092862,61092864;61092866]IDI[LAU.gko.0]}'), // sadaļu ceļš ir kā no galvenās sadaļas nevis produkta
// inv
array('CALCSNIPPETINV', '{SADCELS[61045789,61045915;61045917,61045918;61045920,61045930;61045932]IDI[LAU.Inv.4]}'),
// inv nr
array('CALCSNIPPETINVNR', '{SADCELS[61045789,61045915;61045917,61045918;61045920,61045930;61045932]IDI[LAU.Inv.5]}'),
),
);
// pogas Aprēķināt sadaļu ceļš, pogai jābūt aktivitātei CLC klikšķis, kas izsauc sarakstu
$this->snippetForm['runPoga'] = array(
'KASKO_OLN' => '{SADCELS[61059716,61060235;61060237,61059903;77716891]IDI[LAU.Apr.4]}',
'OCTA_OLN' => '{SADCELS[61045789,61045915;61045917,61045918;61045920,61046086;61046088]IDI[LAU.Apr.1]}',
);
// linki
$this->snippetForm['lnkArr'] = array('KASKO_OLN' => 'kaskolnk', 'OCTA_OLN' => 'octalnk');
// autorizācijas kods
$this->snippetForm = $this->add_aut_code_to_snippet($this->snippetForm);
// lauki, kurus apstrādāt
$this->snippetForm['lauki'] = array('CALCSNIPPETTLNR', 'CALCSNIPPETREGNR', 'CALCSNIPPETAUTKODS', '@snippetForm-autKods-Txt', 'CALCSNIPPETINV', 'CALCSNIPPETINVNR');
// ciklā apstrādā derīgos produktus
foreach($this->snippetForm['prodArr'] as $k => $prodKods){
// poga jauns kods
if(isset($_REQUEST['CALCSNIPPETAUTKODSJAUNS']) && $_REQUEST['CALCSNIPPETAUTKODSJAUNS'] == $prodKods){
// reseto autorizācijas kodu
unset($this->snippetForm['autKodsHtml']);
// pievieno javascript, lai fokusētu attiecīgo pogu
$this->snippetForm['js'] .= '$(\'#'.$this->snippetForm['lnkArr'][$prodKods].'\').trigger(\'click\');';
$this->snippetForm['js'] .= '$(\'#CALCSNIPPETPOGAAPREKINAT\').focus().blur();';
}
// inv click OCTA_OLN
if (isset($_REQUEST['CALCSNIPPETRUNPROD']) && $_REQUEST['CALCSNIPPETRUNPROD'] == $prodKods && $prodKods == 'OCTA_OLN'
&& isset($_REQUEST['CALCSNIPPETINV'.$prodKods]) && $_REQUEST['CALCSNIPPETINV'.$prodKods] > 0) {
$this->snippetForm['clickPoga'][$prodKods][] = '{SADCELS[61045789,61045915;61045917,61045918;61045920,61045930;61045932]IDI[LAU.Inv.4]}';
}
// poga aprēķināt
if(isset($_REQUEST['CALCSNIPPETRUNPROD']) && $_REQUEST['CALCSNIPPETRUNPROD'] == $prodKods){
// uzstāda pazīmi, ka jāpalaiž attiecīgais produkts
$this->snippetForm['run'] = $prodKods;
}
// apstrādā datu laukus
foreach($this->snippetForm['lauki'] as $k1 => $lauks){
// check field type
if (substr($lauks, 0, 1) == '@') {
// get value from session variable
$this->snippetForm['val'][$lauks.$prodKods] = trim($this->session->get(substr($lauks, 1)));
} else {
// get value from request
if(isset($_REQUEST[$lauks.$prodKods])){
$this->snippetForm['val'][$lauks.$prodKods] = trim($_REQUEST[$lauks.$prodKods]);
}else{
$this->snippetForm['val'][$lauks.$prodKods] = '';
}
}
}
}
}
private function izveidot_landing_main_calcsnippet_attelojumu(){
// tekošā valoda
$valKods = mb_strtoupper($this->olnValoda, 'UTF8');
// izveido landing lapas kalkulatoru atgriezumu
$tmpl = $this->tmpl->createFromFile($this->adminDIR.'/online/landing-calcsnippet.tmpl');
// atgriezumu logu ciļņu virsraksti
// kasko
$tmpl->vars['CALCSNIPPETAPREKINICENUTXTKASKO'] = $this->getPdSistemParam('DEF.Kas.2', 'Land.Tab.Virsr', $valKods);
// octa
$tmpl->vars['CALCSNIPPETAPREKINICENUTXTOCTA'] = $this->getPdSistemParam('DEF.Oct.22', 'Land.Tab.Virsr', $valKods);
// product paths
$this->addProductPaths($tmpl);
// autorizācijas kods
$this->snippetForm = $this->add_aut_code_to_snippet($this->snippetForm);
// kalkulatoru atgriezumi
// kasko
$tmpl->vars['CALCSNIPPETLOGSKASKO'] = $this->izveidot_landing_main_calcsnippet_logs_attelojumu('DEF.Kas.2', 'KASKO_OLN', $valKods);
// octa
$tmpl->vars['CALCSNIPPETLOGSOCTA'] = $this->izveidot_landing_main_calcsnippet_logs_attelojumu('DEF.Oct.22', 'OCTA_OLN', $valKods);
// poga abiem atgriezumiem viena un tā pati
$tmpl->vars['CALCSNIPPETPOGAAPREKINAT'] = $this->getPdProdTulk('DEF.Oct.22', 'OCTA_OLN', $valKods, 'LAU.Apr.1', 'VIRS');
// izveido html
return $tmpl->get().'<script type="text/javascript">function snippetFormJs(){'.$this->snippetForm['js'].'}</script>';
}
/**
* Add / reset authorization code to snippet form data
* @param array snippet form data structure
*/
public function add_aut_code_to_snippet($snippet) {
if ((!isset($this->snippetForm['autKodsHtml']))
|| (!isset($this->snippetForm['autKodsTxt']))
|| (empty($this->snippetForm['autKodsHtml']))
|| (empty($this->snippetForm['autKodsTxt']))
)
{
$snippet['autKodsTxt'] = $this->generet_autorizacijas_koda_txt();
}
$snippet['autKodsImg'] = $this->izveidot_autorizacijas_koda_attelu($snippet['autKodsTxt'], 75, 22);
$snippet['autKodsHtml'] = $this->software_handled_picture->html($this->olnLinkReference, $snippet['autKodsImg']);
$this->session->set('snippetForm-autKods', json_encode(array($snippet['autKodsTxt'], $snippet['autKodsImg'])));
$this->session->set('snippetForm-autKods-Txt', $snippet['autKodsTxt']);
return $snippet;
}
private function izveidot_landing_main_calcsnippet_logs_attelojumu($prodIdi, $prodKods, $valKods) {
// izveido landing lapas kalkulatora atgriezuma logu pēc produkta idi, produkta koda un valodas koda
$idiArr = array(
'KASKO_OLN' => array('TLNR' => 'LAU.Reģ.9', 'CODE' => 'LAU.Apl.3', 'AUTK' => 'LAU.Jau.23', ),
'OCTA_OLN' => array('TLNR' => 'LAU.Reģ.7', 'CODE' => 'LAU.Apl.0', 'AUTK' => 'LAU.kod.1', 'INV' => 'LAU.Inv.4', 'INVNR' => 'LAU.Inv.5'),
);
// izveido atgriezuma logu
$tmpl = $this->tmpl->createFromFile($this->adminDIR.'/online/landing-calcsnippet-logs.tmpl');
// kalkulatora atgriezuma teksts
$tmpl->vars['CALCSNIPPETAIZPILDITTXT'] = $this->getPdSistemParam($prodIdi, 'Land.Tab.Apr.Txt', $valKods);
// lauka virsraksts transportlīdzekļa regjistrācijas numurs
$tmpl->vars['CALCSNIPPETTLNRTXT'] = $this->getPdProdTulk($prodIdi, $prodKods, $valKods, $idiArr[$prodKods]['TLNR'], 'VIRS');
// lauka paraksts transportlīdzekļa regjistrācijas numura
if($prodKods == 'OCTA_OLN'){
// tl nr pieraksts
$tmpl->vars['CALCSNIPPETTLNRPIERTXT'] = $this->getPdProdTulk($prodIdi, $prodKods, $valKods, 'LAU.Reģ.7', 'LPIEM');
// invalīda apliecība
$tmpl->vars['CALCSNIPPETINVTXT'] = $this->getPdProdTulk($prodIdi, $prodKods, $valKods, $idiArr[$prodKods]['INV'], 'VIRS');
// invalīda apliecības numurs
$tmpl->vars['CALCSNIPPETINVNRTXT'] = $this->getPdProdTulk($prodIdi, $prodKods, $valKods, $idiArr[$prodKods]['INVNR'], 'VIRS');
// inv nr pieraksts
$tmpl->vars['CALCSNIPPETINVNRPIERTXT'] = $this->getPdProdTulk($prodIdi, $prodKods, $valKods, 'LAU.Inv.5', 'LPIEM');
}else{
$tmpl->vars['CALCSNIPPETTLNRPIERTXT'] = '';
$tmpl->vars['CALCSNIPPETINVTXT'] = '';
$this->snippetForm['js'] .= '$(\'#TLNRPIER'.$prodKods.'\').remove();';
$this->snippetForm['js'] .= '$(\'#INV'.$prodKods.'\').remove();';
$this->snippetForm['js'] .= '$(\'#DIVINVNR'.$prodKods.'\').remove();';
}
// lauka virsraksts personas kods / apliecības numurs
$tmpl->vars['CALCSNIPPETREGNRTXT'] = $this->getPdProdTulk($prodIdi, $prodKods, $valKods, $idiArr[$prodKods]['CODE'], 'VIRS');
// teksts autorizācijas kods
$tmpl->vars['CALCSNIPPETAUTKODSPAZTXT'] = $this->getPdProdTulk($prodIdi, $prodKods, $valKods, 'LAU.I: .0', 'KP');
// lauka virsraksts autorizācijas kods
$tmpl->vars['CALCSNIPPETAUTKODSTXT'] = $this->getPdProdTulk($prodIdi, $prodKods, $valKods, 'LAU.kod.1', 'VIRS');
// poga jauns kods
$tmpl->vars['CALCSNIPPETJAUNSKODSBUTTONTXT'] = $this->getPdProdTulk($prodIdi, $prodKods, $valKods, 'LAU.Jau.23', 'VIRS');
// produkta kods, kas atšķiro dažādu produktu logu laukus
$tmpl->vars['CALCSNIPPETPROD'] = $prodKods;
// paskaidrojums transportlīdzekļa regjistrācijas numurs
$this->snippetForm['js'] .= 'pdjsLauHint(\'CALCSNIPPETTLNR'.$prodKods.'\', \''.$this->getPdProdTulk($prodIdi, $prodKods, $valKods, $idiArr[$prodKods]['TLNR'], 'PASK').'\');';
// paskaidrojums personas kods / apliecības numurs
$this->snippetForm['js'] .= 'pdjsLauHint(\'CALCSNIPPETREGNR'.$prodKods.'\', \''.$this->getPdProdTulk($prodIdi, $prodKods, $valKods, $idiArr[$prodKods]['CODE'], 'PASK').'\');';
// paskaidrojums autorizācijas kods
$this->snippetForm['js'] .= 'pdjsLauHint(\'CALCSNIPPETJAUNSKODS'.$prodKods.'\', \''.$this->getPdProdTulk($prodIdi, $prodKods, $valKods, $idiArr[$prodKods]['AUTK'], 'PASK').'\');';
// autorizācijas kods
$tmpl->vars['CALCSNIPPETAUTKODSHTML'] = $this->snippetForm['autKodsHtml'];
// paskaidrojums invalīda apliecība
if (isset($idiArr[$prodKods]['INV'])) $this->snippetForm['js'] .= 'pdjsLauHint(\'CALCSNIPPETINV'.$prodKods.'\', \''.$this->getPdProdTulk($prodIdi, $prodKods, $valKods, $idiArr[$prodKods]['INV'], 'PASK').'\');';
// paskaidrojums invalīda apliecības numurs
if (isset($idiArr[$prodKods]['INVNR'])) $this->snippetForm['js'] .= 'pdjsLauHint(\'CALCSNIPPETINVNR'.$prodKods.'\', \''.$this->getPdProdTulk($prodIdi, $prodKods, $valKods, $idiArr[$prodKods]['INVNR'], 'PASK').'\');';
// pievieno lauku vērtības
foreach($this->snippetForm['lauki'] as $k1 => $lauks){
$this->snippetForm['js'] .= '$(\'#PDLAUKS'.$lauks.$prodKods.'\').val(\''.addslashes($this->apstradat_restes($this->snippetForm['val'][$lauks.$prodKods], false)).'\');';
}
// izveido html
return $tmpl->get();
}
function getPdSistemParam($prodIdi, $paramKods, $valKods){
// atrod sistēmas parametru pēc produkta idi, parametra koda un valodas koda
$sql = ''
.' select vertibaSpec, vertibaSpecLidz, vertibaSpecNo, vertiba from pdsistemparamv v inner join pdsistemparam p on p.id = v.idsistemparam '
.' where v.iddsvalodaskods = "'.mysql_real_escape_string($valKods).'" '
.' and p.kods = "'.mysql_real_escape_string($paramKods).'" '
.' and((p.prod_idi is null and not exists( '
.' select 1 from pdsistemparamv v1 inner join pdsistemparam p1 on p1.id = v1.idsistemparam '
.' where v1.iddsvalodaskods = "'.mysql_real_escape_string($valKods).'" '
.' and p1.kods = "'.mysql_real_escape_string($paramKods).'" '
.' and p1.prod_idi = "'.mysql_real_escape_string($prodIdi).'")) '
.' or p.prod_idi = "'.mysql_real_escape_string($prodIdi).'") '
;
$ret = '';
if ($this->kernel->db) {
$r = $this->kernel->db->query($sql);
if ($r && $r->numRows()) {
$r = $r->getRows();
if (!is_array($r) || !isset($r[0]) || !isset($r[0]['vertiba'])) {
// parametrs nav atrasts
$ret = '';
} else {
// parametrs ir atrasts
if (isset($r[0]['vertibaSpecNo']) && isset($r[0]['vertibaSpecLidz']) && time() >= strtotime($r[0]['vertibaSpecNo']) && time() <= strtotime($r[0]['vertibaSpecLidz'])) {
$ret = $r[0]['vertibaSpec'];
} else {
$ret = $r[0]['vertiba'];
}
}
}
}
return $this->makeTextToHtmlText($ret);
}
function getPdProdTulk($prodIdi, $prodKods, $valKods, $itlIdi, $txtVeids){
// atrod produkta tulkojumu pēc produkta koda, valodas koda, ITL lauka idi un teksta veida
$sql = ''
.' select tulkojums from dsLaukXproXvalXveids '
.' where idi = "'.mysql_real_escape_string($itlIdi).'" '
.' and pro_kods = "'.mysql_real_escape_string($prodKods).'" '
.' and txt_veids = "'.mysql_real_escape_string($txtVeids).'" '
.' and val_kods = "'.mysql_real_escape_string($valKods).'" '
.' order by id desc limit 1 '
;
if ($this->kernel->db) {
$r = $this->kernel->db->query($sql);
if ($r && $r->numRows()) {
$r = $r->getRows();
if(!is_array($r) || !isset($r[0]) || !isset($r[0]['tulkojums'])){
// parametrs nav atrasts
$ret = '';
}else{
// parametrs ir atrasts
$ret = $r[0]['tulkojums'];
}
}
}
// apstrādā parametrus
$ANTICIKLS = 0;
while(strpos($ret, '{P[') !== false){
$ANTICIKLS++;
$i1 = strpos($ret, '{P[');
$i2 = strpos($ret, ']}', $i1);
$s = substr($ret, $i1, $i2 - $i1 + 2);
$s1 = $s;
if(substr($s1, 0, 8) == '{P[@SYS.'){
// sistēmas parametrs
$s1 = substr($s1, 8);
$s1 = left($s1, mb_strlen($s1, 'UTF8') - 2);
$s1 = $this->getPdSistemParam($prodIdi, $s1, $valKods);
}else{
// cits parametrs - vērtība ir tukša
$s1 = '';
}
$ret = str_replace($s, $s1, $ret);
if($ANTICIKLS > 100)break;
}
// atgriež apstrādātu tekstu
return $this->apstradat_restes(htmlspecialchars($ret), false);
}
function generet_autorizacijas_koda_txt(){
// gjenerē autorizācijas koda teksta virkni
for($formula_i=0;$formula_i<4;$formula_i++)
while(true){
$formula_r[$formula_i]=rand(48,122);
if($formula_r[$formula_i]>=48)if($formula_r[$formula_i]<=57)break;
if($formula_r[$formula_i]>=65)if($formula_r[$formula_i]<=90)break;
if($formula_r[$formula_i]>=97)if($formula_r[$formula_i]<=122)break;
}
$ret = chr($formula_r[0]).chr($formula_r[1]).chr($formula_r[2]).chr($formula_r[3]);
$ret = str_replace("1","a",$ret);
$ret = str_replace("l","C",$ret);
$ret = str_replace("0","N",$ret);
$ret = str_replace("o","H",$ret);
$ret = str_replace("O","z",$ret);
$ret = str_replace("I","v",$ret);
return $ret;
}
function izveidot_autorizacijas_koda_attelu($pTeksts, $pWidth, $pHeight){
// izveido autorizācijas koda attēlu
$att = imagecreatetruecolor($pWidth, $pHeight);
$background = imagecolorallocate($att, 250, 250, 248);
imagefilledrectangle($att,0,0,$pWidth,$pHeight,$background);
$colbg[0] = imagecolorallocate($att, 225, 221, 221);
$colbg[1] = imagecolorallocate($att, 253, 246, 246);
$colbg[2] = imagecolorallocate($att, 219, 219, 219);
$colbg[3] = imagecolorallocate($att, 213, 234, 246);
for($i1 = 0; $i1 < 20; $i1++){
if($i1 == 0){
$rx = -10;
$ry = 11;
}else{
if($i1 == 1){
$rx = 85;
$ry = 11;
}else{
if($i1 == 2){
$rx = 42;
$ry = 11;
}else{
$rx = rand(0, 95) - 10;
$ry = rand(0, 42) - 10;
}
}
}
$bx = rand(10, 100);
$by = rand(10, 100);
$dyn = 5;
for($i = 0; $i < $dyn; $i++){
$rcc= rand(0, 3);
$zx = $bx / $dyn * $i;
$zy = $by / $dyn * $i;
imageellipse($att, $rx, $ry, $zx, $zy, $colbg[$rcc]);
imageellipse($att, $rx, $ry, $zx+1, $zy, $colbg[$rcc]);
imageellipse($att, $rx, $ry, $zx, $zy+1, $colbg[$rcc]);
imageellipse($att, $rx, $ry, $zx+1, $zy+1, $colbg[$rcc]);
}
}
$step = $pWidth / 4;
for($i = 0; $i < 4; $i++){
$coltxt = imagecolorallocate($att, rand(80, 130), rand(80, 130), rand(80, 130));
$degree = rand(-30,30);
$fontfile = ADMIN_DIR."/pd/dz/res/font.ttf";
$fontsize = rand(12,16);
imagettftext($att, $fontsize, $degree,4 + $i * $step, round(1+$pHeight*27/40),$coltxt, $fontfile,substr($pTeksts, $i, 1));
}
$fname = $this->cfg['pdfDir'].'/'.md5($pTeksts);
imagepng($att, $fname);
imagedestroy($att);
$imgbinary = fread(fopen($fname, "r"), filesize($fname));
unlink($fname);
$ret = 'data:image/png;base64,'.base64_encode($imgbinary);
return $ret;
}
function makeTextToHtmlText($txt){
// pārveido tekstu par html tekstu pēc dzinēja principiem
return addcslashes(htmlspecialchars($txt), '\'"');
}
public function izveidot_landing_main_reklama_attelojumu(){
$tmpl = $this->tmpl->createFromFile($this->adminDIR.'/online/landing-main-reklama.tmpl');
// pielieku rotējošās bildes
$out = '';
$dir = 'online/images/lv/scroll';
$files = scandir($this->adminDIR."/".$dir);
for ($i=0; $i<count($files); $i++)
if (!is_file($dir.'/'.$files[$i])) unset($files[$i]);
$files = array_values($files);
$imgCount = count($files);
// drīkst būt max 5 bildes
if ($imgCount > 5) $imgCount = 5;
for ($i=0; $i<$imgCount; $i++)
$out .= "<div><a href='#'><img src='$dir/$files[$i]' alt='Insurance product'></a></div>\n";
$tmpl->vars['SCROLLER'] = $out;
$tmpl->vars['LANDINGMAINREKLAMAPROD'] = $this->izveidot_landing_main_reklama_prodpogas_attelojumu();
return $tmpl->get();
}
public function izveidot_landing_main_reklama_prodpogas_attelojumu(){
$tmpl = $this->tmpl->createFromFile($this->adminDIR.'/online/landing-main-reklama-prod.tmpl');
$this->addProductPaths($tmpl);
$tmpl->vars['OCTAIRAKCIJA'] = $this->getSystemParam('ir-akcija', 'DEF.Oct.22') == 1? 'discount' : 'none';
$tmpl->vars['OCTAATLAIDE'] = $this->getSystemParam('atlaide', 'DEF.Oct.22');
$tmpl->vars['CELOJIRAKCIJA'] = $this->getSystemParam('ir-akcija', 'DEF.Ceļ.0') == 1? 'discount' : 'none';
$tmpl->vars['CELOJATLAIDE'] = $this->getSystemParam('atlaide', 'DEF.Ceļ.0');
$tmpl->vars['NEKIPIRAKCIJA'] = $this->getSystemParam('ir-akcija', 'DEF.Īpa.0') == 1? 'discount' : 'none';
$tmpl->vars['NEKIPATLAIDE'] = $this->getSystemParam('atlaide', 'DEF.Īpa.0');
return $tmpl->get();
}
// pārbauda, vai pieprasītais id ir sesijas polišu id masīvā
private function parbaudit_pieprasitas_polises_id($id){
$ret = false;
if(empty($id)){
$ret = true;
}else{
$sesPolIdArr = $this->session->get('onlinePolisesIdMasivs');
if(!empty($sesPolIdArr)){
$sesPolIdArr = json_decode($sesPolIdArr, true);
if(is_array($sesPolIdArr) && count($sesPolIdArr) > 0){
// masīvs ir ok - apskatās, vai ir polises id
if(in_array($id, $sesPolIdArr)){
$ret = true;
}
}
}
}
return $ret;
}
/**
* Add requested policy instance id to security array
* @param int $id policy instance id
*/
public function pievienot_pieprasitas_polises_id($id){
$sesPolIdArr = $this->session->get('onlinePolisesIdMasivs');
if(!empty($sesPolIdArr)){
$sesPolIdArr = json_decode($sesPolIdArr, true);
if(!is_array($sesPolIdArr)){
$sesPolIdArr = array();
}
}else{
$sesPolIdArr = array();
$this->session->set('online_partner_policy', $id);
}
if(!in_array($id, $sesPolIdArr)){
$sesPolIdArr[] = $id;
$this->session->set('onlinePolisesIdMasivs', json_encode($sesPolIdArr));
}
}
/**
* Remove requested policy instance id from security array
* @param int $id policy instance id
*/
public function remove_instance_security_id($id) {
$sesPolIdArr = $this->session->get('onlinePolisesIdMasivs');
if(!empty($sesPolIdArr)){
$sesPolIdArr = json_decode($sesPolIdArr, true);
if(!is_array($sesPolIdArr)){
$sesPolIdArr = array();
}
}else{
$sesPolIdArr = array();
}
$i = array_search($id, $sesPolIdArr);
if ($i !== false) {
$sesPolIdArr[$i] = 0;
$this->session->set('onlinePolisesIdMasivs', json_encode($sesPolIdArr));
}
}
/**
* Call engine product with framework activity
*/
private function processFrameworkActivity() {
$this->online_relog_anonymous_user($this->online_partner->get_id_user());
$this->online_nolasit_parametrus();
return $this->izveidot_landing_main_produkts_attelojumu();
}
/**
* Call engine product and get html
*/
private function izveidot_landing_main_produkts_attelojumu() {
$out = '';
// atlasa produkta definīcijas idi pēc produkta online linka nosaukuma
$productCode = $this->olnProdukts;
$sql = 'select i.idi idi,x.kodspro kods from pdsarpro p inner join pdsardefxpro x on x.kodspro = p.kods'
.' inner join pdnobji i on i.id = x.iddef where upper(p.olnlinkname) = upper("'.$this->olnProdukts.'") and irOnlineProd = 1';
if ($this->kernel->db) {
$r = $this->kernel->db->query($sql);
if ($r) {
$r = $r->getRows();
if(!is_array($r) || !isset($r[0]) || !isset($r[0]['idi'])){
if ($this->ir_online_apturets() == false) {
// tāds produkta idi nav atrasts
$this->olnProdukts = false;
}
$defIekIdi = '';
}else{
// produkta idi ir atrasts
$defIekIdi = $r[0]['idi'];
$this->produktaKods = $r[0]['kods'];
}
}
}
// nosaka veicamo darbību
if($this->olnProdukts !== false){
$action = '';
$actionID = '';
include $this->adminDIR.'/pd/dz/koredz.php';
$_REQUEST['PDDEFIEKID'] = $defIekIdi;
if($this->olnInstancesParametrs !== false){
// ir norādīts izpildāmais darbību saraksts esošai instancei
$_REQUEST['PDDEFIEKID'] = $defIekIdi;
$_REQUEST['PDPOLSISID'] = $this->olnInstance;
$_REQUEST['PDID'] = $this->olnInstance;
$action = 'PDIZPDARSAR';
$actionID = $this->olnInstancesParametrs;
}else{
if($this->olnInstance !== false){
// atvērt esošu instanci pēc id
$_REQUEST['PDPOLSISID'] = $this->olnInstance;
$_REQUEST['PDID'] = $this->olnInstance;
$action = 'PDPOLSISID';
}else{
// jauna polise
$_REQUEST['PDPOLSISID'] = '';
$_REQUEST['PDID'] = '';
$action = 'PDDEFIEKID';
$actionID = '';
// check and process partner data which will be passed to engine
$this->online_partner->fill_partner_data($this->snippetForm);
}
}
// framework activity
if (isset($this->frameworkActivity)) {
$action = 'frameworkActivity';
$actionId = $this->frameworkActivity;
}
$pieprPolId = $this->olnInstance; // pieprasītās polises id
$previousPolicyId = $pieprPolId;
// check if this is redirect
if (isset($_SESSION['engineFrameworkOutput'][$pieprPolId])) {
$out .= $_SESSION['engineFrameworkOutput'][$pieprPolId];
$this->runtimeFrameworkName = $_SESSION['runtimeFrameworkName'][$pieprPolId];
unset($_SESSION['engineFrameworkOutput'][$pieprPolId]);
unset($_SESSION['runtimeFrameworkName'][$pieprPolId]);
return $out;
}
// apskatās, vai nav apturēts
$this->olnLietotajaDarbibaJaaptur = false;
$this->olnInstanceIrSaveOffer = false;
if($this->ir_online_apturets()){
$this->olnLietotajaDarbibaJaaptur = true;
if(!empty($pieprPolId)){
// apskatās, vai instancei ir saveoffer
// atlasa instances statusu
$sql = '/*kernel960*/select status "0" from pdsarpol_oln where polises_id='.$pieprPolId;
$r = $this->kernel->db->query($sql)->getRows();
if(is_array($r) && isset($r[0])){
// apskatās, vai statuss ir saveoffer, vai tālāk
if($r[0] >= 1){
// ir veiksmīgs saveoffer vai tālāk
$this->olnLietotajaDarbibaJaaptur = false;
$this->olnInstanceIrSaveOffer = true;
}
}
}
}
if(!isset($this->olnLietotajaDarbibaJaaptur) || $this->olnLietotajaDarbibaJaaptur === false){
$this->olnInstance = false;
$this->olnInstancesParametrs = false;
$this->olnDefIekIdi = $defIekIdi;
if($this->parbaudit_pieprasitas_polises_id($pieprPolId) // pieprasītās polises id ir saglabāts sesijā, vai arī jauna polise
|| $this->callMode == 'silent' // ja palaists no konsoles, tad atļauts atvērt visas polises
){
$this->dz = new pdkoredzComp($this, $action, $actionID); // izpilda polises apstrādi dzinējā
$this->olnInstance = $this->dz->ins->idins;
if(empty($pieprPolId)){
$this->pievienot_pieprasitas_polises_id($this->dz->ins->idins); // pievieno polises id sesijas mainīgajam
$this->online_reg_proc_action($this->dz->ins->idins, 'sākta jauna polise');
$this->online_partner->use_new_policy();
}
}
}else{
// atgriež tukšumu, bet nereseto produktu
return '';
}
}
// create output
$out .= (isset($this->dz)?$this->dz->out:'');
// check framework
if (isset($this->dz)) {
if (isset($this->dz->ins->fw['show'])) {
// redirect to link with policy id
if ('['.$previousPolicyId.']' != '['.$this->dz->ins->idins.']') {
// store framework into session
$_SESSION['engineFrameworkOutput'][$this->dz->ins->idins] = $out;
$_SESSION['runtimeFrameworkName'][$this->dz->ins->idins] = $this->runtimeFrameworkName;
// redirect to link with instance number at the end
$url = $this->olnLinkReference.'/'.$this->olnValoda.'/'.$this->olnProdukts.'/'.$this->dz->ins->idins;
$this->header_redirect($url, false);
}
}
}
return $out;
}
/**
* Atgriež sistēmas parametra vērtību norādītajam produktam
* Ja nav norādīts definīcijas idi, atgriež globālo parametra vērtību
* @param string $param sistēmas parametra nosaukums
* @param string $defidi produkta definicījas idi
* @return string sistēmas parametra vērtība
*/
public function getSystemParam($param, $defidi = '') {
$sql = 'select v.vertibaSpec,v.vertibaSpecNo,v.vertibaSpecLidz, v.vertiba, isnull(p.prod_idi) as ord from pdsistemparam p join pdsistemparamv v on p.id=v.idsistemparam
where p.kods="'.$param.'" and (prod_idi = "'.$defidi.'" or p.prod_idi is null) order by ord';
if ($this->kernel->db) {
$r = $this->kernel->db->query($sql);
if ($r && $r->numRows()) {
$res = $r->getRows();
if ( isset($res[0]) ) {
if ((isset($res[0]['vertibaSpecNo']) && !empty($res[0]['vertibaSpecNo']))
&& (isset($res[0]['vertibaSpecLidz']) && !empty($res[0]['vertibaSpecNo']))
&& time() >= strtotime($res[0]['vertibaSpecNo']) && time() <= strtotime($res[0]['vertibaSpecLidz'])) {
return $res[0]['vertibaSpec'];
} else {
return $res[0]['vertiba'];
}
}
}
}
else return '';
}
/**
* Pievieno padotajam šablonam ceļus uz produktiem.
* Šablonā jābūt %IWOLNPATH/%IWOLNLANGUAGE/%IWOLNPROD + produkta kods no pdsarpro.
* @param tmplNode $tmpl šablona objekts
*/
public function addProductPaths(tmplNode $tmpl) {
$tmpl->vars['OLNPATH'] = rtrim($this->olnLinkReference, '/');
$tmpl->vars['OLNLANGUAGE'] = $this->olnValoda;
$sql = 'select kods "0", olnlinkname "1" from pdsarpro where irOnlineProd = 1 and olnlinkname is not null';
if ($this->kernel->db) {
$r = $this->kernel->db->query($sql);
if ($r && $r->numRows()) {
$r = $r->getRows();
if(!is_array($r) || !isset($r[0]) || !isset($r[0]['idi'])){
foreach($r as $l){
$tmpl->vars['OLNPROD'.$l[0]] = $l[1];
}
}
}
}
}
/**
* Atgriež pieprasījumu ar kuru tiek atvērta tekošā lapa.
* Pieprasījums nesatur instances un sarakstu idus.
* @param $lang - pazīme vai pieprasījumu vajag ar valodu
* @return string
* @author Andrejs Petrovs
*/
public function getQueryPath($lang = false) {
if (empty($_SERVER['QUERY_STRING'])) return;
$q_path = explode('&', $_SERVER['QUERY_STRING']);
$q_path1 = preg_grep('/query=/', $q_path);
$q_path = end($q_path1);
if (empty($q_path)) return;
$q_path1 = explode('=', $q_path);
$q_path = end($q_path1);
$q_path = preg_replace('/\/\d+/', '', $q_path);
if (!$lang && preg_match('/^[a-z]{2}\//i', $q_path))
$q_path = preg_replace('/^.{3}/', '', $q_path);
return $q_path;
}
// nolasa atslēgas vērtību no masīva, nav case sensitive
public function getArrayKeyValue($arr, $key){
$key = strtoupper($key);
$ret = '';
if(is_array($arr)){
foreach($arr as $key1 => $val){
if(is_array($val)){
$ret = $this->getArrayKeyValue($val, $key);
}else{
if(strtoupper($key1) == $key){
$ret = $val;
break;
}
}
}
}else{
$ret = '';
}
return $ret;
}
// nolasa polises numuru no dis izsaukuma rezultāta, ko vēlak pievieno logam
// ja polises numurs nav atrasts, tad uzstāda tukšumu
public function getLogPoliceNr($r1, $r2){
$r1 = json_encode($r1);
$r1 = json_decode($r1, true);
$polNr = $this->getArrayKeyValue($r1, 'policyNumber');
$polSe = $this->getArrayKeyValue($r1, 'policySerie');
if(empty($polNr)){
$polNr = $this->getArrayKeyValue($r1, 'policyOfferNumber');
$polSe = $this->getArrayKeyValue($r1, 'policyOfferSerie');
if(empty($polNr)){
if (isset($r2['fileData'])) {
unset($r2['fileData']);
}
$r2 = json_encode($r2);
$r2 = json_decode($r2, true);
$polNr = $this->getArrayKeyValue($r2, 'policyNumber');
$polSe = $this->getArrayKeyValue($r2, 'policySerie');
if(empty($polNr)){
$polNr = $this->getArrayKeyValue($r2, 'policyOfferNumber');
$polSe = $this->getArrayKeyValue($r2, 'policyOfferSerie');
}
}
}
if(empty($polNr)){
$this->logPolisesNr = '';
}else{
$this->logPolisesNr = 'polNr='.$polSe.$polNr.' ';
}
$this->session->set('logPolisesNr', $this->logPolisesNr);
}
// atgriež tekošo instances id un polises nr, kā teksta virkni, kas liekama
// log funkcijas skaidrojuma teksta sākumā
public function getLogInsIdPolNr(){
$ret = $this->session->get('logInstancesId').$this->session->get('logPolisesNr');
if (empty($ret) && isset($_REQUEST['serviceRequestId'])) {
$ret = 'requestId='.(int)$_REQUEST['serviceRequestId'];
}
return $ret;
}
// apstrādā restes, nejaukt ar dzinēja restēm
public function apstradat_portala_restes($virkne){
return
str_replace('#71','<i>',
str_replace('#72','</i>',
str_replace('#21','<b>',
str_replace('#22','</b>',
str_replace('#60','<br>',
str_replace(array("\r\n","\r","\n"),'#60',$virkne))))));
}
/**
* Aizvieto simbolus ar restēm ar definēto vērtību
* @param string $data teksts ar restēm
* @return string teksts ar aizvietotiem simboliem
* @author Andrejs Petrovs
*/
function apstradat_restes($data, $doRealBreak = false){
// $doRealBreak - norāda, vai #60 gadījumu pārveidot par <br>, vai "\n"
$data = str_replace(array("\r\n", "\r", "\n"), '#60', $data); // pārveido <Enterus> par <br>
$repl = array( // restu pārveidošanas masīvs
'#1' => '<br />' , '#10' => '&raquo;',
'#21' => '<b>' , '#22' => '</b>' ,
'#23' => '"',
'#31' => '<u>' , '#32' => '</u>' ,
'#41' => '<a' , '#42' => '>' ,
'#43' => '</a>' , '#44' => '</br>' ,
'#45' => '<' , '#46' => '</' ,
'#5' => '\'' ,
'#60' => (($doRealBreak === true)?"\n":'<br>'),
'#71' => '<i>' , '#72' => '</i>' ,
'#81' => '<ul>' , '#82' => '<li>' ,
'#83' => '</li>' , '#84' => '</ul>' ,
'#930' => '<h3>' , '#931' => '</h3>' ,
);
$data = preg_replace('/#([15]|[2][123]|[3478][12]|[48][34]|[4][56]|[6][0]|[9][3][01])/e', '$repl["\\0"]', $data); // izpilda restu pārveidošanu
$data = $this->sabojat_neatlautos_html_tagus($data);
return $data;
}
/**
* Sabojā html tagus, kas nav iekļauti atļauto tagu sarakstā
* @param unknown_type $virkne html teksts
*/
function sabojat_neatlautos_html_tagus($virkne){
if(strpos($virkne, '<') !== false){
$atlautie_tagi = array('a','b','p','i','u','h1','h2','h3','h4','ul','li','br','sup','sub','pre','br','br /','br/','span','strong','font');
$m = explode('<', $virkne);
$msk = count($m);
for($i = 1; $i < $msk; $i++){
$a = $m[$i];
if(substr($a, 0, 1) != ' '){ // tags, kas sākas ar tukšumu, nav kaitīgs
$t = strtolower($a);
$j = strpos($t, ' ');
if($j !== false){ // nogriež tagu pirms tukšuma, pārējie ir taga atribūti
$t = substr($t, 0, $j);
}
if(substr($t, 0, 1) == '/'){ // aizverošais tags
$t = substr($t, 1);
}
$j = strpos($t, '>');
if($j !== false){
$t = substr($t, 0, $j);
}
if(in_array($t, $atlautie_tagi) === false){ // tags nav atļauts, sabojā
$m[$i] = ' '.$a;
}
}
}
$virkne = implode('<', $m);
}
return $virkne;
}
// pievieno sesijas masīvam polises numuru, kuru ir atļauts atvērt
public function atlauts_polises_nr_pievienot($nr){
if(substr($nr, 0, 1) == 'O' || substr($nr, 0, 1) == 'J'){
$nr = substr($nr, 1);
}
$m = $this->session->get('atlautiePolisesNr');
if(empty($m)){
$m = array();
}else{
$m = json_decode($m, true);
}
if(!in_array($nr, $m)){
$m[] = $nr;
}
$this->session->set('atlautiePolisesNr', json_encode($m));
return true;
}
// pārbaude, vai ir atļauts atvērt polisi ar doto numuru
public function atlauts_polises_nr_parbaude($nr){
$m = $this->session->get('atlautiePolisesNr');
if(empty($m)){
$m = array($nr);
}else{
$m = json_decode($m, true);
}
$ret = empty($nr) || in_array($nr, $m);
return $ret;
}
// notīra atļauto polišu sarakstu
public function atlauts_polises_nr_dzest_visu(){
$this->session->set('atlautiePolisesNr', json_encode(array()));
return true;
}
// saglabā sesijas mainīgajā pēdējo pieprasīto id
public function atlauts_polises_nr_pedejais_action_id(){
$ir_label = false;
$ir_action_id = false;
$ir_dzinejs = false;
$ir_saglabat_ka = false;
$pedejais_action_id = '';
foreach($_REQUEST as $k => $v){
if(strtoupper($k) == 'ACTIONID'){
$pedejais_action_id = $v;
//$ir_action_id = $v;
}
// cita label izsaukums
if(strtoupper($k) == 'LABEL'
|| (strtoupper($k) == 'ACTION'
&& strtoupper($v) !== 'CLICK'
)){
$ir_label = true;
}
// dzinēja darbības izsaukums
if(strtoupper($k) == 'ACTION' && substr(strtoupper($v),0,2) == 'PD' && strtoupper($k) != 'KOPETPOLISI'){
// saglabāt kā gadījum
substr(strtoupper($v),0,2) == $ir_dzinejs = true;
}
// dzinēja polises izsaukums
if(strtoupper($k) == 'PDDEFIEKID'){
$this->session->set('pedejais_action_pddefiekid', $v);
}
// dzinēja saglabāt kā izsaukums
if(strtoupper($k) == 'VECASPOLISESID'){
// saglabāt kā iepriekšējās polises id, uz kuru jāveic pārbaude
$ir_action_id = trim($v);
}
if(strtoupper($k) != 'KOPETPOLISI'){
// saglabāt kā darbība
$ir_saglabat_ka = true;
}
if(strtoupper($k) == 'PDID'){
// saglabāt kā darbība
$ir_action_id = trim($v);
}
}
if($ir_action_id === false){
if($ir_label === true){
// cits izsaukums
$pedejais_action_id = '';
}
}else{
// polises izsaukums
if($ir_action_id !== false){
$pedejais_action_id = $ir_action_id;
}
}
$this->session->set('pedejais_action_id', $pedejais_action_id);
return true;
}
// pārbauda pēdējo action id
public function atlauts_polises_nr_parbaude_pedejais_action_id(){
return $this->atlauts_polises_nr_parbaude($this->kernel->session->get('pedejais_action_id'));
}
// atrod produkta log veidu
public function getAllLogType($returnLogin, $function, &$logGrp){
// returnLogin - pazīme, vai atrgiezt LOGIN
// function - funkcijas teksts, kas tiek logota
// logGrp - atgriež funkcijas grupas pazīmi
// pēc noklusējuma atgriež OTHER
switch($function){
case 'authorization':
case 'checkSession':
case 'dis authorization':
$logGrp = 1;
break;
default:
$logGrp = 0;
}
// IP29 iKASKO
if($this->kernel->session->get('in-imports-iKASKO') == 1){
if(isset($GLOBALS['label']) && $GLOBALS['label'] == 'imports-iKASKO'){
return 'iKASKO';
}
}
if($this->kernel->session->get('in-imports-iOCTA') == 1){
if(isset($GLOBALS['label']) && $GLOBALS['label'] == 'imports-iOCTA'){
return 'iOCTA';
}
}
// ja definīcijas idi ir saglabāts sesijā
$pdiekid = trim($this->kernel->session->get('PDDEFIEKID'));
if(empty($pdiekid)){
// ja definīcijas idi ir pieprasījumā
if(isset($_REQUEST['PDDEFIEKID']) && $_REQUEST['PDDEFIEKID']){
$pdiekid = trim($_REQUEST['PDDEFIEKID']);
}
}
if(empty($pdiekid)){
// ja definīcijas idi ir online pieprasījumā
if(isset($this->olnProduktaIdi) && $this->olnProduktaIdi !== false){
$pdiekid = $this->olnProduktaIdi;
}
}
// ja dzinēja polises id ir pieprasījumā
if((isset($_REQUEST['PDID']) && $_REQUEST['PDID'])
|| (isset($this->olnInstance) && $this->olnInstance)){
if(isset($_REQUEST['PDID']) && $_REQUEST['PDID']){
$reqId = (int)$_REQUEST['PDID'];
}else{
$reqId = (int)$this->kernel->olnInstance;
}
$sql1 = "SELECT def.kodspro as idprod FROM pdover ver, pdoins ins, pdsardefxpro def "
." where ver.id = ins.idver and def.iddef = ver.iddef and ins.id = ".$reqId." LIMIT 1";
$r = $this->kernel->db->query($sql1);
if($r && $r->numRows()){
$prod = $r->getRow();
switch(trim($prod['idprod'])){
case 'KASKO': return 'KASKO';
case 'NEKIP': return 'ESTATE361';
case 'OCTA': return 'OCTA';
case 'DZOCTA': return 'OCTA';
case 'TRIP': return 'TRIP';
case 'NELGAD': return 'NELGAD';
case 'KOMIP': return 'KOMIP';
case 'DZIV_KALK': return 'DZIV';
case 'LIFE_CALC': return 'LIFE';
case 'CELOJ_OLN': return 'CELOJ_OLN';
case 'OCTA_OLN': return 'OCTA_OLN';
case 'NEKIP_OLN': return 'NEKIP_OLN';
case 'KASKO_OLN': return 'KASKO_OLN';
case 'USER_INFO': return 'OPAL';
case 'DZAK': return 'DZAK';
case 'OC_HEALTH': return 'OC_HEALTH';
case 'S_LIFE_CLC': return 'S_LIFE_CLC';
}
}
}
switch($pdiekid){
case 'DEF.KAS.0': return 'KASKO';
case 'DEF.Nel.0': return 'NELGAD';
case 'DEF.Īp.0': return 'ESTATE361';
case 'DEF.Kom.0': return 'KOMIP';
case 'DEF.Īpa.0': return 'NEKIP_OLN';
case 'DEF.Dzī.0': return 'DZIV';
case 'DEF.ERELI.0': return 'LIFE';
case 'DEF.Oct.22': return 'OCTA_OLN';
case 'DEF.Ceļ.0': return 'CELOJ_OLN';
case 'DEF.Kas.2': return 'KASKO_OLN';
case 'DEF.Peaa.0': return 'OPAL';
case 'DEF.Icebe.0': return 'DZAK';
case 'DEF.Poche.0': return 'OC_HEALTH';
case 'DEF.OCT.2': return 'OCTA';
}
// pārbauda produkta tipu pēc labeļa
switch(trim(substr($GLOBALS['label'], 0,4))){
case 'DZka':
case 'kask': return 'KASKO';
case 'octa': return 'OCTA';
case 'trip': return 'TRIP';
case 'real': return 'ESTATE';
case 'insu': return 'ESTATE';
case 'DZre': return 'ESTATE361';
case 'DZne': return 'NELGAD';
case 'DZko': return 'KOMIP';
case 'DZdz': return 'DZIV';
case 'DZli': return 'LIFE';
case 'atsk': return 'ATSK_BLOKS';
case 'heal': return 'HEALTH_CLAIMS';
case 'dzdz': return 'DZAK';
case 'myer': return 'OPAL';
}
// check function
if (isset($_REQUEST['service'])) {
switch ($_REQUEST['service']) {
case 'lifecalculator': return 'S_LIFE_CLC';
}
}
// nekas nav atrasts, atgriež LOGIN
if($returnLogin === true){
$logGrp = 1;
return 'LOGIN';
}
//atgriež logu tipu no konfig(cfg.php) faila
if($this->sistemasParametri['sistema-funkcija'] != 20){
foreach($this->cfg['logsTypes'] as $logType => $functionsNames)
if (in_array(strtoupper($function), $functionsNames))
return $logType;
}
// atgriež noklusēto vērtību
return 'OTHER';
}
/**
* Remove replace html entity &quot; with real quote symbol "
* @param string $text text with &quote; html entities
* @return string text with real quote symbols
*/
public function removeQuotes($text) { return str_replace('&quot;', '"', $text); }
/**
* Return engine object name by engine object idi
* @param string $idi engine object idi
* @return string engine object name
*/
public function getObjNameByIdi($idi) {
if (is_numeric($idi)) return $idi;
$q = 'select nosauk from pdnobji where idi="'.addslashes($idi).'"';
$r = $this->db->query($q);
if ($r && $r->numRows()) {
$r = $r->getRow();
return trim($r['nosauk']);
}
return $idi;
}
/**
* Return online error mail subject appendix
*/
public function error_mail_subject_appendix() {
switch ($this->sistemasParametri['sistema-vide']) {
case 10: return '(dev)';
case 20: return '(dev test)';
case 30: return '(test)';
case 40: return '';
}
return '(IDENTITY CFG ERROR)';
}
/**
* PCTool functionality - this function must be member of kernel object
* Perform form include for particular chain form
*/
public function PCTool_do_obj_chainform_include() {
$this->userID = $this->get_current_user_id();
$tmplDir = ADMIN_DIR.'/tmpl/'.$this->kernel->mode;
$engineDir = ADMIN_DIR.'/engine';
$thisDir = ADMIN_DIR.'/pages/admin/produktudzinejs';
include ADMIN_DIR.'/pages/admin/produktudzinejs/main.php';
return array($out, $script);
}
/**
* Gets latest jquery from google, and puts it in temp folder
*/
public function get_latest_jquery() {
$folderJQuery = $this->kernel->cfg['pdfDir'].'/JS/'; // jquery js temp folder
if (!file_exists($folderJQuery)) {
mkdir($folderJQuery, 0777); // create folder if it doesnt exist
}
$fileJQuery = $folderJQuery.'saved.'.date('Y').'.'.date('m').'.jquery-latest.min.js'; // jquery js temp file
if (!file_exists($fileJQuery)) {
// retrieve jquery js from google if its not saved last month
file_put_contents($fileJQuery, file_get_contents('http://code.jquery.com/jquery-latest.min.js'));
}
return $fileJQuery;
}
/**
* Send a file
*/
public function send_physical_file($file, $fileName) {
header('Pragma: public');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Content-Type: '.$this->file_send_get_mime_type($file));
header('Content-Disposition: attachment; filename='.urlencode($fileName));
header('Content-Transfer-Encoding: binary');
header('Content-Description: File Transfer');
header('Content-Length: '.filesize($file));
if (ob_get_length() != 0 ) {
ob_flush();
ob_end_clean();
}
set_time_limit(0);
$fileHandle = fopen($file, 'rb');
while (!feof($fileHandle)) {
print fread($fileHandle, 1024 * 8);
}
exit;
}
/**
* Get file content type
*/
function file_send_get_mime_type($file) {
$ret = false;
$r = new finfo();
if (is_resource($r) === true) {
$ret = $result->file($file, FILEINFO_MIME_TYPE);
}
return $ret;
}
} // End of "kernel" class
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment