403Webshell
Server IP : 80.87.202.40  /  Your IP : 216.73.216.169
Web Server : Apache
System : Linux rospirotorg.ru 5.14.0-539.el9.x86_64 #1 SMP PREEMPT_DYNAMIC Thu Dec 5 22:26:13 UTC 2024 x86_64
User : bitrix ( 600)
PHP Version : 8.2.27
Disable Function : NONE
MySQL : OFF |  cURL : ON |  WGET : ON |  Perl : ON |  Python : OFF |  Sudo : ON |  Pkexec : ON
Directory :  /home/bitrix/ext_www/rospirotorg.ru/bitrix/modules/grain.iiko/lib/

Upload File :
current_dir [ Writeable] document_root [ Writeable]

 

Command :


[ Back ]     

Current File : /home/bitrix/ext_www/rospirotorg.ru/bitrix/modules/grain.iiko/lib/rest.php
<?php

namespace Grain\Iiko;

use \Bitrix\Main\Localization\Loc;	
use \Bitrix\Main\Loader;
use \Bitrix\Main\Application;
use \Bitrix\Main\Config\Option;
use \Bitrix\Main\Web\Uri;
use \Grain\Iiko\Restaurants;
use \Grain\Iiko\Rest\v0;
use \Grain\Iiko\Rest\v1;
use \Grain\Iiko\Rest\Compatibility;

Loc::loadMessages(__FILE__);

class Rest
{
	const moduleName = 'grain.iiko';

	public static function getOrganizations()
	{
		$results = array();
		if(Loader::includeModule('grain.iikomulti'))
		{
			$accounts = \Grain\IikoMulti\Auth::getAll();
		}
		else
		{
			$accounts = array();
			if($account=static::getAccount())
				$accounts[0] = $account;
		}

		foreach($accounts as $account)
		{
			if($account['API_VERSION']==0) 
			{
				$result = static::query('/organization/list',false,'GET',$account);
				if(is_array($result['result']))
				{
					$tmpResult = $result['result'];
					$result['result'] = array();
					foreach($tmpResult as $organization)
					{
						$result['result'][] = array(
							'id' => $organization['id'],
							'name' => $organization['name'],
							'latitude' => !!$organization['latitude']?$organization['latitude']:'',
							'longitude' => !!$organization['longitude']?$organization['longitude']:'',
							'address' => $organization['address'],
						);
					}
				}
				$results[$account['ID']] = $result;
			}			
			elseif($account['API_VERSION']==1) 
			{
				$result = static::query('/organizations',array('returnAdditionalInfo'=>true),'POST',$account);
				if(is_array($result['result']))
				{
					$tmpResult = $result['result'];
					$result['result'] = array();
					if(is_array($tmpResult['organizations'])) foreach($tmpResult['organizations'] as $organization)
					{
						$result['result'][] = array(
							'id' => $organization['id'],
							'name' => $organization['name'],
							'latitude' => !!$organization['latitude']?$organization['latitude']:'',
							'longitude' => !!$organization['longitude']?$organization['longitude']:'',
							'address' => $organization['restaurantAddress'],
						);
					}
				}
				$results[$account['ID']] = $result;
			}			
		}
		return $results;
	}

	public static function getDishes($restaurantId)
	{
		if(!is_array($account=static::getAccount($restaurantId)) || !($restaurant=Restaurants::getRestaurantById($restaurantId)))
			return array('error'=>Loc::getMessage('GRAIN_IIKO_REST_NO_ACCOUNT_ERROR'));
		if($account['API_VERSION']==0)
		{
			return Compatibility\v0tov1::dishes(static::query('/nomenclature/'.$restaurant['XML_ID'],false,'GET',$account),$restaurant['XML_ID']);
		}
		elseif($account['API_VERSION']==1)
		{
			return static::query('/nomenclature',array('organizationId' => $restaurant['XML_ID']),'POST',$account);
		}
	}

	public static function getPaymentTypes($restaurantId)
	{
		if(!is_array($account=static::getAccount($restaurantId)) || !($restaurant=Restaurants::getRestaurantById($restaurantId)))
			return array('error'=>Loc::getMessage('GRAIN_IIKO_REST_NO_ACCOUNT_ERROR'));
		if($account['API_VERSION']==0)
		{
			return Compatibility\v0tov1::paymentTypes(static::query('/rmsSettings/getPaymentTypes',array('organization' => $restaurant['XML_ID']),'GET',$account),$restaurant['XML_ID']);
		}
		if($account['API_VERSION']==1)
		{
			return static::query('/payment_types',array('organizationIds' => array($restaurant['XML_ID'])),'POST',$account);
		}
	}

	public static function getDiscounts($restaurantId)
	{
		if(!is_array($account=static::getAccount($restaurantId)) || !($restaurant=Restaurants::getRestaurantById($restaurantId)))
			return array('error'=>Loc::getMessage('GRAIN_IIKO_REST_NO_ACCOUNT_ERROR'));
		if($account['API_VERSION']==0)
		{
			return Compatibility\v0tov1::discounts(static::query('/deliverySettings/deliveryDiscounts',array('organization' => $restaurant['XML_ID']),'GET',$account),$restaurant['XML_ID']);
		}
		if($account['API_VERSION']==1)
		{
			return static::query('/discounts',array('organizationIds' => array($restaurant['XML_ID'])),'POST',$account);
		}
	}

	public static function getCities($restaurantId)
	{
		if(!is_array($account=static::getAccount($restaurantId)) || !($restaurant=Restaurants::getRestaurantById($restaurantId)))
			return array('error'=>Loc::getMessage('GRAIN_IIKO_REST_NO_ACCOUNT_ERROR'));
		if($account['API_VERSION']==0)
		{
			return Compatibility\v0tov1::cities(static::query('/cities/cities',array('organization' => $restaurant['XML_ID']),'GET',$account),$restaurant['XML_ID']);
		}
		elseif($account['API_VERSION']==1)
		{
			$cities = static::query('/cities',array('organizationIds' => array($restaurant['XML_ID'])),'POST',$account);
			return $cities;
		}
	}

	public static function getStreets($restaurantId,$cityId)
	{
		if(!is_array($account=static::getAccount($restaurantId)) || !($restaurant=Restaurants::getRestaurantById($restaurantId)))
			return array('error'=>Loc::getMessage('GRAIN_IIKO_REST_NO_ACCOUNT_ERROR'));
		if($account['API_VERSION']==0)
		{
			return array('error'=>'Not implemented in this api version, use api 1');
		}
		elseif($account['API_VERSION']==1)
		{
			$streets = static::query('/streets/by_city',array(
				'organizationId' => $restaurant['XML_ID'],
				'cityId' => $cityId,
			),'POST',$account);
			return $streets;
		}
	}

	public static function getDeliveryTerminals($restaurantId)
	{
		if(!is_array($account=static::getAccount($restaurantId)) || !($restaurant=Restaurants::getRestaurantById($restaurantId)))
			return array('error'=>Loc::getMessage('GRAIN_IIKO_REST_NO_ACCOUNT_ERROR'));
		if($account['API_VERSION']==0)
		{
			return Compatibility\v0tov1::terminalGroups(static::query('/deliverySettings/getDeliveryTerminals',array('organization' => $restaurant['XML_ID']),'GET',$account),$restaurant['XML_ID']);
		}
		elseif($account['API_VERSION']==1)
		{
			return static::query('/terminal_groups',array('organizationIds' => array($restaurant['XML_ID']),'includeDisabled'=>false),'POST',$account);
		}
	}

	public static function getStopList($restaurantId)
	{
		if(!is_array($account=static::getAccount($restaurantId)) || !($restaurant=Restaurants::getRestaurantById($restaurantId)))
			return array('error'=>Loc::getMessage('GRAIN_IIKO_REST_NO_ACCOUNT_ERROR'));
		if($account['API_VERSION']==0)
		{
			return array('error'=>'Not implemented in this api version, use api 1');
		}
		elseif($account['API_VERSION']==1)
		{
			return static::query('/stop_lists',array('organizationIds' => array($restaurant['XML_ID'])),'POST',$account);
		}
	}
	
	public static function orderCreate($body,$restaurantId)
	{
		if(!is_array($account=static::getAccount($restaurantId)) || !($restaurant=Restaurants::getRestaurantById($restaurantId)))
			return array('error'=>Loc::getMessage('GRAIN_IIKO_REST_NO_ACCOUNT_ERROR'));
		if($account['API_VERSION']==0)
		{
			return static::query('/orders/add',$body,'POST',$account);
		}
		if($account['API_VERSION']==1)
		{
			$result = static::query('/deliveries/create',$body,'POST',$account);
			if($result['result']['orderInfo']['creationStatus']=='Error')
				$result['error'] = $result['result']['orderInfo']['errorInfo']['description']?$result['result']['orderInfo']['errorInfo']['description']:($result['result']['orderInfo']['errorInfo']['message']?$result['result']['orderInfo']['errorInfo']['message']:$result['result']['orderInfo']['errorInfo']['code']);
			return $result;
		}
	}

	public static function orderCheckCreate($body,$restaurantId)
	{
		if(!is_array($account=static::getAccount($restaurantId)) || !($restaurant=Restaurants::getRestaurantById($restaurantId)))
			return array('error'=>Loc::getMessage('GRAIN_IIKO_REST_NO_ACCOUNT_ERROR'));
		if($account['API_VERSION']==0)
		{
			return static::query('/orders/checkCreate',$body,'POST',$account);
		}
		if($account['API_VERSION']==1)
		{
			$result = static::query('/deliveries/check_create',$body,'POST',$account);
			if($result['result']['orderInfo']['creationStatus']=='Error')
				$result['error'] = $result['result']['orderInfo']['errorInfo']['description']?$result['result']['orderInfo']['errorInfo']['description']:($result['result']['orderInfo']['errorInfo']['message']?$result['result']['orderInfo']['errorInfo']['message']:$result['result']['orderInfo']['errorInfo']['code']);
			return $result;
		}
	}
	
	public static function getWalletBalancesByPhone($restaurantId,$phone,$registerWallet=false)
	{
		if(!is_array($account=static::getAccount($restaurantId)) || !($restaurant=Restaurants::getRestaurantById($restaurantId)))
			return array('error'=>Loc::getMessage('GRAIN_IIKO_REST_NO_ACCOUNT_ERROR'));
		if($account['API_VERSION']==0)
		{
			$result = Compatibility\v0tov1::walletBalances(static::query('/customers/get_customer_by_phone',array('organization' => $restaurant['XML_ID'], 'phone' => $phone),'GET',$account),$restaurant['XML_ID']);
			if(!is_array($result['result']['walletBalances']) || count($result['result']['walletBalances'])<=0)
				return array('error'=>'No wallet');
			$result['result'] = $result['result']['walletBalances'];
			return $result;
		}
		if($account['API_VERSION']==1)
		{
			$result = static::query('/loyalty/iiko/customer/info',array(
				'organizationId' => $restaurant['XML_ID'], 
				'phone' => $phone, 
				'type' => 'phone'
			),'POST',$account);
			if(!is_array($result['result']['walletBalances']) || count($result['result']['walletBalances'])<=0)
				return static::tryCreateWallet($restaurant,$account,$phone,$result,$registerWallet);
			$result['result'] = $result['result']['walletBalances'];
			return $result;
		}
	}
	
	public static function tryCreateWallet($restaurant,$account,$phone,$result,$registerWallet)
	{
		$allowCreateWallet = Option::get('grain.iikocard','allow_create_wallet_'.$restaurant['ID']);
		if(!$registerWallet || !in_array($allowCreateWallet,array('new_user','all')))
			return array('error'=>'No wallet');
		if(is_array($result['result']['walletBalances']) && $allowCreateWallet=='new_user')
			return array('error'=>'No wallet');
		if($account['API_VERSION']==0)
		{
			return array('error'=>'No wallet');
		}
		if($account['API_VERSION']==1)
		{
			list($programId,$walletId) = explode(':',strval(Option::get('grain.iikocard','create_wallet_program_'.$restaurant['ID'])));
			if(!$programId || !$walletId)
				return array('error'=>'No wallet');
			
			$customerId = null;
			if(isset($result['error']))
			{
				$customerAddResult = static::query('/loyalty/iiko/customer/create_or_update',array(
					'organizationId' => $restaurant['XML_ID'], 
					'phone' => $phone,
					'consentStatus' => 1,
				),'POST',$account);
				if(isset($customerAddResult['result']['id']))
					$customerId = $customerAddResult['result']['id'];
			}
			elseif(isset($result['result']['id']))
			{
				$customerId = $result['result']['id'];
			}
					
			if(!$customerId)
				return array('error'=>'No wallet');
			$cardAddResult = static::query('/loyalty/iiko/customer/card/add',array(
				'organizationId' => $restaurant['XML_ID'], 
				'customerId' => $customerId, 
				'cardTrack' => \RandString(10,'0123456789'), 
				'cardNumber' => \RandString(10,'0123456789'), 
			),'POST',$account);
			
			foreach(explode(',',strval(Option::get('grain.iikocard','new_wallet_customer_categories_'.$restaurant['ID']))) as $customerCategoryId)
			{
				$addCategoryForCustomer = static::query('/loyalty/iiko/customer_category/add',array(
					'organizationId' => $restaurant['XML_ID'], 
					'customerId' => $customerId, 
					'categoryId' => $customerCategoryId, 
				),'POST',$account);
			}
			
			$addToProgramResult = static::query('/loyalty/iiko/customer/program/add',array(
				'organizationId' => $restaurant['XML_ID'], 
				'customerId' => $customerId, 
				'programId' => $programId, 
			),'POST',$account);
	
			if(
				isset($addToProgramResult['result']['userWalletId']) 
				&& ($newWalletSum = floatval(Option::get('grain.iikocard','new_wallet_sum_'.$restaurant['ID'])))
			) {
				$bonusAddResult = static::query('/loyalty/iiko/customer/wallet/topup',array(
					'organizationId' => $restaurant['XML_ID'], 
					'customerId' => $customerId, 
					'walletId' => $walletId, // there is no need $addToProgramResult['result']['userWalletId'], but need program wallet id
					'sum' => $newWalletSum, 
					'comment' => 'Website new customer bonus', 
				),'POST',$account);	
			}
	
			$result = static::query('/loyalty/iiko/customer/info',array('organizationId' => $restaurant['XML_ID'], 'phone' => $phone, 'type' => 'phone'),'POST',$account);
			if(!is_array($result['result']['walletBalances']) || count($result['result']['walletBalances'])<=0)
				return array('error'=>'No wallet');
			$result['result'] = $result['result']['walletBalances'];
			return $result;
		}
	}

	public static function getPrograms($restaurantId)
	{
		if(!is_array($account=static::getAccount($restaurantId)) || !($restaurant=Restaurants::getRestaurantById($restaurantId)))
			return array('error'=>Loc::getMessage('GRAIN_IIKO_REST_NO_ACCOUNT_ERROR'));
		if($account['API_VERSION']==0)
		{
			return array('error'=>'Not implemented in this api version, use api 1');
		}
		if($account['API_VERSION']==1)
		{
			return static::query('/loyalty/iiko/program',array(
				'organizationId' => $restaurant['XML_ID'], 
			),'POST',$account);
		}
	}

	public static function getCustomerCategories($restaurantId)
	{
		if(!is_array($account=static::getAccount($restaurantId)) || !($restaurant=Restaurants::getRestaurantById($restaurantId)))
			return array('error'=>Loc::getMessage('GRAIN_IIKO_REST_NO_ACCOUNT_ERROR'));
		if($account['API_VERSION']==0)
		{
			return array('error'=>'Not implemented in this api version, use api 1');
		}
		if($account['API_VERSION']==1)
		{
			return static::query('/loyalty/iiko/customer_category',array(
				'organizationId' => $restaurant['XML_ID'], 
			),'POST',$account);
		}
	}
	
	public static function calculateLoyalty($body,$restaurantId)
	{
		if(!is_array($account=static::getAccount($restaurantId)) || !($restaurant=Restaurants::getRestaurantById($restaurantId)))
			return array('error'=>Loc::getMessage('GRAIN_IIKO_REST_NO_ACCOUNT_ERROR'));
		if($account['API_VERSION']==0)
		{
			return Compatibility\v0tov1::loyalty(static::query('/orders/calculate_checkin_result',$body,'POST',$account),$restaurant['XML_ID']);
		}
		if($account['API_VERSION']==1)
		{
			$result = static::query('/loyalty/iiko/calculate',$body,'POST',$account);
			if(is_array($result['result']['loyaltyProgramResults']))
			{
				foreach($result['result']['loyaltyProgramResults'] as &$loyaltyProgramResult)
				{
					if(is_array($loyaltyProgramResult['discounts']))
					{
						foreach($loyaltyProgramResult['discounts'] as &$discount)
						{
							if(array_key_exists('amount', $discount))
								unset($discount['amount']);
						}
						unset($discount);
					}
				}
				unset($loyaltyProgramResult);
			}
			$result['result']['apiVersion'] = 1;
			return $result;
		}
	}
	
	public static function getDeliveryRestrictionsAllowed($body,$restaurantId)
	{
		if(!is_array($account=static::getAccount($restaurantId)) || !($restaurant=Restaurants::getRestaurantById($restaurantId)))
			return array('error'=>Loc::getMessage('GRAIN_IIKO_REST_NO_ACCOUNT_ERROR'));
		if($account['API_VERSION']==0)
		{
			// not implemented in api 0
		}
		if($account['API_VERSION']==1)
		{
			return static::query('/delivery_restrictions/allowed',$body,'POST',$account);
		}
	}

	public static function getCommandStatus($correlationId,$restaurantId)
	{
		if(!is_array($account=static::getAccount($restaurantId)) || !($restaurant=Restaurants::getRestaurantById($restaurantId)))
			return array('error'=>Loc::getMessage('GRAIN_IIKO_REST_NO_ACCOUNT_ERROR'));
		if($account['API_VERSION']==0)
		{
			return array('error' => 'Not implemented in iikoDelivery');
		}
		if($account['API_VERSION']==1)
		{
			return static::query('/commands/status',array(
				'organizationId' => $restaurant['XML_ID'],
				'correlationId' => $correlationId,
			),'POST',$account);
		}
	}

	public static function getWebhook($restaurantId)
	{
		if(!is_array($account=static::getAccount($restaurantId)) || !($restaurant=Restaurants::getRestaurantById($restaurantId)))
			return array('error'=>Loc::getMessage('GRAIN_IIKO_REST_NO_ACCOUNT_ERROR'));
		if($account['API_VERSION']==0)
		{
			return array('error' => 'Not implemented in iikoDelivery');
		}
		if($account['API_VERSION']==1)
		{
			return static::query('/webhooks/settings',array(
				'organizationId' => $restaurant['XML_ID'],
			),'POST',$account);
		}
	}

	public static function setWebhook($body,$restaurantId)
	{
		if(!is_array($account=static::getAccount($restaurantId)) || !($restaurant=Restaurants::getRestaurantById($restaurantId)))
			return array('error'=>Loc::getMessage('GRAIN_IIKO_REST_NO_ACCOUNT_ERROR'));
		if($account['API_VERSION']==0)
		{
			return array('error' => 'Not implemented in iikoDelivery');
		}
		if($account['API_VERSION']==1)
		{
			if(!isset($body['organizationId']))
				$body['organizationId'] = $restaurant['XML_ID'];
			return static::query('/webhooks/update_settings',$body,'POST',$account);
		}
	}
	
	public static function getAccount($accountOrRestaurantId=false)
	{
		$account = null;
		if(is_array($accountOrRestaurantId))
		{
			$account = $accountOrRestaurantId;
		}
		elseif(Loader::includeModule('grain.iikomulti'))
		{
			$account = \Grain\IikoMulti\Auth::get($accountOrRestaurantId);
		}
		elseif(Option::get(static::moduleName,'api_login'))
		{
			$login = strval(Option::get(static::moduleName,'api_login'));
			$password = strval(Option::get(static::moduleName,'api_password'));
			list($apiVersion,$host,$port) = explode(':',strval(Option::get(static::moduleName,'api_server')));
			$account = array(
				'ID' => 0,
				'HOST' => $host,
				'PORT' => intval($port)>0?intval($port):443,
				'LOGIN' => $login,
				'PASSWORD' => $password,
				'API_VERSION' => intval($apiVersion),
			);
		}
		return $account;
	}

	public static function buildIikoOrderBody($params,$restaurantId)
	{
		if(!is_array($account=static::getAccount($restaurantId)))
			return array('error'=>Loc::getMessage('GRAIN_IIKO_REST_NO_ACCOUNT_ERROR'));
		if($account['API_VERSION']==0)
			return v0::buildIikoOrderBody($params,$restaurantId);
		elseif($account['API_VERSION']==1)
			return v1::buildIikoOrderBody($params,$restaurantId);
	}
	
	public static function query($path,$body,$method='POST',$accountOrRestaurantId=false)
	{
		$account = static::getAccount($accountOrRestaurantId);
		if(!is_array($account))
			return array('error'=>Loc::getMessage('GRAIN_IIKO_REST_NO_ACCOUNT_ERROR'));
		if($account['API_VERSION']==0)
			$result = v0::query($path,$body,$method,$account);
		elseif($account['API_VERSION']==1)
			$result = v1::query($path,$body,$method,$account);
		else
			$result = array(
				'error' => 'Cannot find provider',
			);
		if(array_key_exists('error', $result))
			$result['error'] = str_replace(array($account['LOGIN'],$account['PASSWORD']),"***",$result['error']);
		$account['LOGIN'] = '***';
		$account['PASSWORD'] = is_string($account['PASSWORD']) && strlen($account['PASSWORD'])?'***':'';
		$result['account'] = $account;
		return $result;
	}
	
	public static function generateOrderUuid($restaurant,$order)
	{
		$uuid = \Bitrix\Main\Security\Random::getStringByCharsets(8,'0123456789abcdef').'-0000-0000-0000-'.str_pad(strval($order->getId()),12,'0',STR_PAD_LEFT);

		$event = new \Bitrix\Main\Event("grain.iiko", "OnGenerateOrderUuid", array(
			'RESTAURANT' => $restaurant,
			'ORDER' => $order,
			'UUID' => $uuid,
		));
		$event->send();
		foreach ($event->getResults() as $eventResult)
		{
			if($eventResult->getType() == \Bitrix\Main\EventResult::ERROR)
				continue;
			if($eventResult->getParameters())
				$uuid = $eventResult->getParameters();
		}
		return $uuid;
	}
	
	public static function generateUuid($data = null) 
	{
		$dataInitial = $data;
		$data = md5(strval($data),true) ?? random_bytes(16);
		$data[6] = chr(ord($data[6]) & 0x0f | 0x40);
		$data[8] = chr(ord($data[8]) & 0x3f | 0x80);
		$uuid = vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));

		$event = new \Bitrix\Main\Event("grain.iiko", "OnGenerateUuid", array(
			'DATA' => $data,
			'DATA_INITIAL' => $dataInitial,
			'UUID' => $uuid,
		));
		$event->send();
		foreach ($event->getResults() as $eventResult)
		{
			if($eventResult->getType() == \Bitrix\Main\EventResult::ERROR)
				continue;
			if($eventResult->getParameters())
				$uuid = $eventResult->getParameters();
		}
		return $uuid;
	}	
	
	public static function checkAccess($account)
	{
		if($account['API_VERSION']==0)
			return v0::checkAccess($account);
		elseif($account['API_VERSION']==1)
			return v1::checkAccess($account);
	}
	
	public static function getServerList()
	{
		$serverList = array(
			'1:api-ru.iiko.services:443' => 'iikoTransport - api-ru.iiko.services:443',
			'1:api-eu.iiko.services:443' => 'iikoTransport - api-eu.iiko.services:443',
			'0:iiko.biz:9900' => 'iikoDelivery - iiko.biz:9900',
			'0:card.iiko.co.uk:9900' => 'iikoDelivery - card.iiko.co.uk:9900',
			'0:loyalty.syrve.live:443' => 'iikoDelivery - loyalty.syrve.live:443',
		);
		$event = new \Bitrix\Main\Event("grain.iiko", "OnGetServerList", array(
			'SERVER_LIST' => $serverList,
		));
		$event->send();
		foreach ($event->getResults() as $eventResult)
		{
			if($eventResult->getType() == \Bitrix\Main\EventResult::ERROR)
				continue;
			if($eventResult->getParameters())
				$serverList = $eventResult->getParameters();
		}
		return $serverList;
	}
	
}

Youez - 2016 - github.com/yon3zu
LinuXploit