File: /home/imensosw/www/imenso.co/timesheet/lib/lib.inc.php
<?php
/////////////////////////////////////////////////////////////////////////////
//System Setup
date_default_timezone_set('America/New_York');
define('DBDATE', 'Y-m-d', true);
define('DBDATETIME', 'Y-m-d H:i:s', true);
define('DBTIME', 'H:i', true);
$config = array();
/*if (is_readable(":/xampp/htdocs/nthrive/imensotime/thor-dev.conf.php")) {
require_once("F:/xampp/htdocs/nthrive/imensotime/thor-dev.conf.php");
} */
if (is_readable("E:/xampp/htdocs/timesheet/config.php")) {
require_once("E:/xampp/htdocs/timesheet/config.php");
}
else if(is_readable("../config.php")){
require_once("../config.php");
}
else {
die("No config found");
}
if(!defined("DEV")) define("DEV", FALSE, false);
$config['now'] = time();
$config['dbconnect'] = false;
$config['dblink'] = null;
$config['mysqli'] = false;
$config['mysqlpdo'] = true;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\SMTP;
require_once "../lib/mail/src/PHPMailer.php";
require_once "../lib/mail/src/Exception.php";
require_once "../lib/mail/src/SMTP.php";
// Errors and Logging
if (!defined('FATAL')) {
define('FATAL', 5, true);
}
if (!defined('WARN')) {
define('WARN', 4, true);
}
if (!defined('INFO')) {
define('INFO', 3, true);
}
if (!defined('LOG')) {
define('LOG', 2, true);
}
if (!defined('REPORT')) {
define('REPORT', 1, true);
}
if (!defined('DEBUG')) {
define('DEBUG', 0, true);
}
logit(INFO,"Starting on server " . NTHRIVE_SERVER_NAME);
////////////////////////////////////
//DB Manager
function dbConnect($multiple = false)
{
global $config;
if (!$config['dbconnect'] or $multiple) {
if ($config['mysqlpdo']) {
try {
$db = new PDO("mysql:host={$config['db_server']};dbname={$config['db_name']}", $config['db_user'], $config['db_password']);
} catch (PDOException $e) {
logit(FATAL, "Can't select database {$config['db_name']}@{$config['db_server']} in ".__FILE__.' on line: '.__LINE__);
}
}
else if ($config['mysqli']) {
$db = mysqli_connect($config['db_server'], $config['db_user'], $config['db_password']) or logit(FATAL, "Can't connect to database {$config['db_server']} in ".__FILE__.' on line: '.__LINE__);
mysqli_select_db($db, $config['db_name']) or logit(FATAL, "Can't select database {$config['db_name']}@{$config['db_server']} in ".__FILE__.' on line: '.__LINE__);
} else {
$db = mysql_connect($config['db_server'], $config['db_user'], $config['db_password']) or logit(FATAL, "Can't connect to database {$config['db_server']} in ".__FILE__.' on line: '.__LINE__);
mysql_select_db($config['db_name']) or logit(FATAL, "Can't select database {$config['db_name']}@{$config['db_server']} in ".__FILE__.' on line: '.__LINE__);
}
//$sql="SET character_set_results = 'utf-8'";
//dbQuery($sql);
//set flag
$config['dbconnect'] = true;
$config['dblink'] = $db;
return $db;
} else {
return true;
}
}
function dbRealEscapeString($string)
{
global $config;
if ($config['mysqli']) {
return mysqli_real_escape_string($config['dblink'], $string);
} else {
return mysql_real_escape_string($string);
}
}
function dbPdoQuery($sql,$array=array()){
global $config;
$config['pdostatement'] = $config['dblink']->prepare($sql);
if (!$config['pdostatement']) {
logit(WARN,"DB ERROR[prep]: ",$config['dblink']->errorInfo());
return false;
}
$ret = $config['pdostatement']->execute($array);
if (!$ret) {
logit(WARN,"DB ERROR[exec]: ",$config['pdostatement']->errorInfo());
}
return $config['pdostatement'];
} //- dbPdoQuery
function dbPdoPrep($sql){
global $config;
$config['pdostatement'] = $config['dblink']->prepare($sql);
if (!$config['pdostatement']) {
logit(WARN,"DB ERROR: ",$config['dblink']->errorInfo());
}
return $config['pdostatement'];
} //- dbPdoPrep
function dbPdoExec($array=array()){
global $config;
$ret = $config['pdostatement']->execute($array);
if (!$ret) {
logit(WARN,"DB ERROR: ",$config['pdostatement']->errorInfo());
}
return $ret;
} //- dbPdoExec
function dbPdoFetchall($rc) {
global $config;
$row = $rc->fetchAll(PDO::FETCH_ASSOC);
return $row;
} //- dbPdoFetchall
function dbPdoFetch($rc) {
global $config;
$rows = $rc->fetch(PDO::FETCH_ASSOC);
return $rows;
} //- dbPdoFetch
function dboPdoLastId() {
global $config;
return $config['dblink']->lastInsertId();
} //- dboPdoLastId
function dbPdoQuote($str){
global $config;
return $config['dblink']->quote($str);
} //- dbPdoQuote
function dbQuery($sql)
{
$s = microtime(1);
global $config;
if ($config['mysqli']) {
$rc = mysqli_query($config['dblink'], $sql);
} else {
$rc = mysql_query($sql);
}
return $rc;
}
function dbFetch($pointer)
{
global $config;
if ($config['mysqlpdo']) {
$pointer->setFetchMode(PDO::FETCH_ASSOC);
$row = mysqli_fetch_assoc($pointer);
} else if ($config['mysqli']) {
$row = mysqli_fetch_assoc($pointer);
} else {
$row = mysql_fetch_assoc($pointer);
}
return $row;
}
function dbFetchRow($pointer)
{
global $config;
if ($config['mysqli']) {
$row = mysqli_fetch_row($pointer);
} else {
$row = mysql_fetch_row($pointer);
}
return $row;
}
function dbResult($pointer, $rownum = 0, $fieldnum = 0)
{
global $config;
if ($config['mysqli']) {
mysqli_data_seek($pointer, $rownum);
mysqli_field_seek($pointer, $fieldnum);
return mysqli_fetch_field($pointer);
} else {
return mysql_result($pointer, $rownum, $fieldnum);
}
}
function dbDate($sqldate = '')
{
if (!$sqldate) {
$sqldate = time();
} elseif (!is_numeric($sqldate)) {
$sqldate = strtotime($sqldate);
}
return date(DBDATE, $sqldate);
}
function dbDateTime($sqldate = '')
{
if (strlen($sqldate) == 0) {
$sqldate = time();
} elseif (!is_numeric($sqldate)) {
$sqldate = strtotime($sqldate);
}
return date(DBDATETIME, $sqldate);
}
function dbAffectedRows($dblink = null)
{
global $config;
if ($config['mysqli']) {
return mysqli_affected_rows($config['dblink']);
} else {
return mysql_affected_rows();
}
}
function dbErrNo()
{
global $config;
if ($config['mysqli']) {
if ($config['dbconnect'] || $config['dblink']) {
return mysqli_errno($config['dblink']);
} else {
// logit(WARN, "No database link given in ".__FILE__." on line: ".__LINE__);
return 1105; // 1105 = mysql unknown error
}
} else {
return mysql_errno();
}
}
function dbError()
{
global $config;
if ($config['mysqli']) {
if ($config['dbconnect'] || $config['dblink']) {
return mysqli_error($config['dblink']);
} else {
return 'No database link';
}
} else {
return mysql_error();
}
}
function dbInsertId() {
$sql="SELECT LAST_INSERT_ID()";
$rc=dbQuery($sql) or logit(WARN, " Can't get insertid: $sql");
$id=dbFetch($rc);
return array_shift($id);
}
function dbClose($link)
{
global $config;
if ($config['mysqli']) {
mysqli_close($link);
} else {
mysql_close($link);
}
$config['dblink'] = null;
$config['dbconnect'] = false;
}
////////////////////////////////////////////
// gen sql statement
function makeSQL($var, $mode = 'insert')
{
if($mode=='insert'){
foreach ($var as $key => $value) {
$field[] = $key;
$datum[] = $value;
}
$sql = '('.implode(',', $field).") VALUES ('".implode("','", $datum)."')";
} else {
foreach ($var as $key => $value) {
$field[] = "$key='$value'";
}
$sql = 'SET '.implode(',', $field);
}
return $sql;
}
////////////////////////////////////
//format data for SQL db input
function sqlClean($data, $mode = '')
{
if (isset($data)) {
if ($mode == 'html') {
if (is_array($data)) {
$new = array();
foreach ($data as $value) {
$new[] = dbRealEscapeString(stripslashes($value));
}
return $new;
} else {
return dbRealEscapeString(stripslashes($data));
}
} else {
if (is_array($data)) {
$new = array();
foreach ($data as $value) {
$new[] = dbRealEscapeString(stripslashes(strip_tags($value)));
}
return $new;
} else {
return dbRealEscapeString(stripslashes(strip_tags($data)));
}
}
}
}
///////////////////////
//convert to json
function to_json($in)
{
$utf = to_utf8($in);
$out = json_encode($utf);
if (json_last_error() > 0) {
$out = json_encode(to_utf8($in,"strict"));
}
return $out;
}
//-------------------------------------------------------------------------------------------
if (!function_exists('is_countable'))
{
function is_countable($var)
{
return (is_array($var) || $var instanceof Countable);
}
}
//-------------------------------------------------------------------------------------------
function to_utc($time = '', $zone = '', $format = '')
{
// time = local time, string
// zone = local time zone (Default = server TZ)
if (!$format) {
$format = DBDATETIME;
}
try {
// Specified date/time in the specified time zone.
if ($zone) {
$date = new DateTime($time, new DateTimeZone($zone));
} else {
$date = new DateTime($time);
}
$date->setTimezone(new DateTimeZone('UTC'));
return $date->format($format);
} catch (Exception $e) {
return date($format, strtotime($time));
}
} //ef date
function to_utf8($in, $mode = '') {
if (is_array($in) OR is_object($in)) {
if (count($in) == 0) {
$out = array();
} else {
foreach ($in as $key => $value) {
$out[to_utf8($key, $mode)] = to_utf8($value, $mode);
}
}
} elseif (is_string($in)) {
if ($mode == 'strict') {
$in = filter_var($in, FILTER_UNSAFE_RAW, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH);
}
if (mb_detect_encoding($in) != 'UTF-8') {
return utf8_encode($in);
} else {
//$in = filter_var($in,FILTER_UNSAFE_RAW, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH);
return $in;
}
} else {
return $in;
}
return $out;
}
function logit($level = 1, $msg = '', $arr = '', $arr2 = '', $arr3 = '')
{
global $config;
if (is_array($arr) or is_object($arr)) {
$msg .= 'PRINT_R: '.print_r($arr, 1);
} else {
$msg .= "\t".$arr;
}
if (is_array($arr2) or is_object($arr2)) {
$msg .= 'PRINT_R: '.print_r($arr2, 1);
} else {
$msg .= "\t".$arr2;
}
if (is_array($arr3) or is_object($arr3)) {
$msg .= 'PRINT_R: '.print_r($arr3, 1);
} else {
$msg .= "\t".$arr3;
}
$type = array('DEBUG', 'REPORT', 'LOG', 'INFO', 'WARN', 'FATAL');
$string = date("Y-m-d\tH:i:s");
$string .= "\t{$msg}";
// if ($s = dbError()) {
// $string .= "\t[MYSQL: $s]";
// }
if ($level == FATAL) {
$string .= "\nExecution aborted.";
}
$string .= "\n";
@error_log($string, 3, "{$config["approot"]}/logs/apilog-".date("Y-m-d").".log");
// if (!SILENT) {
// echo $string;
//}
if ($level == FATAL) {
if (!DEV) {sendMail($msg);}
die("Execution aborted");
}
if ($level == WARN AND !DEV) {
sendMail($msg);
}
}
function sendMail($message,$html=false) {
global $config;
$mail = new PHPMailer(); // create a new object
$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 0; // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // authentication enabled
$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for Gmail
$mail->Host = $config["mail_host"];
$mail->Port = $config["mail_port"];
$mail->IsHTML(false);
$mail->email = $config["mail_user"];
$mail->Password = $config["mail_pass"];
$mail->SetFrom("deepak.imenso@gmail.com");
$mail->Subject = "Message from " . $config["app"];
$mail->Body = $message;
$mail->AddAddress("deepak1gehlot@gmail.com");
$mail->Send();
} //ef
function sendMailTo($to,$message,$html=false) {
global $config;
$mail = new PHPMailer(); // create a new object
$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 0; // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // authentication enabled
$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for Gmail
$mail->Host = $config["mail_host"];
$mail->Port = $config["mail_port"];
$mail->IsHTML(true);
$mail->email = $config["mail_user"];
$mail->Password = $config["mail_pass"];
$mail->SetFrom("deepak.imenso@gmail.com");
$mail->Subject = "Message from " . $config["app"];
$mail->Body =$message;
$mail->AddAddress($to);
$mail->Send();
} //ef
// password_hash wrapper
function hashPassword($password)
{
if (!empty($password)) {
return password_hash($password, PASSWORD_BCRYPT, array("cost" => 12));
}
return false;
}
////////////////////////////////
//check login credentials
function verifyLogin($email, $password)
{
global $config;
if(!empty($email) && !empty($password)) {
if ($config['mysqlpdo']) {
$sql = "SELECT id, email, password FROM users WHERE email = '$email'";
if (($rc=dbPdoQuery($sql, array("email" => $email))) && $rc->rowCount() === 1) {
if ($row=dbPdoFetch($rc)) {
return password_verify($password, $row["password"]);
}
}
} else {
$sql = "SELECT id, email, password FROM users WHERE email = '" . sqlClean($email) . "'";
if (($rc=dbQuery($sql)) && $rc->num_rows === 1) {
if ($row=dbFetch($rc)) {
return password_verify($password, $row["password"]);
}
}
}
}
return false;
}
function tokenTimeout($token)
{
$sql = "SELECT * FROM users WHERE token = :token";
if (($rc=dbPdoQuery($sql, array("token" => $token))) && $rc->rowCount() === 1) {
if ($row=dbPdoFetch($rc))
{
$login_time=$row['login_time'];
$login_time = strtotime($login_time);
$login_time = strtotime("+1 day", $login_time);
if(time()>=$login_time)
{
return true;
}
}
}
return false;
}
function isAdmin($token)
{
$sql = "SELECT * FROM users WHERE token = :token and usertype=:access_level";
if (($rc=dbPdoQuery($sql, array("token" => $token,"access_level"=>"admin"))) && $rc->rowCount() === 1) {
return true;
}
return false;
}
function error()
{
global $resp;
header('Content-Type: application/json');
//$resp['error'] = $err;
echo to_json($resp);
logit(WARN, 'ERROR-RESP: ', $resp->error);
exit();
}
function respond()
{
global $resp;
header('Content-Type: application/json');
$resp->resp = 'OK';
echo to_json($resp);
exit();
}
?>