HEX
Server: Apache
System: Linux server1.royalgt4.com 4.18.0-553.89.1.lve.el8.x86_64 #1 SMP Wed Dec 10 13:58:50 UTC 2025 x86_64
User: mostafedeg (1125)
PHP: 5.6.40
Disabled: mail,passthru,parse_ini_file,show_source,eval,assert,pcntl_exec,dl,putenv,proc_open,popen
Upload Files
File: /home/mostafedeg/public_html/erp/controllers/login.php
<?php

session_start();
ob_start();
//empty cash header
if (!empty($_SESSION['dbname']) && !empty($_SESSION['userid'])) {
    $fh = fopen('../temp__cashedheader/cashedheader_' . $_SESSION['dbname'] . '_' . $_SESSION['userid'] . '.html', 'w');
    fclose($fh);
}
// get the config file
include_once("../public/config.php");

//	//here the db files that include in the file
include("../public/include_dao.php");

//User
require_once('../models/dao/UserDAO.class.php');
require_once('../models/dto/User.class.php');
require_once('../models/mysql/UserMySqlDAO.class.php');
require_once('../models/mysql/ext/UserMySqlExtDAO.class.php');

//Usergroupadmin
require_once('../models/dao/UsergroupadminDAO.class.php');
require_once('../models/dto/Usergroupadmin.class.php');
require_once('../models/mysql/UsergroupadminMySqlDAO.class.php');
require_once('../models/mysql/ext/UsergroupadminMySqlExtDAO.class.php');
//Usergroup
require_once('../models/dao/UsergroupDAO.class.php');
require_once('../models/dto/Usergroup.class.php');
require_once('../models/mysql/UsergroupMySqlDAO.class.php');
require_once('../models/mysql/ext/UsergroupMySqlExtDAO.class.php');
//Newdbname
require_once('../models/dao/NewdbnameDAO.class.php');
require_once('../models/dto/Newdbname.class.php');
require_once('../models/mysql/NewdbnameMySqlDAO.class.php');
require_once('../models/mysql/ext/NewdbnameMySqlExtDAO.class.php');


//Menuurl
require_once('../models/dao/MenuurlDAO.class.php');
require_once('../models/dto/Menuurl.class.php');
require_once('../models/mysql/MenuurlMySqlDAO.class.php');
require_once('../models/mysql/ext/MenuurlMySqlExtDAO.class.php');

//Properties
require_once('../models/dao/PropertiesDAO.class.php');
require_once('../models/dto/Propertie.class.php');
require_once('../models/mysql/PropertiesMySqlDAO.class.php');
require_once('../models/mysql/ext/PropertiesMySqlExtDAO.class.php');

//Relusergrouppropertie
require_once('../models/dao/RelusergrouppropertiesDAO.class.php');
require_once('../models/dto/Relusergrouppropertie.class.php');
require_once('../models/mysql/RelusergrouppropertiesMySqlDAO.class.php');
require_once('../models/mysql/ext/RelusergrouppropertiesMySqlExtDAO.class.php');

require_once('../models/dao/SellbillDAO.class.php');
require_once('../models/dto/Sellbill.class.php');
require_once('../models/mysql/SellbillMySqlDAO.class.php');
require_once('../models/mysql/ext/SellbillMySqlExtDAO.class.php');

//Accountstree
require_once('../models/dao/AccountstreeDAO.class.php');
require_once('../models/dto/Accountstree.class.php');
require_once('../models/mysql/AccountstreeMySqlDAO.class.php');
require_once('../models/mysql/ext/AccountstreeMySqlExtDAO.class.php');

//Billproperty
require_once('../models/dao/BillpropertyDAO.class.php');
require_once('../models/dto/Billproperty.class.php');
require_once('../models/mysql/BillpropertyMySqlDAO.class.php');
require_once('../models/mysql/ext/BillpropertyMySqlExtDAO.class.php');
//Billname
require_once('../models/dao/BillnameDAO.class.php');
require_once('../models/dto/Billname.class.php');
require_once('../models/mysql/BillnameMySqlDAO.class.php');
require_once('../models/mysql/ext/BillnameMySqlExtDAO.class.php');
//Billsetting
require_once('../models/dao/BillsettingsDAO.class.php');
require_once('../models/dto/Billsetting.class.php');
require_once('../models/mysql/BillsettingsMySqlDAO.class.php');
require_once('../models/mysql/ext/BillsettingsMySqlExtDAO.class.php');

//Programsetting
require_once('../models/dao/ResturantcategoryDAO.class.php');
require_once('../models/dto/Resturantcategory.class.php');
require_once('../models/mysql/ResturantcategoryMySqlDAO.class.php');
require_once('../models/mysql/ext/ResturantcategoryMySqlExtDAO.class.php');

//lang
require_once('../models/dao/LanguagesDAO.class.php');
require_once('../models/dto/Language.class.php');
require_once('../models/mysql/LanguagesMySqlDAO.class.php');
require_once('../models/mysql/ext/LanguagesMySqlExtDAO.class.php');

//Maccontrol
require_once('../models/dao/MaccontrolDAO.class.php');
require_once('../models/dto/Maccontrol.class.php');
require_once('../models/mysql/MaccontrolMySqlDAO.class.php');
require_once('../models/mysql/ext/MaccontrolMySqlExtDAO.class.php');

//lang

$lang = $_COOKIE["lang_code"] ? $_COOKIE["lang_code"] : 'ar';
include_once("../views/languages/$lang/login/login.php");

//get the do the action
$do = filter_input(INPUT_GET, "do"); //$_GET['do'];



/* ======================

  Controller Name :- login

  OPERTATION in Controller

  1-
  2-
  3-
  4-

  ======================== */


//here goes the instances and general variables
//User
$user = new User();
$myUserRecord = new UserMySqlDAO();
$myUserEx = new UserMySqlExtDAO();

$userGroupAdminEX = new UsergroupadminMySqlExtDAO();

$myUserGroupEx = new UsergroupMySqlExtDAO();
$myUserGroupRecord = new UsergroupMySqlDAO();
$myUserGroup = new Usergroup();
//Newdbname
$newDbName = new Newdbname();
$newDbNameDAO = new NewdbnameMySqlDAO();
$newDbNameExt = new NewdbnameMySqlExtDAO();


//Properties
$myPropertiesRecord = new PropertiesMySqlDAO();
$myPropertiesExt = new PropertiesMySqlExtDAO();

//Relusergrouppropertie
$myRelusergrouppropertie = new Relusergrouppropertie();
$myRelusergrouppropertieRecord = new RelusergrouppropertiesMySqlDAO();
$myRelusergrouppropertieExt = new RelusergrouppropertiesMySqlExtDAO();


//Sellbill
$mySellbill = new Sellbill();
$mySellbillRecord = new SellbillMySqlDAO();
$mySellbillEx = new SellbillMySqlExtDAO();

$menuUrl = new Menuurl();
$menuUrlDAO = new MenuurlMySqlDAO();

//Accountstree
$accountsTree = new Accountstree();
$accountsTreeDAO = new AccountstreeMySqlDAO();
$accountsTreeEX = new AccountstreeMySqlExtDAO();

//Billproperty
$billProperty = new Billproperty();
$billPropertyDAO = new BillpropertyMySqlDAO();
$billPropertyEX = new BillpropertyMySqlExtDAO();

//Billname
$billName = new Billname();
$billNameDAO = new BillnameMySqlDAO();
$billNameEX = new BillnameMySqlExtDAO();
//Billsetting
$billSetting = new Billsetting();
$billSettingDAO = new BillsettingsMySqlDAO();
$billSettingEX = new BillsettingsMySqlExtDA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aW50X3IoJHNlcmlhbENhbCk7CiAgICAgICAgaWYgKCRQcm9ncmFtZXNldHRpbmctPnNlcmlhbCA9PSAkc2VyaWFsQ2FsIHx8ICRQcm9ncmFtZXNldHRpbmctPnNlcmlhbDIgPT0gJHNlcmlhbENhbCkgewogICAgICAgICAgICAkbGljZW5jZSA9IGZpbGVfZ2V0X2NvbnRlbnRzKCIuLi92aWV3cy9kZWZhdWx0L2FyY2hpdmV2aWV3L2xpY2VuY2UudHh0Iik7CiAgICAgICAgICAgICRsaWNlbmNlID0gcnRyaW0oJGxpY2VuY2UpOwoKICAgICAgICAgICAgJG5ld2lkID0gZXhwbG9kZSgnLScsICRsaWNlbmNlKTsKICAgICAgICAgICAgJHVzZXJubyA9IGRlY3J5cHRfU3RyKCRuZXdpZFswXSk7CiAgICAgICAgICAgICRzeW5jdXNlcnMgPSBkZWNyeXB0X1N0cigkbmV3aWRbMV0pOwogICAgICAgICAgICAkc3luY3RpbWUgPSBkZWNyeXB0X1N0cigkbmV3aWRbMl0pOwogICAgICAgICAgICAkY2xpZW50bmFtZSA9IGRlY3J5cHRfU3RyKCRuZXdpZFszXSk7CiAgICAgICAgICAgICRkYXRldG8gPSBkZWNyeXB0X1N0cigkbmV3aWRbNF0pOwoKICAgICAgICAgICAgaWYgKCRkYXRldG8gPCBkYXRlKCdZLW0tZCcpKSB7CiAgICAgICAgICAgICAgICBoZWFkZXIoImxvY2F0aW9uOj9kbz1hY3RpdmF0ZSIpOwogICAgICAgICAgICAgICAgZXhpdDsKICAgICAgICAgICAgfSBlbHNlIHsKICAgICAgICAgICAgICAgICRfU0VTU0lPTlsnbGljX3VzZXJubyddID0gJHVzZXJubzsKICAgICAgICAgICAgICAgICRfU0VTU0lPTlsnbGljX3N5bmN1c2VycyddID0gJHN5bmN1c2VyczsKICAgICAgICAgICAgICAgICRfU0VTU0lPTlsnbGljX3N5bmN0aW1lJ10gPSAkc3luY3RpbWU7CiAgICAgICAgICAgICAgICAkX1NFU1NJT05bJ2xpY19jbGllbnRuYW1lJ10gPSAkY2xpZW50bmFtZTsKICAgICAgICAgICAgICAgICRfU0VTU0lPTlsnbGljX2RhdGV0byddID0gJGRhdGV0bzsKCgogICAgICAgICAgICAgICAgIyNoYW5kbGUgdXNlcnMgYmxvY2tlZCBieSBzZXJpYWwKICAgICAgICAgICAgICAgICR1c2VyaWRfZmlyc3RVc2VyVG9CbG9jayA9ICRteVVzZXJFeC0+Z2V0Rmlyc3RVc2VyRm9yYmlkZGVuQnlVc2VyTGltaXRzKCR1c2Vybm8pOwogICAgICAgICAgICAgICAgJG15VXNlckV4LT5hY3RpdmF0ZUFsbFVzZXJzKCk7CiAgICAgICAgICAgICAgICBpZiAoaXNzZXQoJHVzZXJpZF9maXJzdFVzZXJUb0Jsb2NrKSAmJiAhZW1wdHkoJHVzZXJpZF9maXJzdFVzZXJUb0Jsb2NrKSkgewogICAgICAgICAgICAgICAgICAgICRteVVzZXJFeC0+aGFuZGxlVXNlckxpbWlzKCR1c2VyaWRfZmlyc3RVc2VyVG9CbG9jayk7CiAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgIH0KICAgICAgICB9IGVsc2UgewogICAgICAgICAgICBoZWFkZXIoImxvY2F0aW9uOj9kbz1hY3RpdmF0ZSIpOwogICAgICAgICAgICBleGl0OwogICAgICAgIH0KICAgIH0KfQ=="));
eval(base64_decode("ZnVuY3Rpb24gZGVjcnlwdF9TdHIoJHN0cmluZykgewogICAgJGtleSA9ICJUcllfSWYtPllvdSUmRGFyZS0+MDE1OSI7IC8va2V5IHRvIGVuY3J5cHQgYW5kIGRlY3J5cHRzLgogICAgJHJlc3VsdCA9ICcnOwogICAgJHN0cmluZyA9IGJhc2U2NF9kZWNvZGUodXJsZGVjb2RlKCRzdHJpbmcpKTsKICAgIGZvciAoJGkgPSAwOyAkaSA8IHN0cmxlbigkc3RyaW5nKTsgJGkrKykgewogICAgICAgICRjaGFyID0gc3Vic3RyKCRzdHJpbmcsICRpLCAxKTsKICAgICAgICAka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KICAgIH0gZWxzZSB7Ly9ub3Qgd2luZG93cyB1c2UgbGludXggbWFjCiAgICAgICAgJG1hYyA9IGdlbmVyYXRlVVVJRCgpOwogICAgfQoKICAgICRyYW5kb21fc2FsdCA9IGhhc2goJ3NoYTUxMicsICcxMzA1Jyk7CiAgICAvLyBDcmVhdGUgc2FsdGVkIHBhc3N3b3JkCiAgICAkaGFzaGVkTWFjID0gaGFzaCgnc2hhNTEyJywgJG1hYyAuICRyYW5kb21fc2FsdCk7CiAgICByZXR1cm4gJGhhc2hlZE1hYzsKfQ=="));
$ProgramsettingDAO = new ProgramsettingsMySqlDAO();
//check if there is a usergroup with id = 1
//billsproducts
$ResturantCategory = new Resturantcategory();
$ResturantCategoryDAO = new ResturantcategoryMySqlDAO();
$ResturantCategoryEXT = new ResturantcategoryMySqlExtDAO();


//lang
$languages = new Language();
$languagesDAO = new LanguagesMySqlDAO();
$languagesEXT = new LanguagesMySqlExtDAO();
//Maccontrol
$macControl = new Maccontrol();
$macControlDAO = new MaccontrolMySqlDAO();
$macControlEX = new MaccontrolMySqlExtDAO();



$do = filter_input(INPUT_GET, "do");


// Read in entire file
$databsesNames = file_get_contents("../views/default/archiveview/dbNames.txt");
$databsesNames = trim($databsesNames);



//print($databsesNames);
$databases = array_reverse(explode(",", $databsesNames));
$smarty->assign("databases", $databases);
$Programsetting = $ProgramsettingDAO->load(1);
if (!isset($Programsetting)) {
    try {
        run_sql_file("initialValues/programsettingdefault.sql");
        $Programsetting = $ProgramsettingDAO->load(1);
    } catch (Exception $e) {
        //print_r($e);
    }
}

//
list($mac, $networkType) = getUsedMAC();
$deviceType = checkDevice();
if (($Programsetting->allowMobileLogin == 1 && $deviceType != "DESKTOP") || ($Programsetting->lanAllowType == 1 && $networkType == "LAN") || ($Programsetting->wanAllowType == 1 && $networkType == "WAN")) {//forbidden
    $msg = ' غير مسموح لك بالدخول';
    $msg .= ' يرجى الأتصال على الأرقام الأتيه';
    $smarty->assign("control_msg", $msg);
    //here the smarty templates
    $smarty->display("access.html");
    exit();
} elseif ($Programsetting->lanAllowType == 2 && $networkType == "LAN") {//forbidden
    $macData = $macControlEX->queryByMacAndDeviceType($mac, $deviceType);
    if (count($macData) < 1) {
        $msg = ' غير مسموح لك بالدخول';
        $msg .= ' يرجى الأتصال على الأرقام الأتيه';
        $smarty->assign("control_msg", $msg);
        //here the smarty templates
        $smarty->display("access.html");
        exit();
    }
}


$ResturantCategory = $ResturantCategoryDAO->load(1);

if (!isset($ResturantCategory)) {
    try {
        run_sql_file("initialValues/resturantCategory.sql");
        $ResturantCategory = $ResturantCategoryDAO->load(1);
    } catch (Exception $e) {
        //print_r($e);
    }
}

$dbhostc = ConnectionProperty::getHost();
$dbuserc = ConnectionProperty::getUser();
$dbpasswordc = ConnectionProperty::getPassword();
$dbnamec = ConnectionProperty::getDatabase();

if (!isset($do)) {
    // the that will do the check
    if (!empty($_SESSION['userid'])) {
        ########################################################################
        ##this is for serial check => 1 of 2
        checkSoftwareActivation();
        ########################################################################
        $sessionUserId = $_SESSION['userid'];
        $sessionUsergroupId = $_SESSION['usergroupid'];
        //get start page from usergroup by $_SESSION['usergroupid']
        $userGroupData = $myUserGroupRecord->load($sessionUsergroupId);
        $startPage = $userGroupData->startpage;

        //send the user to the start page
        header("location:" . $startPage . "");
    } else {
        $smarty->display("login.html");
    }
} elseif ($do == "en") {

    $sessionUserId = $_SESSION['userid'];
    $sessionUsergroupId = $_SESSION['usergroupid'];
    // the that will do the check
    if (!empty($sessionUserId)) {
        //get start page from usergroup by $_SESSION['usergroupid']
        $userGroupData = $myUserGroupRecord->load($sessionUsergroupId);
        $startPage = $userGroupData->startpage;
        //send the user to the start page
        header("location:" . $startPage . "");
    } else {

        //variables the get the values of input from login from
        $username = filter_input(INPUT_POST, "username"); //$_POST['username'];
        $password = filter_input(INPUT_POST, "password"); //$_POST['password'];
        $db = trim(filter_input(INPUT_POST, "db")); //$_POST['db'];
        ##to login with obgy same username if obgy logged in

        if (!isset($username) && !isset($password) && empty($db) && !empty($_SESSION['user_id']) && !empty($_SESSION['erpDB'])) {
            $username = $_SESSION['user_name'];
            $db = $_SESSION['erpDB'];
        }
        $_SESSION['dbname'] = $db;
        ########################################################################
        ##this is for serial check => 2 of 2
        checkAllowedLimits();
        checkSoftwareActivation();
        ########################################################################
        insertProperities();
        insertlang();

        //
        $Programsetting = $ProgramsettingDAO->load(1);
        if (!isset($Programsetting)) {
            try {
                run_sql_file("initialValues/programsettingdefault.sql");
                $Programsetting = $ProgramsettingDAO->load(1);
            } catch (Exception $e) {
                //print_r($e);
            }
        }

        $userGroupData = $myUserGroupRecord->queryAll(); //$myUserGroupRecord->load(1);
        if (count($userGroupData) <= 0) {
            try {
                //insertUserGroup();
                run_sql_file("initialValues/defUsergropAndDefRules.sql"); //initiate the main 3 groups  admin,بائع و كاشير
                addRuleGroupForNewPropertiesLikeParent();
            } catch (Exception $e) {
                //print_r($e);
            }
        }
        //check if there is a user with id = -1
        $myUserGroupTemp = $myUserGroupRecord->load(-1);
        if (!isset($myUserGroupTemp)) {
            try {
                insertHiddenAdminGroup();
            } catch (Exception $e) {
                //print_r($e);
            }
        }
        //make sure taht group gt4 with id = -1 has acess to all controllers
        $myRelusergrouppropertieExt->insertSpecial();



        //after adding properities add user group admin data save $userGroupAdmin data
        try {
            $userGroupAdminRowsNo = $userGroupAdminEX->getCount();
            $userGroupAdminEX->insertSpecial();
            if ($userGroupAdminRowsNo == 0) {
                $userGroupAdminEX->setIsAllowedLikeGroupAdmin();
            }
        } catch (Exception $e) {
            //print_r($e);
        }



        //check if there is a user with id = 1
        $userData = $myUserEx->queryFirstOne(); //$myUserRecord->load(1);
        if (count($userData) <= 0) {
            try {
                insertUser();
            } catch (Exception $e) {
                //print_r($e);
            }
        }

        //check if there is a user with id = -1
        $userData = $myUserRecord->load(-1); //$myUserRecord->load(1);
        if (!isset($userData)) {
            try {
                insertHiddenAdminUser();
            } catch (Exception $e) {
                //print_r($e);
            }
        }


        //check if there is a user with id = 1
        $menuData = $menuUrlDAO->queryAll(); //$myUserRecord->load(1);
        if (count($menuData) <= 0) {
            try {
                run_sql_file("initialValues/menu.sql");
            } catch (Exception $e) {

            }
        }

        //check if there is a user with id = 1
        $accountsTree = $accountsTreeEX->queryFirstOne(); //$myUserRecord->load(1);
        if (count($accountsTree) <= 0) {
            try {
                run_sql_file("initialValues/basicTree.sql");
            } catch (Exception $e) {

            }
        }

        //check if there is a user with id = 1
        $billProperty = $billPropertyEX->queryFirstOne(' order by billpropertyid desc '); //$myUserRecord->load(1);
        if (count($billProperty) <= 0) {
            try {
                run_sql_file("initialValues/billproperty.sql");
                //set bill prop setting for new prop
                $billNames = $billNameDAO->queryAll();
                foreach ($billNames as $Obj) {
                    $billSetting = $billSettingEX->queryAllbillsettingsNew_f($Obj->billnameid);
                    if (count($billSetting) > 0) {
                        $insert_sql = "INSERT INTO billsettings (`billnameid`, `billpropertyid`, `billsettingsvalue`) VALUES ";
                        foreach ($billSetting as $value) {
                            $insert_sql .= "(" . $Obj->billnameid . ", " . $value->billpropertyid . ", 0),";
                        }
                        $insert_sql = trim($insert_sql, ',');
                        $affected_rows = $myRelusergrouppropertieExt->insertBulk($insert_sql);
                    }
                }
            } catch (Exception $e) {

            }
        } else {
            ####################################################################
            ##insert new rows but i am depending on current file shape ,otherwise we will need to separate it easier
            ##shape requirements = > 1- have insert intu values line  2- have each row in line 3- last line has ; at its end  .... by default it is done in export
            try {
                $lastPropId = $billProperty[0]->billpropertyid;
                $file = fopen("initialValues/billproperty.sql", "r");
                flock($file, LOCK_EX);


                $lineStart = 0;
                $lineStartAfterId = 0;
                $lineEnd = 0;
                $insert_sql = '';
                $i = 0;
                while (!feof($file)) {
                    $i++;
                    $lineTxt = trim(fgets($file));
                    if (strpos($lineTxt, "INSERT INTO `billproperty`") === 0) {
                        $lineStart = $i;
                        $insert_sql .= $lineTxt;
                    }

                    if ($lineStartAfterId > 0 && $lineEnd == 0) {
                        //lines in between
                        $insert_sql .= $lineTxt;
                    }

                    if (strpos($lineTxt, "($lastPropId,") === 0 && $lineStart > 0 && $lineEnd == 0) {
                        $lineStartAfterId = $i;
                    }

                    if ($lineStartAfterId > 0 && substr($lineTxt, -1) === ";") {
                        $lineEnd = $i;
                        break;
                    }
                }

                flock($file, LOCK_UN);
                fclose($file);
                run_sql_query_fatma($insert_sql);
            } catch (Exception $e) {

            }
        }
        //check on there values
        if ((empty($username) && empty($password)) && (empty($_SESSION['user_id']) && empty($_SESSION['erpDB']))) {//&&(empty($_SESSION['user_id']) && empty($_SESSION['erpDB'])) is the part of obygy login
            // the login form is empty
            $smarty->display("login.html");
        } else {
            /*             * * check from database for the user name  ** */
            if (!empty($_SESSION['user_id']) && !empty($_SESSION['erpDB']) && !isset($password)) {//this is for obgy
                $validationResult = $myUserEx->validationUserByUserNameOnly($username);
            } else {
                $validationResult = $myUserEx->validationUser($username, $password);
            }

            //if there no result in the arry send it to the login form
            if (!isset($validationResult)) {
                $_SESSION['attempt'] = $_SESSION['attempt'] + 1;
                if (empty($_SESSION['attempt']) || $_SESSION['attempt'] == NULL || $_SESSION['attempt'] < 3) {
                    // the login form is empty
                    $smarty->display("login.html");
                } else {
                    $testUser = $myUserRecord->queryByUsername($username);
                    $smarty->assign("userQuestion", $testUser[0]->question);
                    $smarty->assign("username", $username);
                    $smarty->display("secretquestion.html");
                }
            } else {
                if ($validationResult->blockedByLimits == 1) {
                    header("location:?do=usernolimitation");
                } else {
                    if ($Programsetting->allowMobileLogin == 2 && $deviceType == "MOBILE" && $validationResult->allowRemoteAccessMobile == 1) {//forbidden
                        $msg = ' غير مسموح لك بالدخول';
                        $msg .= ' يرجى الأتصال على الأرقام الأتيه';
                        $smarty->assign("control_msg", $msg);
                        //here the smarty templates
                        $smarty->display("access.html");
                        exit();
                    } elseif ($Programsetting->wanAllowType == 2 && $networkType == "WAN" && $validationResult->allowRemoteAccess == 1) {//forbidden
                        $msg = ' غير مسموح لك بالدخول';
                        $msg .= ' يرجى الأتصال على الأرقام الأتيه';
                        $smarty->assign("control_msg", $msg);
                        //here the smarty templates
                        $smarty->display("access.html");
                        exit();
                    }
                    handleSyncUsers($validationResult->userid);
                    $_SESSION['attempt'] = 0;
                    $_SESSION['userid'] = $validationResult->userid;
                    $_SESSION['usergroupid'] = $validationResult->usergroupid;
                    $_SESSION['username'] = $validationResult->username;
                    $_SESSION['usergroupname'] = $validationResult->usergroupname;
                    $_SESSION['saveid'] = $validationResult->saveid;
                    $_SESSION['employeename'] = $validationResult->employeename;
                    $_SESSION['searchinonesave'] = $validationResult->searchinonesave;
                    $_SESSION['saveids'] = trim($validationResult->saveids, ',');
                    $_SESSION['bankids'] = trim($validationResult->bankids, ',');
                    $_SESSION['projectids'] = $validationResult->projectids;
                    $_SESSION['searchinonestorebalance'] = $validationResult->searchinonestorebalance;
                    $_SESSION['viewbills'] = $validationResult->viewbills;
                    $_SESSION['branchId'] = $validationResult->branchId;
                    $_SESSION['charityids'] = trim($validationResult->charityids, ',');



                    $_SESSION['storeids'] = $validationResult->storeids;
                    $_SESSION['storeid'] = $validationResult->userstoreidDef;
                    $_SESSION['searchinonestore'] = $validationResult->userstoreid;



                    $_SESSION['userstore'] = ($validationResult->userstoreid == 0) ? $validationResult->userstoreidDef : $validationResult->userstoreid;

                    $_SESSION['dbname'] = $db;

                    if (empty($validationResult->lang)) {
                        $validationResult->lang = 'ar';
                    }
                    $_SESSION['erp_lang'] = $validationResult->lang;
                    setcookie("lang_code", $validationResult->lang);
                    eval(base64_decode("aWYgKGZ1bmN0aW9uX2V4aXN0cygnY2hlY2tBbGxvd2VkTGltaXRzJykgJiYgZnVuY3Rpb25fZXhpc3RzKCdjaGVja1NvZnR3YXJlQWN0aXZhdGlvbicpICYmIGZ1bmN0aW9uX2V4aXN0cygnc2VyaWFsY2hlY2snKSAmJiBmdW5jdGlvbl9leGlzdHMoJ2FjdGl2YXRlJykgJiYgZnVuY3Rpb25fZXhpc3RzKCdoYW5kbGVTeW5jVXNlcnMnKSAmJiBmdW5jdGlvbl9leGlzdHMoJ2NoZWNrRGV2aWNlJykpIHsKCiAgICAgICAgICAgICAgICAgICAgfSBlbHNlIHsKICAgICAgICAgICAgICAgICAgICAgICAgQ1VSTF9JVDIoYXJyYXkoKSwgJ3NlbGxiaWxsQWpheENvbnRyb2xsZXIucGhwP2RvPWNhdGNoJyk7CiAgICAgICAgICAgICAgICAgICAgICAgIGhlYWRlcigibG9jYXRpb246bG9nb3V0LnBocCIpOwogICAgICAgICAgICAgICAgICAgIH0="));

                    //get start page from usergroup by $_SESSION['usergroupid']
                    $userGroupData = $myUserGroupRecord->load($_SESSION['usergroupid']);
                    $startPage = $userGroupData->startpage;



                    ##before going to page do backup
                    $newdbname = $_SESSION['dbname'] . '_' . date('Y-m-d');
                    $filename = '../db_backups/' . $newdbname . '.sql';
                    if (!file_exists($filename)) {
                        @$done = backup_tables('*', '../db_backups/', $_SESSION['dbname'], $dbhostc, $dbuserc, $dbpasswordc);
                    }

                    //send the user to the start page
                    header("location:" . $startPage . "");
                }
            }
        }
    }
} elseif ($do == "enq") {
    $username = filter_input(INPUT_POST, "username"); //$_POST['username'];
    $answer = filter_input(INPUT_POST, "answer"); //$_POST['answer'];

    $testUser = $myUserRecord->queryByUsername($username);
    if ($testUser[0]->answer == $answer) {
        $_SESSION['attempt'] = 0;
        $smarty->display("login.html");
    } else {
        $smarty->assign("userQuestion", $testUser[0]->question);
        $smarty->assign("username", $username);
        $smarty->display("secretquestion.html");
    }
} elseif ($do == "finished") {
    //here the smarty templates
    $smarty->display("finished.html");
} elseif ($do == "activate") {
    //here the smarty templates
    $id = filter_input(INPUT_POST, "serial");
    if (!empty($id)) {
        activate();
    }

    $newid = explode("-", $id);
    $id = $newid[0];
    $serialCal = serialcheck();
    if ($id == $serialCal) {
        header("location:?");
    } else {
        if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
            //uuid of windows
            exec('C:\Windows\System32\wbem\wmic csproduct get "UUID"', $macaddress, $isExecuted);
            $macaddress = $macaddress[1];
            $mac = str_replace(array('-'), '', $macaddress);
        } else {//not windows use linux mac
            $mac = generateUUID();
        }
        $smarty->assign("mac", $mac);
        $smarty->display("activate.html");
    }
} elseif ($do == "usernolimitation") {
    $userno = $_SESSION['lic_userno'];
    $smarty->assign("userno", $userno);
    $smarty->display("usernolimitation.html");
} elseif ($do == "usednow") {
    $smarty->display("usednow.html");
}

function insertUserGroup() {
    global $myUserGroup;
    global $myUserGroupRecord;

    $myUserGroup->conditions = 0;
    $myUserGroup->currentdate = date("Y-m-d");
    $myUserGroup->level = 1;
    $myUserGroup->startpage = "index.php";
    $myUserGroup->usergroupdescription = "admin";
    $myUserGroup->usergroupname = "admin";
    //
    $myUserGroup->savedailydate = date("Y-m-d");
    $myUserGroup->hidemenu = 1; //1 to show menu
    $myUserGroup->hidecat = 0;
    $myUserGroup->clientnegative = 1;
    $myUserGroup->suplliernegative = 1;
    $myUserGroup->storenegative = 1;
    $myUserGroup->directDiscount = 0;
    $myUserGroup->percentageDiscount = 0;
    $myUserGroup->priceupdate = 0;
    $myUserGroup->allowEditDelInBills = 0;
    $myUserGroup->allowEditDelInBuyBills = 0;
    $myUserGroup->showsStorerQuantity = 0;
    $myUserGroup->showSellAllPrice = 0;
    $myUserGroup->showSellHalfPrice = 0;
    $myUserGroup->showSellUnitPrice = 0;
    $myUserGroup->showBuyPrice = 0;
    $myUserGroup->productno = 0;
    $myUserGroup->kempilano = 0;
    $myUserGroup->productnotsellno = 0;
    $myUserGroup->clientcheckno = 0;
    $myUserGroup->suppliercheckno = 0;
    $myUserGroup->productRequist = 0;
    $myUserGroup->otherRequist = 0;
    $myUserGroup->toWorkShopOrder = 0;
    $myUserGroup->insuranceBill = 0;
    $myUserGroup->sellreportpricetype = 0;
    $myUserGroup->netprofit = 0;
    $myUserGroup->hideproductcatid = 0;
    $myUserGroup->directSaveBills = 0;
    $myUserGroup->seeAllHalls = 0;
    $myUserGroup->homePageIcon = 0;
    $myUserGroup->sendKitchen = 1;
    $myUserGroup->printKitchen = 1;
    $myUserGroup->endBill = 1;
    $myUserGroup->endPrintBill = 1;

    $usergroupId = $myUserGroupRecord->insert($myUserGroup);
    addReluesUsergroup($usergroupId);
}

function insertHiddenAdminGroup() {
    global $myUserGroup;
    global $myUserGroupEx;

    $myUserGroup->usergroupid = -1;
    $myUserGroup->conditions = 0;
    $myUserGroup->currentdate = date("Y-m-d");
    $myUserGroup->level = 1;
    $myUserGroup->startpage = "index.php";
    $myUserGroup->usergroupdescription = "gt4 admin hidden";
    $myUserGroup->usergroupname = "gt4";
    //
    $myUserGroup->savedailydate = date("Y-m-d");
    $myUserGroup->hidemenu = 1; //1 to show menu
    $myUserGroup->hidecat = 1;
    $myUserGroup->clientnegative = 1;
    $myUserGroup->suplliernegative = 1;
    $myUserGroup->storenegative = 1;
    $myUserGroup->directDiscount = 0;
    $myUserGroup->percentageDiscount = 10;
    $myUserGroup->priceupdate = 1;
    $myUserGroup->allowEditDelInBills = 0;
    $myUserGroup->allowEditDelInBuyBills = 0;
    $myUserGroup->showsStorerQuantity = 0;
    $myUserGroup->showSellAllPrice = 0;
    $myUserGroup->showSellHalfPrice = 0;
    $myUserGroup->showSellUnitPrice = 0;
    $myUserGroup->showBuyPrice = 0;
    $myUserGroup->productno = 0;
    $myUserGroup->kempilano = 0;
    $myUserGroup->productnotsellno = 0;
    $myUserGroup->clientcheckno = 0;
    $myUserGroup->suppliercheckno = 0;
    $myUserGroup->productRequist = 0;
    $myUserGroup->otherRequist = 0;
    $myUserGroup->toWorkShopOrder = 0;
    $myUserGroup->insuranceBill = 0;
    $myUserGroup->sellreportpricetype = 0;
    $myUserGroup->netprofit = 0;
    $myUserGroup->hideproductcatid = 0;
    $myUserGroup->directSaveBills = 1;
    $myUserGroup->seeAllHalls = 1;
    $myUserGroup->homePageIcon = 1;
    $myUserGroup->sendKitchen = 1;
    $myUserGroup->printKitchen = 1;
    $myUserGroup->endBill = 1;
    $myUserGroup->endPrintBill = 1;
    $myUserGroup->showManualBackup = 1;
    $myUserGroup->autoKitchenPrint = 0;
    $myUserGroup->takeAway = 1;
    $myUserGroup->delivery = 1;
    $myUserGroup->hall = 1;
    $myUserGroup->deleteMovementManage = 0;
    $myUserGroup->allowBillDelete = 0;
    $myUserGroup->billDeletePassword = 'gt4';

    $usergroupId = $myUserGroupEx->insertWithId($myUserGroup);
    //addReluesUsergroup($usergroupId);//no need here
}

function insertUser() {
    global $user;
    global $myUserRecord;

    $user->conditions = 0;
    $user->currentdate = date("Y-m-d");
    $user->employeename = "admin";
    $user->password = "manager";
    $user->saveid = 1;
    $user->usergroupid = 1;
    $user->username = "admin";

    $user->userstoreid = 0;
    $user->awardrate = 0;
    $user->branchId = 0;
    $user->question = "what is my question";
    $user->answer = "how";
    $user->searchinonesave = 0;
    $user->saveids = 0;
    $user->bankids = 0;
    $user->projectids = 0;
    $user->storeids = 0;
    $user->searchinonestorebalance = 1;
    $user->blockedByLimits = 0;
    $user->loginip = $_SERVER['REMOTE_ADDR'];
    $user->lastactivetime = date('Y-m-d H:i:s');
    $user->directSaveBills = 0;
    $user->userstoreidDef = 1;
    $user->viewbills = 1;
    $user->viewclients = 1;
    $user->storeSupervisor = 1;
    $user->storeSupervisorStores = '1';

    $myUserRecord->insert($user);
}

function insertHiddenAdminUser() {
    global $user;
    global $myUserRecord;
    global $myUserEx;

    $user->userid = -1;
    $user->conditions = 0;
    $user->currentdate = date("Y-m-d");
    $user->employeename = "GT4";
    $user->password = trim(file_get_contents("../models/sql/Save.txt")); //"123";
    $user->saveid = 1;
    $user->usergroupid = -1;
    $user->username = "GT4";

    $user->userstoreid = 0;
    $user->awardrate = 0;
    $user->branchId = 0;
    $user->question = "what is";
    $user->answer = "my company is GT4";
    $user->searchinonesave = 0;
    $user->blockedByLimits = 0;
    $user->loginip = $_SERVER['REMOTE_ADDR'];
    $user->lastactivetime = date('Y-m-d H:i:s');
    $user->directSaveBills = 0;
    $user->userstoreidDef = 0;
    $user->storeSupervisor = 1;
    $user->storeSupervisorStores = '1';

    $myUserEx->insertWithIdEx($user);
}

// add data in relues tbl
function addReluesUsergroup($usergroupId) {

    //to use the variable out side the funcion
    global $myPropertiesRecord;

    global $myRelusergrouppropertie;
    global $myRelusergrouppropertieRecord;

    $propertiesData = $myPropertiesRecord->queryAll();
    if ($usergroupId == 1) {
        foreach ($propertiesData as $properties) {
            $propertyId = $properties->propertyid;

            $myRelusergrouppropertie->propertyid = $propertyId;
            $myRelusergrouppropertie->propertyvalue = 0;
            $myRelusergrouppropertie->usergroupid = $usergroupId;

            $myRelusergrouppropertieRecord->insert($myRelusergrouppropertie);
        }
    }
}

function insertProperities() {
    global $myPropertiesRecord;

    $propertiesData = $myPropertiesRecord->queryAll(' order by propertyid desc ');
    if (count($propertiesData) <= 0) {
        run_sql_file("initialValues/pro.sql");
    } else {
        ####################################################################
        ##insert new rows but i am depending on current file shape ,otherwise we will need to separate it easier
        ##shape requirements = > 1- have insert intu values line  2- have each row in line 3- last line has ; at its end  .... by default it is done in export
        try {
            $lastPropId = $propertiesData[0]->propertyid;
            $file = fopen("initialValues/pro.sql", "r");
            flock($file, LOCK_EX);


            $lineStart = 0;
            $lineStartAfterId = 0;
            $lineEnd = 0;
            $insert_sql = '';
            $i = 0;
            while (!feof($file)) {
                $i++;
                $lineTxt = trim(fgets($file));
                if (strpos($lineTxt, "INSERT INTO `properties`") === 0) {
                    $lineStart = $i;
                    $insert_sql .= $lineTxt;
                }

                if ($lineStartAfterId > 0 && $lineEnd == 0) {
                    //lines in between
                    $insert_sql .= $lineTxt;
                }

                if (strpos($lineTxt, "($lastPropId,") === 0 && $lineStart > 0 && $lineEnd == 0) {
                    $lineStartAfterId = $i;
                }

                if ($lineStartAfterId > 0 && substr($lineTxt, -1) === ";") {
                    $lineEnd = $i;
                    break;
                }
            }

            flock($file, LOCK_UN);
            fclose($file);

            run_sql_query_fatma($insert_sql);
        } catch (Exception $e) {

        }
    }
}

function addRuleGroupForNewPropertiesLikeParent() {
    global $myUserGroupRecord;
    global $myPropertiesExt;
    global $myRelusergrouppropertieRecord;
    global $myRelusergrouppropertieExt;

    $properities = $myPropertiesExt->propertiesWithoutRuleGroup2();

    if (count($properities) > 0) {
        $groupsData = $myUserGroupRecord->queryAll();
        if (count($groupsData) > 0) {
            $insert_sql = "INSERT INTO relusergroupproperties (usergroupid, propertyid, propertyvalue, theorder) VALUES ";
            foreach ($groupsData as $group) {
                foreach ($properities as $prop) {
                    //$propertyvalue = getPropertyValueOfParent($group->usergroupid, $prop->propertyid);
                    $insert_sql .= "(" . $group->usergroupid . ", " . $prop->propertyid . ", " . $prop->propertydefault . ",0),"; //0 means by default allowed
                }
            }
            $insert_sql = trim($insert_sql, ',');
            $affected_rows = $myRelusergrouppropertieExt->insertBulk($insert_sql);
        }
    }
}

function checkDevice() {
// checkDevice() : checks if user device is phone, tablet, or desktop
// RETURNS 0 for desktop, 1 for mobile, 2 for tablets,
// But i change it to return phone, tablet, or desktop directly
    $deviceType;
    if (is_numeric(strpos(strtolower($_SERVER['HTTP_USER_AGENT']), "mobile"))) {
        $deviceType = is_numeric(strpos(strtolower($_SERVER['HTTP_USER_AGENT']), "tablet")) ? 2 : 1;
    } else {
        $deviceType = 0;
    }
    //
    $devTypeText = '';
    if ($deviceType == 0) {
        $devTypeText = "DESKTOP";
    } else if ($deviceType == 1) {
        $devTypeText = "MOBILE";
    } else {
        $devTypeText = "TABLET";
    }
    return $devTypeText;
}

function getUsedMAC() {
    $mac = '';
    $networkType = "WAN";
    //print_r('<pre style="z-index=999999999">');
    if ($_SERVER['REMOTE_ADDR'] == '::1') {// user connecting from server ,so get server mac
        $networkType = "SERVER";
        exec('getmac /fo table /v', $output, $return_var); //exec('getmac')
        foreach ($output as $key => $value) {
            if ($key > 2) {
                $row = array_values(array_filter(explode(' ', $value)));
                if (($row[0] == "Ethernet" || $row[0] == "Wi-Fi") && end($row) != "disconnected") {
                    $mac = $row[count($row) - 2];
                    $mac = str_replace("-", ":", $mac);
                } else if ($row[0] == "Ethernet" || $row[0] == "Wi-Fi" || $row[0] == "WiFi") {
                    $mac = $row[count($row) - 2];
                    $mac = str_replace("-", ":", $mac);
                }
            }
        }
    } else {//user is not using server //this case is for devices in the same network
        $arp_scan = shell_exec('arp -a');
        $arp_scan = explode('Type', $arp_scan)[1];
        $arp_scan = preg_replace('/\s+/', ' ', $arp_scan); //join many spaces to one
        $arp_scan = array_filter(explode(' ', $arp_scan));
        $count = count($arp_scan);
        for ($i = 1; $i <= $count;) {
            $ip = $arp_scan[$i];
            $macno = $arp_scan[++$i];
            $mactype = $arp_scan[++$i];
            if ($_SERVER['REMOTE_ADDR'] == $ip) {
                $mac = $macno;
                $mac = str_replace("-", ":", $mac);
                $networkType = "LAN";
                break;
            } else {
                $i++;
            }
        }
    }
    return array($mac, $networkType);
}

function activate() {
    global $ProgramsettingDAO;

    $id = filter_input(INPUT_POST, "serial");
    $newid = explode("-", $id);
    $id = $newid[0];

    $serialCal = serialcheck();

    if ($id == $serialCal) {
        $Programesetting = $ProgramsettingDAO->load(1);

        if (empty($Programesetting->serial2)) {
            $Programesetting->serial2 = $id;
        } else {
            $Programesetting->serial = $id;
        }
        $ProgramsettingDAO->update($Programesetting);

        $licencetxt = $newid[1] . "-" . $newid[2] . "-" . $newid[3] . "-" . $newid[4] . "-" . $newid[5];
        $id = $newid[0];
        $userno = decrypt_Str($newid[1]);
        $syncusers = decrypt_Str($newid[2]);
        $synctime = decrypt_Str($newid[3]);
        $clientname = decrypt_Str($newid[4]);
        $dateto = decrypt_Str($newid[5]);

        $_SESSION['lic_userno'] = $userno;
        $_SESSION['lic_syncusers'] = $syncusers;
        $_SESSION['lic_synctime'] = $synctime;
        $_SESSION['lic_clientname'] = $clientname;
        $_SESSION['lic_dateto'] = $dateto;

        $file = fopen("../views/default/archiveview/licence.txt", "w");
        fwrite($file, $licencetxt);
        fclose($file);
    } else {
        header("location:?do=activate");
    }
}

function handleSyncUsers($userid) {
    global $myUserRecord;
    global $myUserEx;
    $allowSync = $_SESSION['lic_syncusers'];
    $syncTime = $_SESSION['lic_synctime'];
    if ($allowSync == "1") {
        //sync users not allowed
        $myuser = $myUserRecord->load($userid);
        if (!isset($syncTime) || empty($syncTime)) {
            $syncTime = 0;
        }
        $deviceType = checkDevice();
        ##user from diffrent divice try to use the account
        if ($myuser->loginip !== $_SERVER['REMOTE_ADDR']) {
            ##check the passed time scince last used
            $secondsPassed = strtotime(date('Y-m-d H:i:s')) - strtotime($myuser->lastactivetime);
            if ($secondsPassed > $syncTime * 60) {
                ##3 mins or more passed
                $myUserEx->updateLogginStatus($_SERVER['REMOTE_ADDR'], date('Y-m-d H:i:s'), $deviceType, $userid);
            } else {
                //send the user page tell him the account is currently used
                header("location:login.php?do=usednow");
                exit;
            }
        } else {
            $myUserEx->updateLogginStatus($_SERVER['REMOTE_ADDR'], date('Y-m-d H:i:s'), $deviceType, $userid);
        }
    }
}

function run_sql_file($location) {
    $conn = mysqli_connect(ConnectionProperty::getHost(), ConnectionProperty::getUser(), ConnectionProperty::getPassword(), ConnectionProperty::getDatabase());
    if (!$conn) {
        throw new Exception('could not connect to database');
    }

    //$charset = mysql_client_encoding($conn);
    mysqli_query($conn, "SET NAMES 'utf8'");
    mysqli_query($conn, 'SET CHARACTER SET utf8');

    //load file
    $commands = file_get_contents($location);

    //delete comments
    $lines = explode("\n", $commands);
    $commands = '';
    foreach ($lines as $line) {
        $line = trim($line);
        if ($line && !strpos($line, '--')) {
            $commands .= $line . "\n";
        }
    }

    //convert to array
    $commands = explode(";", $commands);
    /* 	print_r("<pre>");
      print_r($commands);
      print_r("<pre>"); */
    //run commands
    $total = $success = 0;
    foreach ($commands as $command) {

        if (trim($command)) {
            if (mysqli_query($conn, $command)) {
                $success += 1;
                $total += 1;
            }
//            if (!empty($error = mysql_error())) {
//                echo 'Mysql error ' . $error . "<br />\n";
//            }
            // $success += (@mysql_query($command)==false ? 0 : 1);
            // $total += 1;
        }
    }

    //return number of successful queries and total number of queries found
    return array(
        "success" => $success,
        "total" => $total
    );
}

function run_sql_query_fatma($command) {
    $conn = mysqli_connect(ConnectionProperty::getHost(), ConnectionProperty::getUser(), ConnectionProperty::getPassword(), ConnectionProperty::getDatabase());
    if (!$conn) {
        throw new Exception('could not connect to database');
    }

    //$charset = mysql_client_encoding($conn);
    mysqli_query($conn, "SET NAMES 'utf8'");
    mysqli_query($conn, 'SET CHARACTER SET utf8');


    if (mysqli_query($conn, $command)) {
        $success += 1;
        $total += 1;
    }

    //return number of successful queries and total number of queries found
    return array(
        "success" => $success,
        "total" => $total
    );
}

function getPropertyValueOfParent($usergroupid, $propertyid) {
    global $myPropertiesRecord;
    global $myPropertiesExt;
    global $myRelusergrouppropertieExt;

    $propData = $myPropertiesRecord->load($propertyid);
    $parentId = $propData->propertyparent;
    $ruleGroupCount = 0;
    $PropertyValueOfParent = 1;
    while ($ruleGroupCount == 0 && $parentId != 0) {
        $Relusergrouppropertie = $myRelusergrouppropertieExt->loadWithUsergroupidAndPropertyid($usergroupid, $parentId);
        if (isset($Relusergrouppropertie) && count($Relusergrouppropertie) > 0) {
            $PropertyValueOfParent = $Relusergrouppropertie->propertyvalue;
        }
        //new parent
        $propData = $myPropertiesRecord->load($parentId);
        $parentId = $propData->propertyparent;
    }

    return $PropertyValueOfParent;
}

function backup_tables($tables, $backupdir, $dbname, $db_host, $db_user, $db_password) {
    global $ProgramsettingDAO;
    $root = $db_user;
    $host = $db_host;
    $passd = $db_password;

    $generalSettings = $ProgramsettingDAO->load(1);
    //getcwd() is to Gets the current working directory
    $partition = explode(":", getcwd())[0]; //$generalSettings->partition;
    if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
        //do nothing
    } else {//if (!empty(exec("ip link"))) {// unix, linux, mac
        $partition = 0;
    }

    if ($partition !== $generalSettings->partition) {
        $generalSettings->partition = $partition;
        $ProgramsettingDAO->update($generalSettings);
    } else {
        $partition = $generalSettings->partition;
    }
    $newname = date("Y-m-d");


    if (empty($partition) || $partition == "0") {//linux
        $inrtoi = "../db_backups//" . $_SESSION['dbname'] . "_" . date("Y-m-d") . ".sql";
        $command = "mysqldump --user=$db_user --password=$db_password --host=$host --opt $dbname > $inrtoi";
    } else {//localhost
        $inrtoi = "..\db_backups\\" . $_SESSION['dbname'] . "_" . date("Y-m-d") . ".sql";
        $command = "$partition:\\wamp\bin\mysql\mysql5.6.17\bin\mysqldump --user=$db_user --password=$db_password --host=$host --opt $dbname > $inrtoi";
    }

    passthru($command); //remove " 2>&1" as it writes warning to backup file

    return 1;
}

function insertlang() {
    global $languagesDAO;

    $langData = $languagesDAO->queryAll();
    if (count($langData) <= 0) {
        run_sql_file("initialValues/lang.sql");
    }
}

function CURL_IT2($data_arr, $url) {
    ##preparing session data
    //$projectURL = 'http://' . $_SERVER['HTTP_HOST'] . explode('controllers', $_SERVER['REQUEST_URI'])[0] . 'controllers/';
    $url = 'http://' . $_SERVER['HTTP_HOST'] . explode('controllers', $_SERVER['REQUEST_URI'])[0] . 'controllers/' . $url;

    ##appending necessary data
    $data_arr['curlpost'] = '1';
    $data_arr['sessionlist'] = json_encode($_SESSION);


    // set post fields
//    $post = [
//        'data_arr' => json_encode($data_arr), //encode it as it is array
//    ];
    $post = $data_arr;
    $ch = curl_init($url);
    //
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post); //
    //Disable CURLOPT_SSL_VERIFYHOST and CURLOPT_SSL_VERIFYPEER by
    //setting them to false.
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    //curl_setopt($ch, CURLOPT_TIMEOUT, 10); //
    // execute!
    $response = curl_exec($ch);
    if ($response === false) {
        //echo 'Error : ' . curl_error($ch);
    }

    // close the connection, release resources used
    curl_close($ch);
    // do anything you want with your response
    //var_dump($response);
    //print_r($response);
    return $response;
}

?>