| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509 |
- <?php
- /****************************
- * File : global.php
- * Author : Cygnusa
- * @2018
- *
- * All Global Rest Api files
- *
- ***************************/
- class globalfunc
- {
- // `userid`, `smpin`, `emp_code`, `password`, `fname`, `lname`, `emailid`, `mobileno`, `role`, `dealer_code`, `address_1`, `address_2`, `address_3`, `valid_token`, `validate_time`, `profile_photo`, `dob`, `doj`, `country`, `auth_token`, `otp`, `otp_expiry`, `language`, `is_married`, `marriage_date`, `mpin`, `status`, `last_password_change`, `is_first_login`, `is_profile_updated`, `is_deleted`, `inactivated_on`, `created_on`, `modified_on`
- private static $user_fields = "userid, `smpin`, `emp_code`, `password`, `fname`, `lname`, `emailid`, `mobileno`, `role`, `dealer_code`, `address_1`, `address_2`, `address_3`,`profile_photo`, `dob`, `doj`, `country`, `language`, `is_married`, `marriage_date`, `mpin`, `status`,`last_password_change`,`is_first_login`,`is_profile_updated`,validate_time";
- /* /////////////////////////////////// DEVELOPER ERROR /////////////////////////////////// */
- public static function callErrorMsg($parent, $data)
- {
- if (!isset($data)) {
- $parent->response(array('response' => 'failed', 'message' => 'PHP UNDEFINED ERROR'), 500);
- }
- if (!isset($data['message']) || $data['message'] == '' || $data['message'] == null) {
- $parent->response(array('response' => 'failed', 'message' => 'PHP UNDEFINED ERROR'), 500);
- }
- $parent->response(array('response' => 'failed', 'message' => $data['message']), 500);
- }
- /* ///////////////////////////////////////////////////////////////////////////////////// */
- /* /////////////////////////////////// CHECK METHOD TYPE /////////////////////////////////// */
- public static function checkMethodType($parent, $method_array)
- {
- if (is_array($method_array)) {
- $method_array = array_map('strtoupper', $method_array);
- if (!in_array($parent->get_request_method(), $method_array)) {
- $parent->response(array('response' => 'failed'), 406);
- }
- } else {
- self::callErrorMsg($parent, array('message' => 'GLOBAL(checkMethodType):REQUIRED DATA'));
- }
- }
- /* ///////////////////////////////////////////////////////////////////////////////////// */
- /* /////////////////////////////// CHECK PARAMETER COUNT EXIT ////////////////////////////// */
- public static function checkParamCount($parent, $param_count)
- {
- if (count($parent->params) != $param_count) {
- $parent->response(array('response' => 'failed'), 404);
- }
- if ($param_count != 0) {
- if (!(trim($parent->params[($param_count - 1)]) != '')) {
- $parent->response(array('response' => 'failed'), 404);
- }
- }
- }
- /* ///////////////////////////////////////////////////////////////////////////////////// */
- /* /////////////////////////////// CHECK ANY KEY ////////////////////////////// */
- public static function checkAnyKey($parent, $element_arr)
- {
- if (!is_array($element_arr)) {
- self::callErrorMsg($parent, array('message' => 'GLOBAL(checkAnyKey):REQUIRED DATA'));
- }
- try {
- $temp = 0;
- //FIELD KEY VALIDATE
- $field_arr = array_keys($element_arr);
- foreach ($field_arr as $single) {
- if (isset($parent->_request[$single])) {$temp = 1;
- break;}
- }
- if ($temp == 0) {
- $parent->response(array('response' => 'failed', 'message' => 'MISSING FIELDS - ' . strtoupper($single)), 406);
- }
- //FIELD VAKUE TYPE VALIDATE
- foreach ($element_arr as $key => $single) {
- if (isset($parent->_request[$key])) {
- if (($parent->_request[$key] == '' || $parent->_request[$key] == null) && !is_array($parent->_request[$key]) && !is_object($parent->_request[$key])) {
- $parent->response(array('response' => 'failed', 'message' => $key . ' FIELD VALUE REQUIRED'), 406);
- }
- (!self::validRequestKey($parent->_request[$key], $single)) ? $parent->response(array('response' => 'failed', 'message' => 'INVALID DATA TYPE. `' . $key . '` Required as ' . $single), 406) : '';
- }
- }
- } catch (Exception $e) {
- $parent->response(array('response' => 'failed', 'message' => $e->getMessage()), 406);
- }
- }
- /* ///////////////////////////////////////////////////////////////////////////////////// */
- /* /////////////////////////////// MANDATORY ////////////////////////////// */
- public static function mandatoryKey($parent, $element_arr)
- {
- if (!is_array($element_arr)) {
- self::callErrorMsg($parent, array('message' => 'GLOBAL(checkAnyKey):REQUIRED DATA'));
- }
- try {
- //FIELD KEY VALIDATE
- $field_arr = array_keys($element_arr);
- foreach ($field_arr as $single) {
- if (!isset($parent->_request[$single])) {
- $parent->response(array('response' => 'failed', 'message' => 'MISSING FIELDS - ' . strtoupper($single)), 406);
- }
- }
- //FIELD VAKUE TYPE VALIDATE
- foreach ($element_arr as $key => $single) {
- if (($parent->_request[$key] == '' || $parent->_request[$key] == null) && !is_array($parent->_request[$key]) && !is_object($parent->_request[$key])) {
- $parent->response(array('response' => 'failed', 'message' => strtoupper($key) . ' FIELD VALUE REQUIRED'), 406);
- }
- (!self::validRequestKey($parent->_request[$key], $single)) ? $parent->response(array('response' => 'failed', 'message' => 'INVALID DATA TYPE. `' . $key . '` Required as ' . $single), 406) : '';
- }
- } catch (Exception $e) {
- $parent->response(array('response' => 'failed', 'message' => $e->getMessage()), 406);
- }
- }
- /* ///////////////////////////////////////////////////////////////////////////////////// */
- /* /////////////////////////////// get ip ////////////////////////////// */
- public static function getIp($parent, $data = array())
- {
- $ip = $_SERVER['REMOTE_ADDR'];
- if ($ip) {
- if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
- $ip = $_SERVER['HTTP_CLIENT_IP'];
- } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
- $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
- }
- return $ip;
- }
- // There might not be any data
- return false;
- }
- /* ///////////////////////////////////////////////////////////////////////////////////// */
- /* /////////////////////////////// CHECK REQUEST PARAMETER CHECK ////////////////////////////// */
- public static function checkElementexist($parent, $elementarr)
- {
- if (!is_array($elementarr)) {
- self::callErrorMsg($parent, array('message' => 'GLOBAL(checkElementexist):REQUIRED DATA'));
- }
- if (count($parent->_request) != count($elementarr)) {
- $parent->response(array('response' => 'failed'), 406);
- }
- foreach ($elementarr as $single) {
- if (!isset($parent->_request[$single])) {
- $parent->response(array('response' => 'failed'), 406);
- }
- }
- }
- /* ///////////////////////////////////////////////////////////////////////////////////// */
- /* /////////////////////////////// CHECK PARAMETER COUNT EXIT ////////////////////////////// */
- public static function checkRequestKey($parent, $element_arr)
- {
- if (!is_array($element_arr)) {
- self::callErrorMsg($parent, array('message' => 'GLOBAL(checkElementexist):REQUIRED DATA'));
- }
- try {
- $field_arr = array_keys($element_arr);
- if (count($parent->_request) != count($field_arr)) {
- $parent->response(array('response' => 'failed', 'message' => 'MISSING KEYS'), 406);
- }
- foreach ($field_arr as $single) {
- if (!isset($parent->_request[$single])) {
- $parent->response(array('response' => 'failed', 'message' => 'MISSING FIELDS'), 406);
- }
- }
- //KEY TYPE VALIDATE
- foreach ($element_arr as $key => $single) {
- (!self::validRequestKey($parent->_request[$key], $single)) ? $parent->response(array('response' => 'failed', 'message' => 'INVALID KEY TYPE'), 406) : '';
- }
- } catch (Exception $e) {
- $parent->response(array('response' => 'failed', 'message' => $e->getMessage()), 406);
- }
- }
- /* ///////////////////////////////////////////////////////////////////////////////////// */
- /* /////////////////////////////// CHECK FILE ////////////////////////////// */
- public static function validateFile($parent, $obj)
- {
- try {
- if (is_object($obj)) {
- (!(isset($obj->filekey) && isset($obj->size) && isset($obj->type) && is_array($obj->type))) ? $parent->response(array('response' => 'failed', 'message' => 'CODE ERROR'), 406) : null;
- (!(isset($_FILES[$obj->filekey]) && ($_FILES[$obj->filekey]["error"] == 0))) ? $parent->response(array('response' => 'failed', 'message' => 'FILE NOT FOUND'), 406) : null;
- $maxsize = $obj->size * 1024 * 1024;
- ($maxsize < $_FILES[$obj->filekey]['size']) ? $parent->response(array('response' => 'failed', 'message' => 'INVALID FILE SIZE'), 406) : null;
- $fileParts = pathinfo($_FILES[$obj->filekey]['name']);
- $fileext_arr = explode('?', $fileParts['extension']);
- (!@in_array(strtolower($fileext_arr[0]), $obj->type)) ? $parent->response(array('response' => 'failed', 'message' => 'You can upload only ', @implode(', ', $obj->type) . " file type."), 406) : null;
- } else {
- self::callErrorMsg($parent, array('message' => 'GLOBAL(validateFile):REQUIRED DATA'));
- }
- } catch (Exception $e) {
- $parent->response(array('response' => 'failed', 'message' => $e->getMessage()), 406);
- }
- }
- /* ///////////////////////////////////////////////////////////////////////////////////// */
- /* /////////////////////////////// EMAIL VALIDATION ////////////////////////////// */
- public static function isValidDomain($email)
- {
- list($user, $url) = explode('@', $email);
- $validation = false;
- /*Parse URL*/
- $urlparts = parse_url(filter_var($url, FILTER_SANITIZE_URL));
- /*Check host exist else path assign to host*/
- if (!isset($urlparts['host'])) {
- $urlparts['host'] = $urlparts['path'];
- }
- if ($urlparts['host'] != '') {
- /*Add scheme if not found*/
- if (!isset($urlparts['scheme'])) {
- $urlparts['scheme'] = 'http';
- }
- /*Validation*/
- if (checkdnsrr($urlparts['host'], 'A') && in_array($urlparts['scheme'], array('http', 'https')) && ip2long($urlparts['host']) === false) {
- $urlparts['host'] = preg_replace('/^www\./', '', $urlparts['host']);
- $url = $urlparts['scheme'] . '://' . $urlparts['host'] . "/";
- if (filter_var($url, FILTER_VALIDATE_URL) !== false && @get_headers($url)) {
- $validation = true;
- }
- }
- }
- return $validation;
- }
- public static function isValidEmail($email)
- {
- return filter_var($email, FILTER_VALIDATE_EMAIL)
- && preg_match('/@.+\./', $email);
- }
- public static function emailValidation($parent, $email_address)
- {
- if (!(self::isValidEmail($email_address))) {
- $parent->response(array('response' => 'failed', 'message' => 'INVALID EMAIL'), 406);
- }
- if (!(self::isValidDomain($email_address))) {
- $parent->response(array('response' => 'failed', 'message' => 'INVALID EMAIL DOMAIN'), 406);
- }
- }
- /* ///////////////////////////////////////////////////////////////////////////////////// */
- /* /////////////////////////////// MOBILE VALIDATION ////////////////////////////// */
- public static function mobileValidation($parent, $mobileno)
- {
- if (!(preg_match('/^[0-9]{10}+$/', $mobileno))) {
- $parent->response(array('response' => 'failed', 'message' => 'INVALID MOBILE'), 406);
- }
- }
- /* ///////////////////////////////////////////////////////////////////////////////////// */
- /* /////////////////////////////// PASSWORD VALIDATION ////////////////////////////// */
- public static function validPassword($parent, $passstring)
- {
- $containsLetter = preg_match('/[a-zA-Z]/', $passstring);
- $containsDigit = preg_match('/\d/', $passstring);
- //$containsSpecial = preg_match('/[^a-zA-Z\d]/',$passstring);
- if (!(strlen($passstring) >= 6 && strlen($passstring) <= 100 && $containsLetter && $containsDigit))
- //if(!(strlen($passstring)>=6 && strlen($passstring)<=10 && $containsLetter && $containsDigit && $containsSpecial ))
- {
- return false;
- }
- return true;
- }
- /* ///////////////////////////////////////////////////////////////////////////////////// */
- /* /////////////////////////////// SET DB RECORD SKIP VALUE ////////////////////////////// */
- public static function setRecordSkip($parent, $data)
- {
- if (strstr($data, "record=")) {
- $qry_params = explode('record=', $data);
- $sepraters = explode("&", $qry_params[1]);
- if (isset($sepraters[0])) {
- if ($sepraters[0] == null || $sepraters[0] == '') {
- $parent->response(array('response' => 'failed'), 404);
- }
- $query_values = explode(",", $sepraters[0]);
- $query_value = (isset($query_values[1])) ? $query_values[0] : 0;
- return $query_value;
- } else {
- return 0;
- }
- } else {
- return 0;
- //$parent->response(array('response'=>'failed'),404);
- }
- }
- /* ////////////////////////////////////////////////////////////////////////// */
- /* /////////////////////////////// SET DB RECORD LIMIT VALUE ////////////////////////////// */
- public static function setRecordLimit($parent, $data)
- {
- if (strstr($data, "record=")) {
- $qry_params = explode('record=', $data);
- $sepraters = explode("&", $qry_params[1]);
- if (isset($sepraters[0])) {
- //echo $sepraters[0];
- $query_values = explode(",", $sepraters[0]);
- (!(isset($query_values[0]) && isset($query_values[1]))) ? $parent->response(array('response' => 'failed', 'invalid limit call'), 403) : null;
- //((int)$query_values[0]>(int)$query_values[1])?$parent->response(array('response'=>'failed','invalid limit call'), 403):NULL;
- /*
- switch (count($query_values)){
- case 1:
- $query_value=(int)$query_values[0];
- break;
- case 2:
- $query_value=(int)$query_values[1];
- break;
- default:
- $query_value='0,'.RECORD_LIMIT;
- break;
- }*/
- $query_value = (int) $query_values[0] . "," . (int) $query_values[1];
- return $query_value;
- } else {
- $parent->current_page = 0;
- return '0,' . RECORD_LIMIT;
- }
- } else {
- $parent->current_page = 0;
- return '0,' . RECORD_LIMIT;
- }
- }
- /* ////////////////////////////////////////////////////////////////////////// */
- /* /////////////////////////////// SET PAGE LIMIT VALUE ////////////////////////////// */
- public static function setPageLimit($parent, $data)
- {
- if (strstr($data, "page=")) {
- $qry_params = explode('page=', $data);
- $sepraters = explode("&", $qry_params[1]);
- if (isset($sepraters[0])) {
- $page_value = intval($sepraters[0]);
- $limit_data = explode('limit=', $data);
- if (strstr($data, "limit=") && isset($limit_data[0])) {
- $sepraters = explode("&", $limit_data[1]);
- $limit_arr = explode("&", $limit_data[1]);
- $limit_value = intval($limit_arr[0]);
- } else {
- $limit_value = RECORD_LIMIT;
- }
- (!(isset($page_value))) ? $parent->response(array('response' => 'failed', 'Invalid Pagination call'), 406) : null;
- $page_start_value = (int) $page_value * (int) $limit_value;
- $parent->current_page = $page_value;
- $parent->current_limit = $limit_value;
- $query_value = $page_start_value . "," . $limit_value;
- return $query_value;
- } else {
- $parent->current_page = 0;
- $parent->current_limit = RECORD_LIMIT;
- return '0,' . RECORD_LIMIT;
- }
- } else {
- $parent->current_page = 0;
- $parent->current_limit = RECORD_LIMIT;
- return '0,' . RECORD_LIMIT;
- }
- }
- /* ////////////////////////////////////////////////////////////////////////// */
- /* /////////////////////////////// GET DB RECORD FILTER VALUE ////////////////////////////// */
- public static function getFilterValues($parent, $data)
- {
- if (strpos($data, "filter=") !== false) {
- $filter_params = explode("filter=", $data);
- if (!isset($filter_params[1]) || $filter_params[1] == null || $filter_params[1] == '') {
- $parent->response(array('response' => 'failed'), 404);
- }
- $filter_param_items = explode(",", array_values(explode('&', $filter_params[1]))[0]);
- $filter_array = array();
- //print_r($filter_param_items);
- foreach ($filter_param_items as $item) {
- $itemval = explode(":", $item);
- if (isset($itemval[1])) {
- $itemkey = $itemval[0];
- $filter_array[$itemkey] = $itemval[1];
- } else {
- $filter_array[] = $itemval[0];
- }
- //$filter_array[]=(isset($itemval[1]))?array($itemval[0]=>$itemval[1]):array($itemval[0]);
- }
- return $filter_array;
- } else {
- return null;
- }
- }
- /* ////////////////////////////////////////////////////////////////////////// */
- /* /////////////////////////////// GET DB RECORD BETWEEN VALUE ////////////////////////////// */
- public static function getBetweenFilter($parent, $data)
- {
- if (!isset($data) || is_null($data)) {
- return null;
- }
- if (strpos($data, "between=")) {
- $between_params = explode("between=", $data);
- if (!isset($between_params[1]) || $between_params[1] == null || $between_params[1] == '') {
- $parent->response(array('response' => 'failed'), 400);
- }
- $between_param_items = explode(",", array_values(explode('&', $between_params[1]))[0]);
- $between_array = array();
- //$more_params=array();
- foreach ($between_param_items as $item) {
- if ($item != '') {
- $itemval = explode(":", $item);
- if (isset($itemval[1])) {
- $itemvals = explode("|", $itemval[1]);
- $between_array[] = array($itemval[0] => $itemvals);
- }
- }
- }
- return (count($between_array) > 0) ? $between_array : null;
- } else {
- return null;
- }
- }
- /* ////////////////////////////////////////////////////////////////////////// */
- /* /////////////////////////////// GET DB RECORD ORDER VALUE ////////////////////////////// */
- public static function getOrderValues($parent, $data)
- {
- $order_array = array();
- if (strpos($data, "orderby=")) {
- $order_params = explode("orderby=", $data);
- if (!isset($order_params[1]) || $order_params[1] == null || $order_params[1] == '') {
- $parent->response(array('response' => 'failed'), 404);
- }
- $order_param_items = explode(",", array_values(explode('&', $order_params[1]))[0]);
- foreach ($order_param_items as $item) {
- $order_array[] = $item;
- }
- return (count($order_array) > 0) ? $order_array : null;
- } else {
- return null;
- }
- }
- /* ////////////////////////////////////////////////////////////////////////// */
- /* /////////////////////////////// TOKEN GENERATION ////////////////////////////// */
- public static function generateToken($parent, $token_type = '', $length = 128)
- {
- $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
- $charactersLength = strlen($characters);
- $randomString = '';
- for ($i = 0; $i < $length; $i++) {
- $randomString .= $characters[rand(0, $charactersLength - 1)];
- }
- //ACCESS TOKEN ALREADY EXIST
- switch (strtolower($token_type)) {
- case "access":
- $query_checkuser = $parent->getQueryCount("SELECT userid FROM " . TABLE_USER . " WHERE auth_token='" . $randomString . "' LIMIT 1");
- return ($query_checkuser == 1) ? self::generateToken($parent, $token_type, $length) : $randomString;
- break;
- case "forgot":
- $query_checkuser = $parent->getQueryCount("SELECT userid FROM " . TABLE_USER . " WHERE valid_token='" . $randomString . "' LIMIT 1");
- return ($query_checkuser == 1) ? self::generateToken($parent, $token_type, $length) : $randomString;
- break;
- case "enquiry":
- $query_checkuser = $parent->getQueryCount("SELECT id FROM " . DMS_ENQUIRY_MASTER . " WHERE share_token='" . $randomString . "' LIMIT 1");
- return ($query_checkuser == 1) ? self::generateToken($parent, $token_type, $length) : $randomString;
- break;
- //case "forgot":
- default:
- return $randomString;
- break;
- }
- }
- /* ///////////////////////////////////////////////////////////////////////////////////// */
- /* /////////////////////////////// EXPIRY TIME ////////////////////////////// */
- public static function generateExpiryTime($parent, $min = 15)
- {
- $sec = $min * 60;
- //echo $sec.'--';
- $expiry_time = date('Y-m-d H:i:s', strtotime('+' . $sec . ' seconds', strtotime(NOW)));
- //echo $expiry_time;die();
- return $expiry_time;
- }
- /* ///////////////////////////////////////////////////////////////////////////////////// */
- /* /////////////////////////////// EXPIRY TIME ////////////////////////////// */
- public static function generateExpiryDate($parent, $days = 10)
- {
- $expiry_time = date('Y-m-d H:i:s', strtotime('-' . $days . ' day', strtotime(NOW)));
- //echo $expiry_time;die();
- return $expiry_time;
- }
- /* ///////////////////////////////////////////////////////////////////////////////////// */
- /* /////////////////////////////// UPDATE USER TOKEN ////////////////////////////// */
- /*
- public static function updateUserToken($parent,$data) {
- if(IS_MULTI_LOGIN==1){
- $parent->executeQuery("INSERT INTO ".TABLE_USER_DEVICES."(`userid`, `devicetype`, `token`, `android_id`, `model`, `manufacture`, `version`, `client_ip`, `created_on`, `modified_on`) VALUES ('".$data['user_id']."','".$data['device_name']."','".$data['device_id']."','".$parent->device_type."','".$data['requester']->ip."','".$data['requester']->city."','".$data['requester']->country."','".$data['access_token']."','".NOW."','".NOW."')");
- return true;
- }else{
- $query_user_devices=$parent->selectQuery(TABLE_USER_DEVICES,"id","user_id='".$data['user_id']."' AND device_type='".$parent->device_type."'","1");
- if($query_user_devices['nr']<= 0){
- $parent->executeQuery("INSERT INTO ".TABLE_USER_DEVICES."( `user_id`,`device_name`,`device_id`,`device_type`,`client_ip`,`city`,`country`,`access_token`, `created_on`, `modified_on`) VALUES ('".$data['user_id']."','".$data['device_name']."','".$data['device_id']."','".$parent->device_type."','".$data['requester']->ip."','".$data['requester']->city."','".$data['requester']->country."','".$data['access_token']."','".NOW."','".NOW."')");
- return true;
- }else{
- $parent->executeQuery(" UPDATE ".TABLE_USER_DEVICES." SET device_name='".$data['device_name']."', device_id ='".$data['device_id']."', client_ip='".$data['requester']->ip."', city ='".$data['requester']->city."', country ='".$data['requester']->city."', access_token ='".$data['access_token']."', modified_on='".NOW."' WHERE user_id='".$data['user_id']."' AND device_type='".$parent->device_type."'");
- return true;
- }
- }
- return false;
- }
- */
- /* ///////////////////////////////////////////////////////////////////////////////////// */
- /* //////////////////////////////////// AUTHROZATION /////////////////////////////////
- /* /////////////////////////////// GET AUTHROZATION TOKEN////////////////////////////// */
- public static function getAuthrozation($parent)
- {
- $headers = getallheaders();
- $auth = '';
- if (isset($headers['Authorization']) || isset($headers['authorization'])) {
- $auth = (isset($headers['Authorization'])) ? 'Authorization' : 'authorization';
- } else {
- $parent->response(array('response' => 'failed', 'message' => 'Authrozation required'), 401);
- }
- $request_token = $headers[$auth];
- if (is_null($request_token)) {
- $parent->response(array('response' => 'failed', 'message' => 'Authrozation value required'), 401);
- }
- $access_token = explode("Bearer ", $request_token);
- if (!(isset($access_token[1])) || $access_token[1] == '') {
- $parent->response(array('response' => 'failed', 'message' => 'Authrozation value format not matched'), 401);
- }
- return $access_token[1];
- }
- /* ///////////////////////////////////////////////////////////////////////////////////// */
- /* /////////////////////////////// LOCK ACCESS ////////////////////////////// */
- public static function secureAccess($parent, $access_token)
- {
- //CHECK LOCK IS ENABLE
- if (LOCK_ACCESS_ENABLE == 1) {
- $sec = LOCK_ACCESS_MINUTES * 60;
- $expiry_time = date('Y-m-d H:i:s', strtotime('-' . $sec . ' seconds', strtotime(NOW)));
- $lock_qry_str = "SELECT * FROM " . TABLE_LOCK_ACCESS . " WHERE is_deleted='0' AND lock_count>='" . LOCK_ACCESS_COUNT . "' AND auth_token='" . $access_token . "' AND modified_on>='" . $expiry_time . "' LIMIT 1 ";
- $lock_value = $parent->getQueryValue($lock_qry_str);
- if (count($lock_value) > 0) {
- $parent->response(array('response' => 'failed', 'message' => 'Sorry Your Access locked.'), 401);
- }
- }
- }
- /* ///////////////////////////////////////////////////////////////////////////////////// */
- /* /////////////////////////////// OTP AUTHROZATION CHECKING ////////////////////////////// */
- public static function checkAuthrozation($parent, $data)
- {
- /* data is a stdClass values */
- /* type : otp/user */
- if (!isset($data)) {
- self::callErrorMsg($parent, array('message' => 'GLOBAL(checkAuthrozation):REQUIRED DATA'));
- }
- if (!isset($data['type'])) {
- self::callErrorMsg($parent, array('message' => 'GLOBAL(checkAuthrozation):REQUIRED type VALUE'));
- }
- $access_token = escape_str(self::getAuthrozation($parent));
- self::secureAccess($parent, $access_token);
- switch ($data['type']) {
- /*
- case "otp":
- $user_qry_str="SELECT user_id FROM ".TABLE_USER." WHERE otpnumber='".$access_token."' AND is_deleted!='1' AND status='1' LIMIT 1";
- $user_value=$parent->getQueryValue($user_qry_str);
- if(count($user_value)<=0) $parent->response(array('response'=>'failed', 'message'=>'INVALID OTP'), 401);
- $parent->current_user_data=$user_value[0];
- return $user_value[0];
- break;
- */
- case "user":
- $user_qry_str = "SELECT * FROM " . TABLE_USER . " WHERE is_deleted='0' AND status='1' AND auth_token='" . $access_token . "' AND auth_token!='' LIMIT 1";
- $user_value = $parent->getQueryValue($user_qry_str);
- //if(count($user_value)<=0) $parent->response(array('response'=>'failed', 'message'=>'INVALID USER ACCESS TOKEN'), 401);
- if (count($user_value) <= 0) {
- self::insertLockLog($parent, $access_token);
- $parent->response(array('response' => 'failed', 'message' => 'Session expired or You have already logged-in another device'), 401);
- }
- $parent->current_user_data = $user_value[0];
- $parent->current_user_id = $user_value[0]->userid;
- $parent->current_user_role = $user_value[0]->role;
- $parent->current_smpin = $user_value[0]->smpin;
- $parent->current_emp_code = $user_value[0]->emp_code;
- unset($user_value[0]->userid);
- return $user_value[0];
- break;
- case "set_password":
- $user_qry_str = "SELECT " . self::$user_fields . " FROM " . TABLE_USER . " WHERE valid_token='" . $access_token . "' AND auth_token!='' AND is_deleted='0' AND status='1' LIMIT 1";
- $user_value = $parent->getQueryValue($user_qry_str);
- if (count($user_value) <= 0) {
- self::insertLockLog($parent, $access_token);
- $parent->response(array('response' => 'failed', 'message' => 'Invalid Authentication token'), 401);
- }
- if ($user_value[0]->validate_time == "0000-00-00 00:00:00") {
- $parent->response(array('response' => 'failed', 'message' => 'Authentication token expired, Please initiate a new password reset request again.'), 406);
- }
- if (strtotime($user_value[0]->validate_time) < strtotime(NOW)) {
- $parent->response(array('response' => 'failed', 'message' => 'Authentication token expired, Please initiate a new password reset request again.'), 406);
- }
- $parent->current_user_data = $user_value[0];
- $parent->current_user_id = $user_value[0]->userid;
- $parent->current_user_role = $user_value[0]->role;
- $parent->current_smpin = $user_value[0]->smpin;
- $parent->current_emp_code = $user_value[0]->emp_code;
- unset($user_value[0]->userid);
- return $user_value[0];
- break;
- case "explore":
- $user_qry_str = "SELECT * FROM " . TABLE_USER . " WHERE is_deleted='0' AND status='1' AND auth_token='" . $access_token . "' AND auth_token!='' LIMIT 1";
- $user_value = $parent->getQueryValue($user_qry_str);
- if (count($user_value) > 0) {
- $parent->current_user_data = $user_value[0];
- $parent->current_user_id = $user_value[0]->userid;
- $parent->current_user_role = $user_value[0]->role;
- $parent->current_smpin = $user_value[0]->smpin;
- $parent->current_emp_code = $user_value[0]->emp_code;
- unset($user_value[0]->userid);
- return $user_value[0];
- } else {
- if ($access_token == MODE_ONE_TOKEN) {
- $parent->exp_model_type = 0;
- } else if ($access_token == MODE_TWO_TOKEN) {
- $parent->exp_model_type = 1;
- } else {
- self::insertLockLog($parent, $access_token);
- $parent->response(array('response' => 'failed', 'message' => 'Invalid Authentication token'), 401);
- }
- $parent->current_user_data = array();
- $parent->current_user_role = 0;
- $parent->current_user_id = 'guest';
- return null;
- }
- break;
- default:
- self::callErrorMsg($parent, array('message' => 'GLOBAL(checkAuthrozation):TYPE VALUE WAS NOT ACCEPTABLE'));
- break;
- }
- }
- /* ///////////////////////////////////////////////////////////////////////////////////// */
- /* /////////////////////////////// TOKEN GENERATION ////////////////////////////// */
- public static function generateOTP($length = 4)
- {
- $characters = '0123456789';
- $charactersLength = strlen($characters);
- $randomString = '';
- for ($i = 0; $i < $length; $i++) {
- $randomString .= $characters[rand(0, $charactersLength - 1)];
- }
- //$randomString='1234';
- //EDIT FOR DEV
- if (IS_LIVE_SERVER == '0') {
- $randomString = '1234';
- }
- // else{ //SMS CHENGE
- // $randomString='1234';
- // }
- return $randomString;
- }
- /* ///////////////////////////////////////////////////////////////////////////////////// */
- /* /////////////////////////////// GET SITE SETTING ////////////////////////////// */
- public static function getSiteSetting($parent, $data)
- {
- if (!isset($data)) {
- self::callErrorMsg($parent, array('message' => 'GLOBAL(getSiteSetting):REQUIRED DATA'));
- }
- if (!isset($data['setting']) || $data['setting'] == '' || $data['setting'] == null) {
- self::callErrorMsg($parent, array('message' => 'GLOBAL(getSiteSetting):REQUIRED setting VALUE'));
- }
- $user_qry_str = "SELECT * FROM " . TABLE_SITE_SETTING . " WHERE setting_type='" . $data['setting'] . "' AND is_active='1'";
- $user_value = $parent->getQueryValue($user_qry_str);
- $out_data = new stdClass();
- foreach ($user_value as $values) {
- $key_name = $values->setting_title;
- $out_data->$key_name = $values->value;
- }
- return $out_data;
- }
- /* ///////////////////////////////////////////////////////////////////////////////////// */
- /* /////////////////////////////// PASSWORD POLICY ////////////////////////////// */
- public static function passwordPolicy($parent, $data)
- {
- if (!isset($data)) {
- self::callErrorMsg($parent, array('message' => 'GLOBAL(passwordPolicy):REQUIRED DATA'));
- }
- if (!isset($data['password']) || $data['password'] == '' || $data['password'] == null) {
- self::callErrorMsg($parent, array('message' => 'GLOBAL(passwordPolicy):REQUIRED password VALUE'));
- }
- $policy_setting = self::getSiteSetting($parent, array('setting' => 'PASSWORD_POLICY'));
- if (strtolower($policy_setting->POLICY_REQUIRED) == "true") {
- //print_r($policy_setting);
- if (!is_numeric($policy_setting->MINIMUM_LENGTH)) {
- self::callErrorMsg($parent, array('message' => 'GLOBAL(passwordPolicy):ERROR IN PASSWORD MINIMUM_LENGTH SETTING VALUE.'));
- }
- if (!is_numeric($policy_setting->MAXIMUM_LENGTH)) {
- self::callErrorMsg($parent, array('message' => 'GLOBAL(passwordPolicy):ERROR IN PASSWORD MAXIMUM_LENGTH SETTING VALUE.'));
- }
- if (!(strlen($data['password']) >= $policy_setting->MINIMUM_LENGTH && strlen($data['password']) <= $policy_setting->MAXIMUM_LENGTH)) {
- $parent->response(array('response' => 'failed', 'message' => 'PASSWORD LENTH WAS NOT MATCHED IN THE PASSWORD POLICY'), 406);
- }
- if (!is_numeric($policy_setting->POLICY_TYPE)) {
- self::callErrorMsg($parent, array('message' => 'GLOBAL(passwordPolicy):ERROR IN PASSWORD POLICY_TYPE SETTING VALUE.'));
- }
- switch ($policy_setting->POLICY_TYPE) {
- case 1:
- if (!is_numeric($data['password'])) {
- $parent->response(array('response' => 'failed', 'message' => 'Password value was not matched in the password policy'), 406);
- }
- break;
- case 2:
- if (!ctype_alpha($data['password'])) {
- $parent->response(array('response' => 'failed', 'message' => 'Password value was not matched in the password policy'), 406);
- }
- break;
- case 3:
- if (!preg_match("/(?=.*[A-Z])(?=.*[a-z])[A-Za-z]+$/", $data['password'])) {
- $parent->response(array('response' => 'failed', 'message' => 'Password value was not matched in the password policy'), 406);
- }
- break;
- case 4:
- if (!(preg_match('/[A-Za-z]/', $data['password']) && preg_match('/[0-9]/', $data['password']))) {
- $parent->response(array('response' => 'failed', 'message' => 'Password value was not matched in the password policy'), 406);
- }
- break;
- case 5:
- if (!(preg_match('/[0-9]/', $data['password']) && preg_match('/[A-Z]/', $data['password']) && preg_match('/[a-z]/', $data['password']))) {
- $parent->response(array('response' => 'failed', 'message' => 'Password value was not matched in the password policy'), 406);
- }
- break;
- case 6:
- if (!preg_match("/^(?=.*\d)(?=.*[@#!.-])(?=.*[A-Z])(?=.*[a-z])[0-9A-Za-z!-@#.\/]{1,}$/", ($data['password']))) {
- $parent->response(array('response' => 'failed', 'message' => 'Password value was not matched in the password policy'), 406);
- }
- break;
- case 7:
- break;
- default:
- self::callErrorMsg($parent, array('message' => 'GLOBAL(passwordPolicy):ERROR IN PASSWORD POLICY_TYPE VALUE SHOULD 1 TO 6 ONLY.'));
- break;
- }
- /*
- if(is_numeric($policy_setting->PREVIOUS_COUNT) && 0<=(int)$policy_setting->PREVIOUS_COUNT){
- if($policy_setting->PREVIOUS_COUNT!=0){
- if(!isset($data['user_id']) || $data['user_id']=='' || $data['user_id']==NULL) self::callErrorMsg($parent,array('message'=>'GLOBAL(passwordPolicy):REQUIRED user_id VALUE.'));
- $query_previous_passwords=$parent->selectQuery("(SELECT * FROM ".TABLE_USER_PASSWORD_LOGS." WHERE user_id='".$data['user_id']."' AND is_reseted=0 ORDER BY id DESC LIMIT ".((int)$policy_setting->PREVIOUS_COUNT+1).") as a ","a.user_id","a.password='".md5($data['password'])."' ");
- if($query_previous_passwords['nr']!=0) $parent->response(array('response'=>'failed','message'=>'Your new password value is match with last '.$policy_setting->PREVIOUS_COUNT.' password(s)'),406);
- }
- }else{
- self::callErrorMsg($parent,array('message'=>'GLOBAL(passwordPolicy):ERROR IN PASSWORD PREVIOUS_COUNT SETTING VALUE.'));
- }
- */
- }
- }
- /* ///////////////////////////////////////////////////////////////////////////////////// */
- /* /////////////////////////////// UPDATE PASSWORD ////////////////////////////// */
- public static function updatePassword($parent, $data)
- {
- if (!isset($data)) {
- self::callErrorMsg($parent, array('message' => 'GLOBAL(updatePassword):REQUIRED DATA'));
- }
- if (!isset($data['password']) || $data['password'] == '' || $data['password'] == null) {
- self::callErrorMsg($parent, array('message' => 'GLOBAL(updatePassword):REQUIRED password VALUE'));
- }
- if (!isset($data['userid']) || $data['userid'] == '' || $data['userid'] == null) {
- self::callErrorMsg($parent, array('message' => 'GLOBAL(updatePassword):REQUIRED userid VALUE'));
- }
- $parent->executeQuery(" UPDATE " . TABLE_USER . " SET password='" . md5($data['password']) . "',last_password_change='" . NOW . "',modified_on='" . NOW . "' WHERE userid='" . $data['userid'] . "'");
- return true;
- }
- /* ///////////////////////////////////////////////////////////////////////////////////// */
- /* /////////////////////////////// SEND OTP ////////////////////////////// */
- public static function sendOtp($parent, $type, $otp_value, $message, $send_to)
- {
- }
- /* ///////////////////////////////////////////////////////////////////////////////////// */
- /* /////////////////////////////// INSERT LOCK ACCESS ////////////////////////////// */
- public static function insertLockLog($parent, $access_token)
- {
- $lock_qry_str = "SELECT * FROM " . TABLE_LOCK_ACCESS . " WHERE is_deleted='0' AND auth_token='" . $access_token . "' LIMIT 1";
- $lock_value = $parent->getQueryValue($lock_qry_str);
- //LOCK ACCESS
- if (count($lock_value) > 0) {
- $client_ip = self::getIp($parent);
- $parent->executeQuery("UPDATE " . TABLE_LOCK_ACCESS . " SET `ip`='" . $client_ip . "',page='" . escape_str($parent->api_url) . "' ,lock_count=lock_count+1, `modified_on`='" . NOW . "' WHERE id='" . $lock_value[0]->id . "'");
- } else {
- $client_ip = self::getIp($parent);
- $parent->executeQuery("INSERT INTO " . TABLE_LOCK_ACCESS . " ( `auth_token`, `ip`, `lock_count`,page, `is_deleted`, `created_on`, `modified_on`) VALUES ('" . $access_token . "','" . $client_ip . "',1,'" . escape_str($parent->api_url) . "', 0, '" . NOW . "', '" . NOW . "')");
- }
- }
- /* ////////////////////////////////////////////////////////////////////////// */
- /* /////////////////////////////// INSERT LOG ////////////////////////////// */
- public static function insertUserLog($parent, $activity, $module_id = 0)
- {
- if ($parent->current_user_id != null) {
- $client_ip = self::getIp($parent);
- $parent->executeQuery("INSERT INTO " . TABLE_USER_LOG . " ( `userid`,`device_type`, `module`,module_id, `ip`, `created_on`) VALUES ('" . $parent->current_user_id . "','" . $parent->device_type . "','" . $activity . "','" . $module_id . "','" . $client_ip . "','" . NOW . "')");
- }
- }
- /* ////////////////////////////////////////////////////////////////////////// */
- /* /////////////////////////////// MASK MOBILE ////////////////////////////// */
- public static function maskMobileno($number)
- {
- $masked = str_pad(substr($number, -4), strlen($number), 'X', STR_PAD_LEFT);
- //$masked = substr($number,0,1).str_pad(substr($number, -4), (strlen($number)-1), 'X', STR_PAD_LEFT);
- return $masked;
- }
- /* ////////////////////////////////////////////////////////////////////////// */
- /* /////////////////////////////// IMAGE CROP ////////////////////////////// */
- public static function setImageCrop($parent, $file_path, $cord, $targ_w = 200, $targ_h = 300)
- {
- //$targ_w = 200;
- //$targ_h = 300;
- $jpeg_quality = 80;
- $img_r = self::imagecreatefromfile($parent, $file_path);
- $dst_r = ImageCreateTrueColor($targ_w, $targ_h);
- $cords = explode("|", $cord);
- //imagecopyresampled($dst_r,$img_r,0,0,(int)$cords[0],(int)$cords[1],$targ_w,$targ_h,(int)$cords[2],(int)$cords[3]);
- imagecopyresampled($dst_r, $img_r, 0, 0, (int) $cords[0], (int) $cords[1], $targ_w, $targ_h, (int) $cords[2], (int) $cords[3]);
- self::imagesavefile($parent, $dst_r, $file_path, $jpeg_quality);
- //shell_exec("sudo chmod -R 777 ".$file_path);
- chmod($file_path, 0777);
- }
- /* ////////////////////////////////////////////////////////////////////////// */
- /* /////////////////////////////// CREATE FILE ////////////////////////////// */
- public static function imagecreatefromfile($parent, $filename)
- {
- (!file_exists($filename)) ? $parent->response(array('response' => 'failed'), 403) : null;
- switch (strtolower(pathinfo($filename, PATHINFO_EXTENSION))) {
- case 'jpeg':
- case 'jpg':
- return imagecreatefromjpeg($filename);
- break;
- case 'png':
- return imagecreatefrompng($filename);
- break;
- case 'gif':
- return imagecreatefromgif($filename);
- break;
- default:
- $parent->response(array('response' => 'failed', 'message' => 'FILE IS NOT VALID JPG, PNG OR GIF IMAGE.'), 403);
- break;
- }
- }
- /* ////////////////////////////////////////////////////////////////////////// */
- /* /////////////////////////////// SAVE CROP FILE ////////////////////////////// */
- public static function imagesavefile($parent, $dst_r, $file_path, $jpeg_quality)
- {
- (!file_exists($file_path)) ? $parent->response(array('response' => 'failed', 'message' => 'FILE PATH NOT FOUND.'), 403) : null;
- switch (strtolower(pathinfo($file_path, PATHINFO_EXTENSION))) {
- case 'jpeg':
- case 'jpg':
- imagejpeg($dst_r, $file_path, $jpeg_quality);
- break;
- case 'png':
- imagepng($dst_r, $file_path);
- break;
- default:
- $parent->response(array('response' => 'failed', 'message' => 'FILE NOT VALID JPG, PNG OR GIF IMAGE.'), 403);
- break;
- }
- }
- /* ////////////////////////////////////////////////////////////////////////// */
- /* /////////////////////////////// UPLOAD FILE ////////////////////////////// */
- public static function uploadFile($parent, $obj)
- {
- $filekey = $obj->filekey;
- $path = $obj->path;
- $fileprefix = (isset($obj->fileprefix)) ? $obj->fileprefix : 'file';
- if (is_object($obj) && isset($_FILES[$obj->filekey])) {
- $tempFile = $_FILES[$obj->filekey]['tmp_name'];
- $fileParts = pathinfo($_FILES[$obj->filekey]['name']);
- $fileext_arr = explode('?', $fileParts['extension']);
- $fileExtension = strtolower($fileext_arr[0]);
- $file_prehead = (IS_LIVE_SERVER != '1') ? "_development" : "";
- $fileName = (isset($obj->filename)) ? $obj->filename . $file_prehead . '.' . $fileExtension : $fileprefix . '_' . date('YmdHis') . uniqid() . $file_prehead . '.' . $fileExtension;
- $targetFile = $path . $fileName;
- @move_uploaded_file($tempFile, $targetFile);
- //shell_exec("sudo chmod -R 777 ".$targetFile);
- chmod($targetFile, 0777);
- if (isset($obj->cord) && $obj->cord != null) {
- (isset($obj->width) && $obj->width != null && isset($obj->height) && $obj->height != null) ? self::setImageCrop($parent, $targetFile, $obj->cord, $obj->width, $obj->height) : self::setImageCrop($parent, $targetFile, $obj->cord);
- }
- return $fileName;
- }
- }
- /* ////////////////////////////////////////////////////////////////////////// */
- /* /////////////////////////////// USER OTP VALIDATE ////////////////////////////// */
- /*
- public static function validateUserOtp($parent,$otpval)
- {
- if($parent->current_user_id)
- {
- $query_checkvin=$parent->getQueryValue("SELECT * FROM ".TABLE_USER." WHERE user_id='".$parent->current_user_id."' LIMIT 1");
- if(count($query_checkvin)>0)
- {
- if($query_checkvin[0]->otp!=$otpval) $parent->response(array('response'=>'failed','message'=>'NOT VALID OTP'),200);
- if(!(strtotime(NOW)<strtotime($query_checkvin[0]->otp_time))) $parent->response(array('response'=>'failed','message'=>'OTP EXPIRED'),200);
- }else{
- $parent->response(array('response'=>'failed'), 401);
- }
- }else{
- $parent->response(array('response'=>'failed'), 401);
- }
- return null;
- }
- */
- /* ////////////////////////////////////////////////////////////////////////// */
- /* /////////////////////////////// GET EXCEL NUMBER ////////////////////////////// */
- public static function getNameFromNumber($num)
- {
- $numeric = $num % 26;
- $letter = chr(65 + $numeric);
- $num2 = intval($num / 26);
- if ($num2 > 0) {
- return self::getNameFromNumber($num2 - 1) . $letter;
- } else {
- return $letter;
- }
- }
- /* ////////////////////////////////////////////////////////////////////////// */
- /* /////////////////////////////// GET INDIAN MOBILE ////////////////////////////// */
- public static function getIndianMobile($mnum)
- {
- return substr($mnum, -10);
- }
- /* ////////////////////////////////////////////////////////////////////////// */
- /* /////////////////////////////// CHECK DATE GREATER ////////////////////////////// */
- public static function checkDateGreater($fdate, $sdate)
- {
- $reval = true;
- if ($fdate && $sdate && $fdate != '0000-00-00 00:00:00' && $sdate != '0000-00-00 00:00:00' && $fdate != '0000-00-00' && $sdate != '0000-00-00') {
- $reval = (strtotime($fdate) > strtotime($sdate)) ? true : false;
- }
- return $reval;
- }
- /* ////////////////////////////////////////////////////////////////////////// */
- /* /////////////////////////////// REMOVE DIRECTORY ////////////////////////////// */
- // rrmdir('../../uploads/zip/');
- public static function rrmdir($dir, $check = false)
- {
- if (is_dir($dir)) {
- $objects = scandir($dir);
- foreach ($objects as $object) {
- if ($object != "." && $object != "..") {
- if (filetype($dir . "/" . $object) == "dir") {
- self::rrmdir($dir . "/" . $object, true);
- } else {
- unlink($dir . "/" . $object);
- }
- }
- }
- reset($objects);
- ($check) ? rmdir($dir) : null;
- }
- }
- /* ////////////////////////////////////////////////////////////////////////// */
- /* ////////////////////////////////// ANDRIOD FCM FUNCTION ///////////////////////////// */
- private static function sendGoogleCloudMessage($messagearr, $reg_id)
- {
- //print_r($messagearr);
- //print_r($reg_id);
- $title = $messagearr['title'];
- $message = $messagearr['message'];
- $messagearr['body'] = $messagearr['message'];
- $fields = array(
- 'registration_ids' => $reg_id,
- 'priority' => "high",
- 'notification' => array("title" => $title, "body" => $message, "sound" => "default"),
- 'data' => $messagearr,
- );
- $headers = array(
- GOOGLE_FCM_URL,
- 'Content-Type: application/json',
- 'Authorization: key=' . GOOGLE_API_KEY,
- );
- // $ch = curl_init();
- // curl_setopt($ch, CURLOPT_URL, GOOGLE_FCM_URL);
- // curl_setopt($ch, CURLOPT_POST, true);
- // curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
- // curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- // curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
- // curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
- // $result = curl_exec($ch);
- // //echo $result;
- // curl_close($ch);
- echo $result="";
- }
- /* ////////////////////////////////////////////////////////////////////////// */
- /* ////////////////////////////////// IOS GCM FUNCTION ///////////////////////////// */
- private static function sendFCMIOSCloudMessage($messagearr, $reg_id)
- {
- //print_r($messagearr);
- //print_r($reg_id);
- $title = $messagearr['title'];
- $message = $messagearr['message'];
- $fields = array(
- //'to'=> $reg_id,
- "content_available" => true,
- 'registration_ids' => $reg_id,
- 'priority' => "high",
- 'aps' => array("content-available" => 1),
- 'notification' => $messagearr,
- //'data' => $messagearr,
- 'data' => array('published' => NOW),
- 'notId' => rand(1000, 9999),
- );
- $headers = array(
- GOOGLE_FCM_URL,
- 'Content-Type: application/json',
- 'Authorization: key=' . GOOGLE_API_KEY,
- );
- //echo "<br>";
- // $ch = curl_init();
- // curl_setopt($ch, CURLOPT_URL, GOOGLE_FCM_URL);
- // curl_setopt($ch, CURLOPT_POST, true);
- // curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
- // curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- // curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
- // curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
- // $result = curl_exec($ch);
- // //print_r($result);
- // curl_close($ch);
- echo $result="";
- }
- /* ////////////////////////////////////////////////////////////////////////// */
- /* ////////////////////////////////////// SEND NOTIFICATION ///////////////////////////////// */
- public static function sendUserNotification($message, $usertokenarr)
- {
- //STRUCTURE $usertokenarr =array('android'=>$arr,'ios'=>$arr);
- // $android_ids = (isset($usertokenarr['android'])) ? $usertokenarr['android'] : array();
- // $ios_ids = (isset($usertokenarr['ios'])) ? $usertokenarr['ios'] : array();
- // if (count($android_ids) > 0) {
- // $ids_arr = array_chunk($android_ids, 1000);
- // if (count($ids_arr) > 0) {
- // foreach ($ids_arr as $groupids) {
- // self::sendGoogleCloudMessage($message, $groupids);
- // }
- // }
- // }
- // if (count($ios_ids) > 0) {
- // $ids_arr = array_chunk($ios_ids, 1000);
- // if (count($ids_arr) > 0) {
- // foreach ($ids_arr as $groupids) {
- // self::sendFCMIOSCloudMessage($message, $groupids);
- // //self::sendIoCloudMessage($message, $groupids);
- // }
- // }
- // }
- }
- /* ////////////////////////////////////////////////////////////////////////// */
- /* ////////////////////////////////////// SLUG ///////////////////////////////// */
- public static function generate_slug($var)
- {
- if ($var) {
- $var = @str_replace(' ', '-', trim($var));
- $var = @strtolower($var);
- $slugname = @preg_replace('/[^A-Za-z0-9\-]/', '', $var);
- $slugname = @preg_replace('/-+/', '-', $slugname);
- }
- return $slugname;
- }
- /* ////////////////////////////////////////////////////////////////////////// */
- //KEY VALIDATION
- public static function validRequestKey($input, $type)
- {
- //TYPES : integer,string,double,array,object,date|Y-m-d
- switch ($type) {
- //VALID CONDITIONS
- case 'integer':return (ctype_digit(strval($input)));
- break;
- case 'string':return is_string($input);
- break;
- case 'number':return is_numeric($input);
- break;
- case 'double':return ((int) $input != $input && is_numeric($input));
- break;
- case 'array':return is_array($input);
- break;
- case 'object':return is_object($input);
- break;
- case 'date|Y-m-d':return self::isValidDateTimeString($input, 'Y-m-d', 'Asia/Kolkata');
- break;
- case 'date|Y-m-d H:i:s':return self::isValidDateTimeString($input, 'Y-m-d H:i:s', 'Asia/Kolkata');
- break;
- case 'date|d-m-Y':return self::isValidDateTimeString($input, 'd-m-Y', 'Asia/Kolkata');
- break;
- default:return false;
- break;
- }
- }
- //DATE VALIDATE
- public static function isValidDateTimeString($str_dt, $str_dateformat, $str_timezone)
- {
- $date = DateTime::createFromFormat($str_dateformat, $str_dt, new DateTimeZone($str_timezone));
- return $date && $date->format($str_dateformat) == $str_dt;
- }
- //MESSAGE RETURN
- public static function getMessage($parent, $lang, $module)
- {
- if (file_exists("../../language/" . $lang . "/common.php")) {
- include_once "../../language/" . $lang . "/common.php";
- if (!isset($string[$module])) {
- $parent->response(array('response' => 'failed', 'message' => 'MODULE LANGUAGE FILE NOT FOUND'), 500);
- }
- return $string[$module];
- } else {
- $parent->response(array('response' => 'failed', 'message' => 'LANGUAGE FILE NOT FOUND'), 500);
- exit;
- }
- }
- //SEND MAIL
- public static function sendMail($parent, $obj)
- {
- // if (IS_LIVE_SERVER != '1') {
- // $obj['to'] = 'lokesh.b@cygnusa.in';
- // if (isset($obj['cc'])) {
- // if (is_string($obj['cc'])) {
- // $cc = $obj['cc'];
- // $obj['cc'] = array();
- // $obj['cc'][] = $cc;
- // }
- // }
- // $obj['cc'][] = 'muthuramanr@cygnusa.in';
- // $obj['subject'] = 'DEVELOPMENT TESTING : ' . $obj['subject'];
- // }
- // require_once dirname(__FILE__) . '/phpmailer/PHPMailerAutoload.php';
- // require_once dirname(__FILE__) . '/phpmailer/class.phpmailer.php';
- // $mail = null;
- // try {
- // $mail = new PHPMailer;
- // $mail->isSMTP(); // telling the class to use SMTP
- // $mail->SMTPAuth = false; // enable SMTP authentication
- // //$mail->SMTPSecure = 'tls'; // sets the prefix to the servier
- // //$mail->SMTPDebug = 2;
- // $mail->Host = SMTP_HOST; // sets as the SMTP server
- // $mail->Port = SMTP_PORT; // set the SMTP port for the server
- // //$mail->Username = SMTP_USERNAME; // username
- // //$mail->Password = SMTP_PASSWORD; // password
- // // $mail->SMTPOptions = array(
- // // 'ssl' => array(
- // // 'verify_peer' => false,
- // // 'verify_peer_name' => false,
- // // 'allow_self_signed' => true
- // // )
- // // );
- // $mail->setFrom($obj['from']); //Set who the message is to be sent from
- // if (isset($obj['FromName'])) {
- // $mail->FromName = $obj['FromName'];
- // }
- // if (isset($obj['replayto'])) {
- // $mail->addReplyTo($obj['replayto']);
- // }
- // //TO EMAIL
- // $to_email = '';
- // if (isset($obj['to'])) {
- // if (is_array($obj['to'])) {
- // foreach ($obj['to'] as $res_to) {
- // $mail->addAddress($res_to);
- // }
- // $to_email = @implode(',', $obj['to']);
- // } else if (is_string($obj['to'])) {
- // $mail->addAddress($obj['to']);
- // $to_email = $obj['to'];
- // }
- // }
- // $mail->addBCC(SUPPORT_EMAIL);
- // //CC EMAIL
- // $cc_email = '';
- // if (isset($obj['cc'])) {
- // if (is_array($obj['cc'])) {
- // foreach ($obj['cc'] as $res_cc) {
- // $mail->AddCC($res_cc);
- // }
- // $cc_email = @implode(',', $obj['cc']);
- // } else if (is_string($obj['cc'])) {
- // $mail->AddCC($obj['cc']);
- // $cc_email = $obj['cc'];
- // }
- // }
- // //$mail->AddBCC($obj->to);
- // if (isset($obj['attachment_file'])) {
- // $file_count = count($obj['attachment_file']);
- // for ($x = 0; $x < $file_count; $x++) {
- // if (!empty($obj['attachment_file'][$x])) {
- // $mail->addAttachment($obj['attachment_file'][$x]);
- // }
- // }
- // }
- // $mail->isHTML(true);
- // $mail->Subject = $obj['subject'];
- // $contentmail = $obj['message'];
- // $mail->Body = $contentmail;
- // $parent->executeQuery("INSERT INTO " . TABLE_EMAIL_LOG . " (`to_mail`, `from_mail`, `cc_mail`, `subject`, `is_success`, `created_on`) VALUES ('" . escape_str($to_email) . "','" . $obj['from'] . "','" . escape_str($cc_email) . "','" . escape_str($obj['subject']) . "', '0','" . NOW . "' )");
- // $logid = $parent->lastInsertId();
- // if (!$mail->send()) {
- // //echo "Mailer Error: " . $mail->ErrorInfo;
- // $headers = "From: " . $obj['from'] . " \r\n";
- // //$headers .= "Reply-To: ".$replayto." \r\n";
- // $headers .= "MIME-Version: 1.0\r\n";
- // $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
- // // @mail(SUPPORT_EMAIL, "Mail delivery report", "FROM : " . $obj['from'] . ", TO :" . $obj['to'] . " mail not delivered", $headers);
- // } else {
- // $parent->executeQuery("UPDATE " . TABLE_EMAIL_LOG . " SET is_success='1' WHERE id='" . $logid . "' ");
- // }
- // } catch (phpmailerException $e) {
- // $headers = "From: " . $obj['from'] . " \r\n";
- // //$headers .= "Reply-To: ".$replayto." \r\n";
- // $headers .= "MIME-Version: 1.0\r\n";
- // $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
- // // @mail(SUPPORT_EMAIL, "Mail delivery report", "FROM : " . $obj['from'] . ", TO :" . $obj['to'] . " mail not delivered", $headers);
- // }
- }
- /* /////////////////////////////// FORGOTLINK ////////////////////////////// */
- public static function sendForgotPasswordLink($parent, $data)
- {
- switch ($data['type']) {
- case "test":
- $message = '<table width="100%" bgcolor="#dfdfdf" border="0" cellspacing="10" cellpadding="0" style="padding-top:10px;">
- <tbody><tr>
- <td><table width="700" border="0" align="center" cellpadding="0" cellspacing="0" style="background:#ffffff; margin-top:0px;">
- <tbody><tr>
- <td bgcolor="#2d2d2d" height="36" style="font-size:12px; font-family:Arial, Helvetica, sans-serif; color:#e4e4e4; text-align:left; font-weight:bold; padding-left:14px; border-bottom:2px solid #C71444">Password Reset</td>
- </tr>
- <tr><td><table width="85%" align="center">
- <tbody><tr><td height="30" style="font-size:12px; font-family:Arial, Helvetica, sans-serif; color:#3f3f3f; text-align:left;">Dear <span style="font-size:12px; font-family:Arial, Helvetica, sans-serif; color:#3f3f3f; text-align:left; font-weight:bold; text-transform:uppercase;">' . $data['send_to'] . ',</span></td>
- </tr><tr><td height="30" style="font-size:11px; font-family:Arial, Helvetica, sans-serif; color:#3f3f3f; text-align:left;padding-left: 10px;
- line-height: 1.5;"><div style="font-family:arial; color:#333; font-size:12px; padding:5px;">' . $data['link_value'] . '</div><div style="font-family:arial; color:#333; font-size:12px; padding:5px;" >This is an automatically generated email - please do not reply.</div></td>
- </tr>
- </tbody></table>
- </td>
- </tr>
- <tr>
- <td style="padding-top:0px; padding-bottom:10px;"></td>
- </tr>
- <tr>
- <td style="font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#3f3f3f; background:#fafafa; line-height:30px; text-align:center;border-bottom:2px solid #C71444"><div class="footer-con">
- <p>Thanks & Regards, <strong style="color:#C71444;"> Nissan Support Team</strong></p>
- </div></td>
- </tr>
- </tbody></table></td>
- </tr>
- </tbody></table>';
- $obj = array();
- $obj['from'] = SUPPORT_EMAIL;
- $obj['replayto'] = SUPPORT_EMAIL;
- $obj['to'] = $data['send_to'];
- $obj['subject'] = "Password Reset";
- $obj['message'] = $message;
- // self::sendMai($parent, $obj);
- break;
- case "email":
- $message = '<table width="100%" bgcolor="#dfdfdf" border="0" cellspacing="10" cellpadding="0" style="padding-top:10px;">
- <tbody><tr>
- <td><table width="700" border="0" align="center" cellpadding="0" cellspacing="0" style="background:#ffffff; margin-top:0px;">
- <tbody><tr>
- <td bgcolor="#2d2d2d" height="36" style="font-size:12px; font-family:Arial, Helvetica, sans-serif; color:#e4e4e4; text-align:left; font-weight:bold; padding-left:14px; ">Reset Password</td>
- </tr>
- <tr><td><table width="85%" align="center">
- <tbody><tr><td height="30" style="font-size:12px; font-family:Arial, Helvetica, sans-serif; color:#3f3f3f; text-align:left;">Hi <span style="font-size:12px; font-family:Arial, Helvetica, sans-serif; color:#3f3f3f; text-align:left; font-weight:bold; text-transform:uppercase;"> ' . $data['user']->fname . ',</span></td>
- </tr><tr><td height="30" style="font-size:11px; font-family:Arial, Helvetica, sans-serif; color:#3f3f3f; text-align:left;padding-left: 10px;
- line-height: 1.5;"><div style="font-family:arial; color:#333; font-size:12px; padding:5px;">A password reset was requested for your account <a href="#" >' . $data['user']->emailid . '</a> at PACCAR PARTS BIN <br>To confirm this request, and set a new password for your account. please go to the following web address:<br><br><a href="' . $data['link_value'] . '">' . $data['link_value'] . '</a><br>(This link is valid for 30 min from the time this reset was first requested) <br><br>If this password reset was not requested by you, no action is needed.<br>If you need help, please contact the site administrator.</div><div style="font-family:arial; color:#333; font-size:12px; padding:5px;" >This is an automatically generated email - please do not reply.<br><br>Admin User </div></td>
- </tr>
- </tbody></table>
- </td>
- </tr>
- <tr>
- <td style="padding-top:0px; padding-bottom:10px;"></td>
- </tr>
- <tr>
- <td style="font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#3f3f3f; background:#fafafa; line-height:30px; text-align:center;border-bottom:2px solid Black"><div class="footer-con">
- <p>Thanks & Regards, <strong style="color:Black"> Support Team</strong></p>
- </div></td>
- </tr>
- </tbody></table></td>
- </tr>
- </tbody></table>';
- $obj = array();
- $obj['from'] = SUPPORT_EMAIL;
- $obj['replayto'] = SUPPORT_EMAIL;
- $obj['to'] = $data['send_to'];
- $obj['subject'] = "FORGOT PASSWORD LINK";
- $obj['message'] = $message;
- // self::sendMai($parent, $obj);
- break;
- }
- }
- /////////////////////User creation Email /////////
- public static function sendUserWelcomeEmail($parent, $data)
- {
- //print_r($data);
- switch ($data['type']) {
- }
- }
- public static function sendSMS($parent, $mobileno, $message)
- {
- // $test = "0";
- // $username = SMS_USERNAME;
- // $hash = SMS_HASH;
- // $sender = SMS_SENDERID;
- // //SMS LOG
- // $parent->executeQuery("INSERT INTO " . TABLE_SMS_LOG . " (`smpin`, `emp_code`, `userid`, `mobile`, `sms_data`, `status`, `created_on`, `modified_on`) VALUES ('" . $parent->current_smpin . "','" . $parent->current_emp_code . "','" . $parent->current_user_id . "','" . $mobileno . "','" . $message . "','0','" . NOW . "','" . NOW . "')");
- // $sms_log_id = $parent->lastInsertId();
- // $result = '';
- // if (strlen($mobileno) > 9) {
- // $method = "SendMessage";
- // $msgType = "TEXT";
- // $v = "1.1";
- // $format = "text";
- // $numbers = "91" . $mobileno;
- // //$data = "method=" . $method . "&send_to=" . $numbers . "&msg=" . $message . "&msg_type=" . $msgType . "&loginid=" . $username . "&auth_scheme=plain&password=" . $hash . "&v=" . $v . "&format=" . $format . "&mask=" . $sender;
- // $data = "username=" . $username . "&password=" . $hash . "&to=" . $numbers . "&from=" . $sender . "&text=" . urlencode($message) . "&dlr-mask=19&dlr-url";
- // $ch = curl_init(SMS_APIURL);
- // curl_setopt($ch, CURLOPT_POST, true);
- // curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
- // curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- // $result = curl_exec($ch); // This is the result from the API
- // curl_close($ch);
- // }
- // $status = '0';
- // if ($result == 'Sent.') {
- // $status = 1;
- // }
- // //UPDATE LOG
- // $parent->executeQuery("UPDATE " . TABLE_SMS_LOG . " SET `status`='" . $status . "', `response`='" . escape_str($result) . "', `modified_on`='" . NOW . "' WHERE id='" . $sms_log_id . "'");
- $result = 'Sent.';
- return $result;
- }
- ////////////////////////////EMD USER EMAIl//////////////////////
- }
|