Commit 94bdb173 authored by Kulya's avatar Kulya 😊

Change BxRestClass

parent 8a5f30eb
<?php namespace AloVoice;
//define('C_REST_CLIENT_ID','local.5da49496afd525.43670682');//Application ID
//define('C_REST_CLIENT_SECRET','aDw7TQ4K337vkWLKTwXyHQTfeOPWgJy5T7LMdX6rR1TD79ev47');//Application key
define('C_REST_CLIENT_ID','local.5ff5d5b915c916.88440927');//Application ID
define('C_REST_CLIENT_SECRET','0EcLQuSN2M3anM1A9vroaGZCWnh9g0jJcT53lIRyoG16CR61ot');//Application key
// or
//define('C_REST_WEB_HOOK_URL','https://rest-api.bitrix24.com/rest/1/doutwqkjxgc3mgc1/');//url on creat Webhook
//define('C_REST_WEB_HOOK_URL','https://4uz.bitrix24.ru/rest/6/gik26zgjzpoe6qhb/');//url on creat Webhook
define('C_REST_CURRENT_ENCODING','utf-8');//'windows-1251'
define('C_REST_IGNORE_SSL',true);//turn off validate ssl by curl
define('C_REST_LOG_TYPE_DUMP',true); //logs save var_export for viewing convenience
define('C_REST_BLOCK_LOG',true);//turn off default logs
define('C_REST_LOGS_DIR', __DIR__ .'/logs/'); //directory path to save the log
//define("C_REST_WEB_HOOK_URL",true);
use AloVoice\AloVoiceConnector as ALVC;
class BitrixRest {
const BATCH_COUNT = 50;//count batch 1 query
const TYPE_TRANSPORT = 'json';// json or xml
/**
* call where install application even url
* only for rest application, not webhook
*/
public static function alovoice_update_dongles_accounts($params){
if(!empty($params["device"])){
$resUpdateDongles = AloVoiceActions::updateOneDongleAccount($params);
} else {
$resUpdateDongles = AloVoiceActions::updateDonglesAccount();
}
return $resUpdateDongles;
}
public static function alovoice_dongle_channels(){
$arGsmLines = AloVoiceActions::getDongles();
$sendersAns = self::call("messageservice.sender.list",array());
$bxSmsSenders = $sendersAns["result"];
return array( "gsmlines" => $arGsmLines, "smssenders" => $bxSmsSenders );
}
public static function sms_serviceslist(){
//$smsServices = array(
// array("code"=>"allonote", "name"=>"AloSMS"),
//);
$arSmsLines = AloVoiceActions::getDongles();
ALVC::eLog($arSmsLines,"--== arSmsLines DONGLES: on ASTER");
$arSendersList = self::doMethod(array("restmethod"=>"messageservice.sender.list"));
$allSmsLines = array();
foreach($arSmsLines as $smsln){
if(in_array($smsln["code"],$arSendersList)){
$smsln["active"] = 'Y';
} else {
$smsln["active"] = 'N';
}
$allSmsLines[] = $smsln;
}
ALVC::eLog($allSmsLines,"--== allSmsLines LIST check: on BITRIX");
return $allSmsLines;
}
public static function is_allotginstalled(){
$arSendersList = self::doMethod(array("restmethod"=>"messageservice.sender.list"));
ALVC::eLog($arSendersList,"--== arSendersList LIST check: on BITRIX");
return (in_array("allotg",$arSendersList));
}
public static function is_allonoteInstalled(){
$arSendersList = self::doMethod(array("restmethod"=>"messageservice.sender.list"));
ALVC::eLog($arSendersList,"--== arSendersList LIST check: on BITRIX");
return (in_array("allonote",$arSendersList));
}
public static function doMethod($params){
if( $params["restmethod"] == "get_crmelems_all_list"){
$elementList = self::call("crm.".$params["enttype"].".list",array());
return $sendersAns["result"];
}
if( $params["restmethod"] == "is_callslisten"){
$listenEvents = BitrixRest::isListenCalls();
if( !empty($listenEvents["ONEXTERNALCALLSTART"]) ){
return '<span style="color:green; font-weight:bold;">Обработывается... </span>';
}
}
if( $params["restmethod"] == "alovoice_settings"){
$alv_AllSettings = ALVC::getConfigs();
return $alv_AllSettings["asterisk_options"];
}
if( $params["restmethod"] == "alovoice_update_dongles_accounts"){
return self::alovoice_update_dongles_accounts($params);
}
if( $params["restmethod"] == "alovoice_dongle_channels"){
return self::alovoice_dongle_channels();
}
if( $params["restmethod"] == "sms_serviceslist"){
return self::sms_serviceslist();
}
if( $params["restmethod"] == "is_allonoteInstalled"){
return self::is_allonoteInstalled();
}
if($params["restmethod"] == "is_allotginstalled"){
return self::is_allotginstalled();
}
if($params["restmethod"] == "messageservice.sender.list"){
$sendersAns = []; //self::call("messageservice.sender.list",array());
return $sendersAns["result"];
}
if($params["restmethod"] == "crm.activity.add"){
ALVC::eLog($params,"--== crm.activity.add: PARAMS:");
//$params["tg_number"]
//$params["tg_message"]
/*
if(!empty($acvId)){
$crmActivitiUpdating = BitrixRest::call("crm.activity.update",array(
'id' =>$acvId,
'fields' => array(
'COMPLETED' => 'Y',
'SUBJECT' => "Телеграм сообщение отправлено!",
'DESCRIPTION' => "Отправленное Телеграм сообщение".time()
)
));
ALVC::eLog($crmActivitiUpdating,"--== crm Activiti UPDATING");
}*/
}
if($params["restmethod"] == "crm.activity.type.delete"){
ALVC::eLog($params,"--== crm.activity.type.delete: PARAMS:");
return BitrixRest::call("crm.activity.type.delete",array(
'TYPE_ID'=>$params["TYPE_ID"],
));
}
if($params["restmethod"] == "placement.bind"){
if(!empty($params["TITLE"]) && !empty($params["PLACEMENT"])){
return self::call("placement.bind",array(
'PLACEMENT' => $params["PLACEMENT"],
'HANDLER' => (!empty($params["HANDLER"])) ? $params["HANDLER"] : $_SESSION["query_data"]["client_endpoint"],
'TITLE' => $params["TITLE"]
));
}
}
if($params["restmethod"] == "placement.unbind"){
if(!empty($params["HANDLER"]) && !empty($params["PLACEMENT"])){
return self::call("placement.unbind",array(
'PLACEMENT' => $params["PLACEMENT"],
'HANDLER' => (!empty($params["HANDLER"])) ? $params["HANDLER"] : $_SESSION["query_data"]["client_endpoint"],
));
}
}
if($params["restmethod"] == "alovoice_index"){
$resCallEvents = self::call("event.get",array());
return $resCallEvents;
}
return true;
}
public static function installApp()
{
$result = array(
'rest_only' => true,
'install' => false
);
if($_REQUEST[ 'event' ] == 'ONAPPINSTALL' && !empty($_REQUEST[ 'auth' ]))
{
$result['install'] = static::setAppSettings($_REQUEST[ 'auth' ], true);
}
elseif($_REQUEST['PLACEMENT'] == 'DEFAULT')
{
$result['rest_only'] = false;
$result['install'] = static::setAppSettings(
array(
'access_token' => htmlspecialchars($_REQUEST['AUTH_ID']),
'expires_in' => htmlspecialchars($_REQUEST['AUTH_EXPIRES']),
'application_token' => htmlspecialchars($_REQUEST['APP_SID']),
'refresh_token' => htmlspecialchars($_REQUEST['REFRESH_ID']),
'domain' => htmlspecialchars($_REQUEST['DOMAIN']),
'client_endpoint' => 'https://' . htmlspecialchars($_REQUEST['DOMAIN']) . '/rest/',
),
true
);
}
static::setLog(
array(
'request' => $_REQUEST,
'result' => $result
),
'installApp'
);
header("Location: ".$_SERVER["SCRIPT_NAME"]);
//return $result;
}
/**
* @var $arParams array
* $arParams = [
* 'method' => 'some rest method',
* 'params' => []//array params of method
* ];
* @return mixed array|string|boolean curl-return or error
*
*/
public static function isTelegramAgentListen(){
$listBxBotsGet = BitrixRest::call("imbot.bot.list",array());
ALVC::eLog($listBxBotsGet,"-------------------== listBxBotsGet: ----------------");
$listenTgAgent = false;
$listenTgAgentId = false;
if(!empty($listBxBotsGet["result"])){
foreach($listBxBotsGet["result"] as $bxBot){
if( $bxBot["CODE"] == 'tg24' ){
$listenTgAgent = true;
$listenTgAgentId = $bxBot["ID"];
}
}
}
if( $listenTgAgent !== true ){
$arConfs = ALVC::getConfigs();
$regTgAgentBot = BitrixRest::call("imbot.register",array(
'CODE' => 'tg24',
'TYPE' => 'S',
'EVENT_HANDLER' => $arConfs["asterisk_host"],
'OPENLINE' => 'Y',
'PROPERTIES' => Array(
'NAME' => 'TG24',
'LAST_NAME' => '',
'COLOR' => 'DARK_BLUE',
'PERSONAL_GENDER' => ''
)
));
ALVC::eLog($regTgAgentBot,"-------------------== regTgAgentBot RES: ----------------");
$listenTgAgentId = $regTgAgentBot["result"];
}
/*
BX24.callMethod("imbot.update",{
'BOT_ID': 64,
'FIELDS': {
'EVENT_HANDLER': 'https://sms.4u.uz/bx24/',
'OPENLINE': 'Y',
'PROPERTIES': {
'NAME' : 'TG24',
'LAST_NAME' : '',
'COLOR' : 'DARK_BLUE',
'PERSONAL_GENDER' : '',
'PERSONAL_PHOTO' : 'iVBORw0KGgoAAAANSUhEUgAAAD0AAAA9CAYAAAAeYmHpAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQ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YnO0fMToin8fLNLxmUWyhb9Cx8WFFD3+uRg/fVdC1zgIWUCAMhv8CZwNf0G7nCYwAAAAASUVORK5CYII='
}
},
},function(result){
console.log("Update ChatBOT:",result);
});
*/
/*$result = restCommand('imbot.register', Array(
'CODE' => 'newbot', // Строковой идентификатор бота, уникальный в рамках вашего приложения (обяз.)
'TYPE' => 'H', // Тип бота, B - чат-бот, ответы поступают сразу, H - человек, ответы поступают с задержкой от 2-х до 10 секунд, O - чат-бот для Открытых линий, S - чат-бот с повышенными привилегиями (supervisor)
'EVENT_HANDLER' => 'http://www.hazz/chatApi/event.php', // Ссылка на обработчик событий поступивших от сервера, см. Обработчики событий ниже (обяз).
'OPENLINE' => 'Y', // Включение режима поддержки Открытых линий, можно не указывать, если TYPE = 'O'
'CLIENT_ID' => '', // строковый идентификатор чат-бота, используется только в режиме Вебхуков
'PROPERTIES' => Array( // Личные данные чат-бота (обяз.)
'NAME' => 'NewBot', // Имя чат-бота (обязательное одно из полей NAME или LAST_NAME)
'LAST_NAME' => '', // Фамилия чат-бота (обязательное одно из полей NAME или LAST_NAME)
'COLOR' => 'GREEN', // Цвет чат-бота для мобильного приложения RED, GREEN, MINT, LIGHT_BLUE, DARK_BLUE, PURPLE, AQUA, PINK, LIME, BROWN, AZURE, KHAKI, SAND, MARENGO, GRAY, GRAPHITE
'EMAIL' => 'test@test.ru', // E-mail для связи. НЕЛЬЗЯ использовать e-mail, дублирующий e-mail реальных пользователей
'PERSONAL_BIRTHDAY' => '2016-03-11', // День рождения в формате YYYY-mm-dd
'WORK_POSITION' => 'Мой первый бот', // Занимаемая должность, используется как описание чат-бота
'PERSONAL_WWW' => 'http://test.ru', // Ссылка на сайт
'PERSONAL_GENDER' => 'F', // Пол чат-бота, допустимые значения M - мужской, F - женский, пусто, если не требуется указывать
'PERSONAL_PHOTO' => '', // Аватар чат-бота - base64
)
), $_REQUEST["auth"]);
*/
return $listenTgAgentId;
}
public static function isListenCalls(){
ALVC::eLog("--================== EVENTs check ===============------------");
$arConfs = ALVC::getConfigs();
$eventsResult = self::call('event.get');
$needBindEvents = array(
"ONCRMDEALADD",
"ONCRMLEADADD",
"ONIMCOMMANDADD",
"ONIMBOTMESSAGEADD",
"ONEXTERNALCALLSTART",
);
$allListenEvents = array();
if(!empty($eventsResult["result"])){
foreach($eventsResult["result"] as $eEvent){
if(in_array($eEvent["event"],$needBindEvents)){
if($eEvent["handler"] == $arConfs["asterisk_host"]){
$allListenEvents[$eEvent["event"]] = $eEvent;
$needBindEvents = array_diff($needBindEvents, array($eEvent["event"]) );
}
}
}
}
if(!empty($needBindEvents)){
$binEventParams = array();
foreach($needBindEvents as $bEvent){
$binEventParams[] = array( "method" => "event.bind", "params" => array( "event" => $bEvent, "handler" => $arConfs["asterisk_host"] ));
}
$allBitrixQuerys = BitrixRest::callBatch($binEventParams);
}
ALVC::eLog("--================== EVENTs check END===============------------");
return $allListenEvents;
}
protected static function callCurl($arParams, $frommApp=false)
{
if(!function_exists('curl_init'))
{
return array(
'error' => 'error_php_lib_curl',
'error_information' => 'need install curl lib'
);
}
$arSettings = static::getAppSettings();
//ALVC::eLog($arSettings, "== BitrixRest: callCurl: arSettings:");
if($arSettings !== false)
{
$thisAuthCh = (!empty($arParams[ 'this_auth' ])) ? $arParams[ 'this_auth' ] : "";
if($thisAuthCh == 'Y')
{
$url = 'https://oauth.bitrix.info/oauth/token/';
}
else
{
$url = $arSettings[ "client_endpoint" ] . $arParams[ 'method' ] . '.' . static::TYPE_TRANSPORT;
if(empty($arSettings[ 'is_web_hook' ]) || $arSettings[ 'is_web_hook' ] != 'Y')
{
$arParams[ 'params' ][ 'auth' ] = $arSettings[ 'access_token' ];
}
}
$sPostFields = http_build_query($arParams[ 'params' ]);
try
{
$obCurl = curl_init();
curl_setopt($obCurl, CURLOPT_URL, $url);
curl_setopt($obCurl, CURLOPT_RETURNTRANSFER, true);
if($sPostFields)
{
curl_setopt($obCurl, CURLOPT_POST, true);
curl_setopt($obCurl, CURLOPT_POSTFIELDS, $sPostFields);
}
curl_setopt(
$obCurl, CURLOPT_FOLLOWLOCATION, (isset($arParams[ 'followlocation' ]))
? $arParams[ 'followlocation' ] : 1
);
if(defined("C_REST_IGNORE_SSL") && C_REST_IGNORE_SSL === true)
{
curl_setopt($obCurl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($obCurl, CURLOPT_SSL_VERIFYHOST, false);
}
$out = curl_exec($obCurl);
$info = curl_getinfo($obCurl);
if(curl_errno($obCurl))
{
$info[ 'curl_error' ] = curl_error($obCurl);
}
$thisAuthCh = (!empty($arParams[ 'this_auth' ])) ? $arParams[ 'this_auth' ] : "";
if($thisAuthCh != 'Y' && static::TYPE_TRANSPORT == 'xml')//auth only json support
{
$result = $out;
}
else
{
$result = static::expandData($out);
}
curl_close($obCurl);
//ALVC::eLog($result,"==callCurl RESULT:");
if(!empty($result[ 'error' ]))
{
if($result[ 'error' ] == 'expired_token' && empty($arParams[ 'this_auth' ]))
{
$result = static::GetNewAuth($arParams);
}
else
{
$arErrorInform = array(
'expired_token' => 'expired token, cant get new auth? Check access oauth server.',
'invalid_token' => 'invalid token, need reinstall application',
'invalid_grant' => 'invalid grant, check out define C_REST_CLIENT_SECRET or C_REST_CLIENT_ID',
'invalid_client' => 'invalid client, check out define C_REST_CLIENT_SECRET or C_REST_CLIENT_ID',
'QUERY_LIMIT_EXCEEDED' => 'Too many requests, maximum 2 query by second',
'ERROR_METHOD_NOT_FOUND' => 'Method not found! You can see the permissions of the application: CRest::call(\'scope\')',
'NO_AUTH_FOUND' => 'Some setup error b24, check in table "b_module_to_module" event "OnRestCheckAuth"',
'INTERNAL_SERVER_ERROR' => 'Server down, try later'
);
if(!empty($arErrorInform[ $result[ 'error' ] ]))
{
$result[ 'error_information' ] = $arErrorInform[ $result[ 'error' ] ];
}
}
}
if(!empty($info[ 'curl_error' ]))
{
$result[ 'error' ] = 'curl_error';
$result[ 'error_information' ] = $info[ 'curl_error' ];
}
static::setLog(
array(
'url' => $url,
'info' => $info,
'params' => $arParams,
'result' => $result
),
'callCurl'
);
return $result;
}
catch(Exception $e)
{
return array(
'error' => 'exception',
'error_information' => $e -> getMessage(),
);
}
}
return array(
'error' => 'no_install_app',
'error_information' => 'error install app, pls install local application '
);
}
/**
* Generate a request for callCurl()
*
* @var $method string
* @var $params array method params
* @return mixed array|string|boolean curl-return or error
*/
public static function call($method, $params = array(),$fromapp=false)
{
/*
$appSettings = self::getSettingData();
if(empty($appSettings)){
self::installApp();
return true;
}
*/
$arPost = array(
'method' => $method,
'params' => $params
);
if(defined('C_REST_CURRENT_ENCODING'))
{
$arPost[ 'params' ] = static::changeEncoding($arPost[ 'params' ]);
}
$result = static::callCurl($arPost,$fromapp);
return $result;
}
/**
* @example $arData:
* $arData = [
* 'find_contact' => [
* 'method' => 'crm.duplicate.findbycomm',
* 'params' => [ "entity_type" => "CONTACT", "type" => "EMAIL", "values" => array("info@bitrix24.com") ]
* ],
* 'get_contact' => [
* 'method' => 'crm.contact.get',
* 'params' => [ "id" => '$result[find_contact][CONTACT][0]' ]
* ],
* 'get_company' => [
* 'method' => 'crm.company.get',
* 'params' => [ "id" => '$result[get_contact][COMPANY_ID]', "select" => ["*"],]
* ]
* ];
*
* @var $arData array
* @var $halt integer 0 or 1 stop batch on error
* @return array
*
*/
public static function callBatch($arData, $halt = 0)
{
$arResult = array();
if(is_array($arData))
{
if(defined('C_REST_CURRENT_ENCODING'))
{
$arData = static::changeEncoding($arData);
}
$arDataRest = array();
$i = 0;
foreach($arData as $key => $data)
{
if(!empty($data[ 'method' ]))
{
$i++;
if(static::BATCH_COUNT > $i)
{
$arDataRest[ 'cmd' ][ $key ] = $data[ 'method' ];
if(!empty($data[ 'params' ]))
{
$arDataRest[ 'cmd' ][ $key ] .= '?' . http_build_query($data[ 'params' ]);
}
}
}
}
if(!empty($arDataRest))
{
$arDataRest[ 'halt' ] = $halt;
$arPost = array(
'method' => 'batch',
'params' => $arDataRest
);
$arResult = static::callCurl($arPost);
}
}
return $arResult;
}
/**
* Getting a new authorization and sending a request for the 2nd time
*
* @var $arParams array request when authorization error returned
* @return array query result from $arParams
*
*/
private static function GetNewAuth($arParams)
{
$result = array();
$arSettings = static::getAppSettings();
if($arSettings !== false)
{
$arParamsAuth = array(
'this_auth' => 'Y',
'params' =>
array(
'client_id' => $arSettings[ 'C_REST_CLIENT_ID' ],
'grant_type' => 'refresh_token',
'client_secret' => $arSettings[ 'C_REST_CLIENT_SECRET' ],
'refresh_token' => $arSettings[ "refresh_token" ],
)
);
$newData = static::callCurl($arParamsAuth);
if(isset($newData[ 'C_REST_CLIENT_ID' ]))
{
unset($newData[ 'C_REST_CLIENT_ID' ]);
}
if(isset($newData[ 'C_REST_CLIENT_SECRET' ]))
{
unset($newData[ 'C_REST_CLIENT_SECRET' ]);
}
if(isset($newData[ 'error' ]))
{
unset($newData[ 'error' ]);
}
if(static::setAppSettings($newData))
{
$arParams[ 'this_auth' ] = 'N';
$result = static::callCurl($arParams);
}
}
return $result;
}
/**
* @var $arSettings array settings application
* @var $isInstall boolean true if install app by installApp()
* @return boolean
*/
private static function setAppSettings($arSettings, $isInstall = false)
{
$return = false;
if(is_array($arSettings))
{
$oldData = static::getAppSettings();
if($isInstall != true && !empty($oldData) && is_array($oldData))
{
$arSettings = array_merge($oldData, $arSettings);
}
$return = static::setSettingData($arSettings);
}
return $return;
}
/**
* @return mixed setting application for query
*/
private static function getSettingData(){
$nowt = time();
//ALVC::eLog($_SESSION, "== BitrixRest: getSettingData: _SESSION:".$nowt);
if( empty($_SESSION["query_data"]) ){
$arConfs = ALVC::getConfigs();
if(!empty($_REQUEST["auth"]["access_token"])){
//ALVC::eLog($_REQUEST["auth"], "== BitrixRest: getSettingData: REQUEST['auth']");
$sysConfs = $_REQUEST["auth"];
} else {
$backTrace = debug_backtrace();
//echo "<PRE>";
//var_dump($backTrace);
//echo "</PRE>";
//ALVC::eLog($backTrace, "== BitrixRest: getSettingData: BACKTRACE:");
foreach($backTrace as $bktr ){
if($bktr["class"]=="AloVoice\\AloVoiceConnector" && $bktr["function"]=="registration" ){
if(!empty($arConfs["install"])){
//ALVC::eLog($arConfs["install"], "== BitrixRest: getSettingData: arConfs['install']");
$sysConfs = json_decode($arConfs["install"],true);
}
break;
}
if($bktr["class"]=="AloVoice\\BitrixEvents" && $bktr["function"]=="incom_tgmessage" ){
if(!empty($arConfs["install"])){
//ALVC::eLog($arConfs["install"], "== BitrixRest: getSettingData: arConfs['install']");
$sysConfs = json_decode($arConfs["install"],true);
}
break;
}
if($bktr["class"]=="AloVoice\\AloVoiceHandle"){
if(!empty($arConfs["install"])){
//ALVC::eLog($arConfs["install"], "== BitrixRest: getSettingData: arConfs['install']");
$sysConfs = json_decode($arConfs["install"],true);
}
break;
}
}
}
if(!empty($sysConfs)){
$sysConfs["C_REST_CLIENT_ID"] = $arConfs["bx_client_id"];
$sysConfs["C_REST_CLIENT_SECRET"] = $arConfs["bx_client_secret"];
//ALVC::eLog($sysConfs, "== BitrixRest: getSettingData: sysConfs:");
return $sysConfs;
} else {
//ALVC::eLog("== BitrixRest: getSettingData: No Session, No Auth, No Install auth...");
return false;
}
}
if( $_SESSION["query_data"]["expires"]< $nowt ){
return false;
}
return $_SESSION["query_data"];
}
private static function getAppSettings()
{
if( defined("C_REST_WEB_HOOK_URL") )
//if( !empty(C_REST_WEB_HOOK_URL) )
{
$arData = array(
'client_endpoint' => C_REST_WEB_HOOK_URL,
'is_web_hook' => 'Y'
);
$isCurrData = true;
}
else
{
$arData = static::getSettingData();
//ALVC::eLog($arData, "== BitrixRest: getAppSettings: arData:");
$isCurrData = false;
if(
!empty($arData[ 'access_token' ]) &&
!empty($arData[ 'domain' ]) &&
//!empty($arData[ 'refresh_token' ]) &&
//!empty($arData[ 'application_token' ]) &&
!empty($arData[ 'client_endpoint' ])
)
{
$isCurrData = true;
if(empty($arData[ 'application_token' ])){
$arConfs = ALVC::getConfigs();
$arData[ 'application_token' ] = $arConfs["bx_application_token"];
}
}
}
//{"access_token":"f0d8b15d0041355e004080f000000001201c036b4311f067844495bd61f97978715a0d","expires":1571936496,"expires_in":3600,"scope":"app,crm,log,user","domain":"4uz.bitrix24.ru","server_endpoint":"https:\/\/oauth.bitrix.info\/rest\/","status":"L","client_endpoint":"https:\/\/4uz.bitrix24.ru\/rest\/","member_id":"cbb436f0f1d7471ce732a524cb8aeb17","user_id":1,"refresh_token":"e057d95d0041355e004080f000000001201c032bf6d447bdc9d3d27a0345d5953fd58e","ts":1571932896}
return ($isCurrData) ? $arData : false;
}
/**
* Can overridden this method to change the data storage location.
*
* @return array setting for getAppSettings()
*/
protected static function oldgetSettingData()
{
$return = array();
if(file_exists(__DIR__ . '/settings.json'))
{
$return = static::expandData(file_get_contents(__DIR__ . '/settings.json'));
if(empty($return)){ return false; }
$app_client_id = (defined("C_REST_CLIENT_ID")) ? C_REST_CLIENT_ID : false;
$app_client_secret = (defined("C_REST_CLIENT_SECRET")) ? C_REST_CLIENT_SECRET : false;
if(!empty($app_client_id))
{
$return['C_REST_CLIENT_ID'] = $app_client_id;
}
if(!empty($app_client_secret))
{
$return['C_REST_CLIENT_SECRET'] = $app_client_secret;
}
}
return $return;
}
/**
* @var $data mixed
* @var $encoding boolean true - encoding to utf8, false - decoding
*
* @return string json_encode with encoding
*/
protected static function changeEncoding($data, $encoding = true)
{
if(is_array($data))
{
$result = array();
foreach ($data as $k => $item)
{
$k = static::changeEncoding($k, $encoding);
$result[$k] = static::changeEncoding($item, $encoding);
}
}
else
{
if($encoding)
{
$result = iconv(C_REST_CURRENT_ENCODING, "UTF-8//TRANSLIT", $data);
}
else
{
$result = iconv( "UTF-8",C_REST_CURRENT_ENCODING, $data);
}
}
return $result;
}
/**
* @var $data mixed
* @var $debag boolean
*
* @return string json_encode with encoding
*/
protected static function wrapData($data, $debag = false)
{
if(defined('C_REST_CURRENT_ENCODING'))
{
$data = static::changeEncoding($data, true);
}
$return = json_encode($data, JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_APOS|JSON_HEX_QUOT);
if($debag)
{
$e = json_last_error();
if ($e != JSON_ERROR_NONE)
{
if ($e == JSON_ERROR_UTF8)
{
return 'Failed encoding! Recommended \'UTF - 8\' or set define C_REST_CURRENT_ENCODING = current site encoding for function iconv()';
}
}
}
return $return;
}
/**
* @var $data mixed
* @var $debag boolean
*
* @return string json_decode with encoding
*/
protected static function expandData($data)
{
$return = json_decode($data, true);
if(defined('C_REST_CURRENT_ENCODING'))
{
$return = static::changeEncoding($return, false);
}
return $return;
}
/**
* Can overridden this method to change the data storage location.
*
* @var $arSettings array settings application
* @return boolean is successes save data for setSettingData()
*/
protected static function setSettingData($arSettings)
{
$arConfs = ALVC::getConfigs();
$arConfs["install"] = static::wrapData($arSettings);
ALVC::setConfigs($arConfs);
return true;
//return (boolean)file_put_contents(__DIR__ . '/settings.json', static::wrapData($arSettings));
}
/**
* Can overridden this method to change the log data storage location.
*
* @var $arData array of logs data
* @var $type string to more identification log data
* @return boolean is successes save log data
*/
public static function setLog($arData, $type = '')
{
ALVC::eLog($arData,"BitrixRest: ".$type.": ");
return true;
/*
$return = false;
if(!defined("C_REST_BLOCK_LOG") || C_REST_BLOCK_LOG !== true)
{
if(defined("C_REST_LOGS_DIR"))
{
$path = C_REST_LOGS_DIR;
}
else
{
$path = __DIR__ . '/logs/';
}
$path .= date("Y-m-d/H") . '/';
@mkdir($path, 0775, true);
$path .= time() . '_' . $type . '_' . rand(1, 9999999) . 'log';
if(!defined("C_REST_LOG_TYPE_DUMP") || C_REST_LOG_TYPE_DUMP !== true)
{
$return = file_put_contents($path . '.json', static::wrapData($arData));
}
else
{
$return = file_put_contents($path . '.txt', var_export($arData, true));
}
}
return $return;*/
}
/**
* check minimal settings server to work CRest
* @var $print boolean
* @return array of errors
*/
public static function checkServer($print = true)
{
$return = array();
//check curl lib install
if(!function_exists('curl_init'))
{
$return['curl_error'] = 'Need install curl lib.';
}
/*
//creat setting file
file_put_contents(__DIR__ . '/settings_check.json', static::wrapData(array('test'=>'data')));
if(!file_exists(__DIR__ . '/settings_check.json'))
{
$return['setting_creat_error'] = 'Check permission! Recommended: folders: 775, files: 664';
}
unlink(__DIR__ . '/settings_check.json');
*/
/*
//creat logs folder and files
$path = __DIR__ . '/logs/'.date("Y-m-d/H") . '/';
if(!mkdir($path, 0775, true) && !file_exists($path))
{
$return['logs_folder_creat_error'] = 'Check permission! Recommended: folders: 775, files: 664';
}
else
{
file_put_contents($path . 'test.txt', var_export(array('test'=>'data'), true));
if(!file_exists($path . 'test.txt'))
{
$return['logs_file_creat_error'] = 'check permission! recommended: folders: 775, files: 664';
}
unlink($path . 'test.txt');
}
*/
if($print === true)
{
if(empty($return))
{
$return['success'] = 'Success!';
}
echo '<pre>';
print_r($return);
echo '</pre>';
}
return $return;
}
/**
* Совершает запрос с заданными данными по заданному адресу. В ответ ожидается JSON
*
* @param string $method GET|POST
* @param string $url адрес
* @param array|null $data POST-данные
*
* @return array
*/
public function query($method, $url, $data = null){
$query_data = "";
$curlOptions = array(
CURLOPT_RETURNTRANSFER => true
);
if($method == "POST")
{
$curlOptions[CURLOPT_POST] = true;
$curlOptions[CURLOPT_POSTFIELDS] = http_build_query($data);
}
elseif(!empty($data))
{
$url .= strpos($url, "?") > 0 ? "&" : "?";
$url .= http_build_query($data);
}
$curl = curl_init($url);
curl_setopt_array($curl, $curlOptions);
$result = curl_exec($curl);
return json_decode($result, 1);
}
public function ucall($url, $params) {
return self::query("POST", $url, $params);
}
}
?>
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment