├── .idea ├── crest.iml ├── misc.xml ├── modules.xml └── vcs.xml ├── LICENSE ├── README.md └── src ├── checkserver.php ├── crest.php ├── index.php ├── install.php └── settings.php /.idea/crest.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 6 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Bitrix 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # @bitrix/crest 2 | [English](#contenten) | [Русский](#contentru) 3 | 4 | 5 |
6 | @bitrix/crest — small PHPSDK used for Bitrix24 REST API for webhooks, local or public applications. 7 | 8 | # Contents 9 | 1. [Description](#description) 10 | 2. [Calling using inbound webhook](#usingwebhook) 11 | 3. [Calling from local application](#localapp) 12 | 4. [Calling from public application](#publicapp) 13 | 14 | 15 | ##
Description 16 | 17 | 25 | 26 | ```php 27 | define('C_REST_CURRENT_ENCODING','windows-1251'); 28 | ``` 29 | 30 | ##
Calling REST using inbound webhook 31 | 32 | Indicate webhook URL in define C_REST_WEB_HOOK_URL inside the settings.php file: 33 | 34 | ```php 35 | define('C_REST_WEB_HOOK_URL','https://xxx.bitrix24.ru/rest/1/douasdqdsxSWgc3mgc1/'); 36 | ``` 37 | 38 | Insert example text into the index.php file: 39 | 40 | ```php 41 | require_once('src/crest.php'); 42 | 43 | // put an example below 44 | echo '
';
 45 | print_r(CRest::call(
 46 |    'crm.lead.add',
 47 |    [
 48 |       'fields' =>[
 49 |           'TITLE' => 'Lead name',//Title*[string]
 50 |           'NAME' => 'Name',//Name[string]
 51 |           'LAST_NAME' => 'Last name',//Last name[string]
 52 |       ]
 53 |    ])
 54 | );
 55 | 
 56 | echo '
'; 57 | ``` 58 | 59 | Indicate example URL in the browser address bar https://example.com/index.php to see the example results. 60 | 61 | 62 | ##
Calling REST from local application 63 | 64 | Insert example text into the index.php file: 65 | 66 | ```php 67 | require_once('src/crest.php'); 68 | 69 | // put an example below 70 | echo '
';
 71 | print_r(CRest::call(
 72 |    'crm.lead.add',
 73 |    [
 74 |       'fields' =>[
 75 |           'TITLE' => 'Lead name',//Title*[string]
 76 |           'NAME' => 'Name',//Name[string]
 77 |           'LAST_NAME' => 'Last name',//Last name[string]
 78 |       ]
 79 |    ])
 80 | );
 81 | 
 82 | echo '
'; 83 | ``` 84 | 85 | Indicate your app URL https://example.com/index.php as well as installation script URL https://example.com/install.php inside the local app details form. 86 | Indicate parameters client_id and client_secret for OAuth 2.0 authorization in define C_REST_CLIENT_ID and C_REST_CLIENT_SECRET inside the settings.php file. 87 | Take these values from the local app details form. 88 |
89 | In the list of local applications, click on your local app and select “Reinstall”. It’s required for install.php to operate correctly after you have indicated correct values C_REST_CLIENT_ID and C_REST_CLIENT_SECRET. 90 | After installation is complete, you will see example results. When the example demonstrates widget embedding into other Bitrix24 tools, switch to these tools. 91 | 92 | ##
Calling REST from public application 93 | 94 | Insert example text into the index.php file: 95 | 96 | ```php 97 | require_once('src/crest.php'); 98 | 99 | // put an example below 100 | echo '
';
101 | print_r(CRest::call(
102 |    'crm.lead.add',
103 |    [
104 |       'fields' =>[
105 |           'TITLE' => 'Lead name',//Title*[string]
106 |           'NAME' => 'Name',//Name[string]
107 |           'LAST_NAME' => 'Last name',//Last name[string]
108 |       ]
109 |    ])
110 | );
111 | 
112 | echo '
'; 113 | ``` 114 | 115 | Add a public application inside the partner’s account to get client_id and client_secret as well as when saving an application. Indicate parameters client_id and client_secret OAuth 2.0 authorization in define C_REST_CLIENT_ID and C_REST_CLIENT_SECRET in the settings.php file. 116 | Select and indicate your application URL https://example.com/index.php and installation script URL https://example.com/install.php inside the app details form. After saving the version, open the version details and install your app to any available Bitrix24 by clicking on "Install". After installation is complete, you will see example results (when the example demonstrates widget embedding into other Bitrix24 tools, switch to these tools). For actual public app operation, you must inherit CRest class by redefining methods getSettingData/setSettingData that get/save authentication tokens in text file. These methods are not designed for application working on several Bitrix24 simultaneously. 117 |

118 |
119 |
120 |
121 | 122 |
123 | @bitrix/crest — небольшой PHPSDK для использования REST API Битрикс24 в локальных, 124 | тиражных приложениях или через вебхуки 125 | 126 | # Содержание 127 | 1. [Описание](#introduction) 128 | 2. [Вызов при помощи входящего вебхука](#webhook) 129 | 3. [Вызов из локального приложения](#local) 130 | 4. [Вызов из тиражного приложения](#public) 131 | 132 | 133 | ##
Описание 134 | 135 | 143 | 144 | ```php 145 | define('C_REST_CURRENT_ENCODING','windows-1251'); 146 | ``` 147 | 148 | ##
Вызов REST с использованием входящего вебхука 149 | 150 | Укажите URL вебхука в define C_REST_WEB_HOOK_URL в файле settings.php: 151 | 152 | ```php 153 | define('C_REST_WEB_HOOK_URL','https://xxx.bitrix24.ru/rest/1/douasdqdsxSWgc3mgc1/'); 154 | ``` 155 | 156 | Вставьте текст примера в файл index.php: 157 | 158 | ```php 159 | require_once('src/crest.php'); 160 | 161 | // put an example below 162 | echo '
';
163 | print_r(CRest::call(
164 |    'crm.lead.add',
165 |    [
166 |       'fields' =>[
167 |           'TITLE' => 'Название лида',//Заголовок*[string]
168 |           'NAME' => 'Имя',//Имя[string]
169 |           'LAST_NAME' => 'Фамилия',//Фамилия[string]
170 |       ]
171 |    ])
172 | );
173 | 
174 | echo '
'; 175 | ``` 176 | 177 | Укажите URL к примеру в адресной строке браузера https://example.com/index.php, чтобы увидеть результат работы примера. 178 | 179 | 180 | ##
Вызов REST из локального приложения 181 | 182 | Вставьте текст примера в файл index.php: 183 | 184 | ```php 185 | require_once('src/crest.php'); 186 | 187 | // put an example below 188 | echo '
';
189 | print_r(CRest::call(
190 |    'crm.lead.add',
191 |    [
192 |       'fields' =>[
193 |           'TITLE' => 'Название лида',//Заголовок*[string]
194 |           'NAME' => 'Имя',//Имя[string]
195 |           'LAST_NAME' => 'Фамилия',//Фамилия[string]
196 |       ]
197 |    ])
198 | );
199 | 
200 | echo '
'; 201 | ``` 202 | 203 | В карточке локального приложения укажите URL своего приложения https://example.com/index.php и URL скрипта установки https://example.com/install.php. 204 | Укажите значения параметров client_id и client_secret для авторизации OAuth 2.0 в define C_REST_CLIENT_ID и C_REST_CLIENT_SECRET в файле settings.php, взяв эти значения из карточки локального приложения. 205 |
206 | В списке локальных приложений нажмите правой кнопкой мыши на своё локальное приложение и выберите пункт "Переустановить". Это нужно чтобы корректно сработал install.php после того, как вы вставили корректные значения C_REST_CLIENT_ID и C_REST_CLIENT_SECRET. 207 | После установки вы увидите результат работы примера. Если пример демонстрирует встраивание виджетов в другие инструменты Битрикс24, необходимо перейти в эти инструменты. 208 | 209 | 210 | ##
Вызов REST из тиражного приложения 211 | 212 | Вставьте текст примера в файл index.php 213 | 214 | ```php 215 | require_once('src/crest.php'); 216 | 217 | // put an example below 218 | echo '
';
219 | print_r(CRest::call(
220 |    'crm.lead.add',
221 |    [
222 |       'fields' =>[
223 |           'TITLE' => 'Название лида',//Заголовок*[string]
224 |           'NAME' => 'Имя',//Имя[string]
225 |           'LAST_NAME' => 'Фамилия',//Фамилия[string]
226 |       ]
227 |    ])
228 | );
229 | 
230 | echo '
'; 231 | ``` 232 | 233 | Добавьте тиражное приложение в партнерском кабинете для получения client_id и client_secret и при сохранении приложения. 234 | Укажите значения параметров client_id и client_secret для авторизации OAuth 2.0 в define C_REST_CLIENT_ID и C_REST_CLIENT_SECRET в файле settings.php. 235 | 236 |
237 | 238 | В карточке приложения добавьте версию и укажите URL своего приложения https://example.com/index.php и URL скрипта установки https://example.com/install.php в карточке версии. 239 | После сохранения версии откройте карточку версии и, нажав на ссылку "Установить на своем Битрикс24", установите свое приложение на любой доступный вам Битрикс24. 240 | После установки вы увидите результат работы примера (в случае, если пример демонстрирует встраивание виджетов в другие инструменты Битрикс24, необходимо перейти в эти инструменты). 241 | Для реального тиражного приложения необходимо пронаследовать класс CRest, переопределив методы getSettingData/setSettingData, которые занимается получением/сохранением токенов авторизации в текстовый файл. Эти методы не предназначены для эксплуатации приложения на нескольких Битрикс24 одновременно. 242 | -------------------------------------------------------------------------------- /src/checkserver.php: -------------------------------------------------------------------------------- 1 | true, 34 | 'install' => false 35 | ]; 36 | if($_REQUEST[ 'event' ] == 'ONAPPINSTALL' && !empty($_REQUEST[ 'auth' ])) 37 | { 38 | $result['install'] = static::setAppSettings($_REQUEST[ 'auth' ], true); 39 | } 40 | elseif($_REQUEST['PLACEMENT'] == 'DEFAULT') 41 | { 42 | $result['rest_only'] = false; 43 | $result['install'] = static::setAppSettings( 44 | [ 45 | 'access_token' => htmlspecialchars($_REQUEST['AUTH_ID']), 46 | 'expires_in' => htmlspecialchars($_REQUEST['AUTH_EXPIRES']), 47 | 'application_token' => htmlspecialchars($_REQUEST['APP_SID']), 48 | 'refresh_token' => htmlspecialchars($_REQUEST['REFRESH_ID']), 49 | 'domain' => htmlspecialchars($_REQUEST['DOMAIN']), 50 | 'client_endpoint' => 'https://' . htmlspecialchars($_REQUEST['DOMAIN']) . '/rest/', 51 | ], 52 | true 53 | ); 54 | } 55 | 56 | static::setLog( 57 | [ 58 | 'request' => $_REQUEST, 59 | 'result' => $result 60 | ], 61 | 'installApp' 62 | ); 63 | return $result; 64 | } 65 | 66 | /** 67 | * @var $arParams array 68 | * $arParams = [ 69 | * 'method' => 'some rest method', 70 | * 'params' => []//array params of method 71 | * ]; 72 | * @return mixed array|string|boolean curl-return or error 73 | * 74 | */ 75 | protected static function callCurl($arParams) 76 | { 77 | if(!function_exists('curl_init')) 78 | { 79 | return [ 80 | 'error' => 'error_php_lib_curl', 81 | 'error_information' => 'need install curl lib' 82 | ]; 83 | } 84 | $arSettings = static::getAppSettings(); 85 | if($arSettings !== false) 86 | { 87 | if(isset($arParams[ 'this_auth' ]) && $arParams[ 'this_auth' ] == 'Y') 88 | { 89 | $url = 'https://oauth.bitrix.info/oauth/token/'; 90 | } 91 | else 92 | { 93 | $url = $arSettings[ "client_endpoint" ] . $arParams[ 'method' ] . '.' . static::TYPE_TRANSPORT; 94 | if(empty($arSettings[ 'is_web_hook' ]) || $arSettings[ 'is_web_hook' ] != 'Y') 95 | { 96 | $arParams[ 'params' ][ 'auth' ] = $arSettings[ 'access_token' ]; 97 | } 98 | } 99 | 100 | $sPostFields = http_build_query($arParams[ 'params' ]); 101 | 102 | try 103 | { 104 | $obCurl = curl_init(); 105 | curl_setopt($obCurl, CURLOPT_URL, $url); 106 | curl_setopt($obCurl, CURLOPT_RETURNTRANSFER, true); 107 | curl_setopt($obCurl, CURLOPT_POSTREDIR, 10); 108 | curl_setopt($obCurl, CURLOPT_USERAGENT, 'Bitrix24 CRest PHP ' . static::VERSION); 109 | if($sPostFields) 110 | { 111 | curl_setopt($obCurl, CURLOPT_POST, true); 112 | curl_setopt($obCurl, CURLOPT_POSTFIELDS, $sPostFields); 113 | } 114 | curl_setopt( 115 | $obCurl, CURLOPT_FOLLOWLOCATION, (isset($arParams[ 'followlocation' ])) 116 | ? $arParams[ 'followlocation' ] : 1 117 | ); 118 | if(defined("C_REST_IGNORE_SSL") && C_REST_IGNORE_SSL === true) 119 | { 120 | curl_setopt($obCurl, CURLOPT_SSL_VERIFYPEER, false); 121 | curl_setopt($obCurl, CURLOPT_SSL_VERIFYHOST, false); 122 | } 123 | $out = curl_exec($obCurl); 124 | $info = curl_getinfo($obCurl); 125 | if(curl_errno($obCurl)) 126 | { 127 | $info[ 'curl_error' ] = curl_error($obCurl); 128 | } 129 | if(static::TYPE_TRANSPORT == 'xml' && (!isset($arParams[ 'this_auth' ]) || $arParams[ 'this_auth' ] != 'Y'))//auth only json support 130 | { 131 | $result = $out; 132 | } 133 | else 134 | { 135 | $result = static::expandData($out); 136 | } 137 | curl_close($obCurl); 138 | 139 | if(!empty($result[ 'error' ])) 140 | { 141 | if($result[ 'error' ] == 'expired_token' && empty($arParams[ 'this_auth' ])) 142 | { 143 | $result = static::GetNewAuth($arParams); 144 | } 145 | else 146 | { 147 | $arErrorInform = [ 148 | 'expired_token' => 'expired token, cant get new auth? Check access oauth server.', 149 | 'invalid_token' => 'invalid token, need reinstall application', 150 | 'invalid_grant' => 'invalid grant, check out define C_REST_CLIENT_SECRET or C_REST_CLIENT_ID', 151 | 'invalid_client' => 'invalid client, check out define C_REST_CLIENT_SECRET or C_REST_CLIENT_ID', 152 | 'QUERY_LIMIT_EXCEEDED' => 'Too many requests, maximum 2 query by second', 153 | 'ERROR_METHOD_NOT_FOUND' => 'Method not found! You can see the permissions of the application: CRest::call(\'scope\')', 154 | 'NO_AUTH_FOUND' => 'Some setup error b24, check in table "b_module_to_module" event "OnRestCheckAuth"', 155 | 'INTERNAL_SERVER_ERROR' => 'Server down, try later' 156 | ]; 157 | if(!empty($arErrorInform[ $result[ 'error' ] ])) 158 | { 159 | $result[ 'error_information' ] = $arErrorInform[ $result[ 'error' ] ]; 160 | } 161 | } 162 | } 163 | if(!empty($info[ 'curl_error' ])) 164 | { 165 | $result[ 'error' ] = 'curl_error'; 166 | $result[ 'error_information' ] = $info[ 'curl_error' ]; 167 | } 168 | 169 | static::setLog( 170 | [ 171 | 'url' => $url, 172 | 'info' => $info, 173 | 'params' => $arParams, 174 | 'result' => $result 175 | ], 176 | 'callCurl' 177 | ); 178 | 179 | return $result; 180 | } 181 | catch(Exception $e) 182 | { 183 | static::setLog( 184 | [ 185 | 'message' => $e->getMessage(), 186 | 'code' => $e->getCode(), 187 | 'trace' => $e->getTrace(), 188 | 'params' => $arParams 189 | ], 190 | 'exceptionCurl' 191 | ); 192 | 193 | return [ 194 | 'error' => 'exception', 195 | 'error_exception_code' => $e->getCode(), 196 | 'error_information' => $e->getMessage(), 197 | ]; 198 | } 199 | } 200 | else 201 | { 202 | static::setLog( 203 | [ 204 | 'params' => $arParams 205 | ], 206 | 'emptySetting' 207 | ); 208 | } 209 | 210 | return [ 211 | 'error' => 'no_install_app', 212 | 'error_information' => 'error install app, pls install local application ' 213 | ]; 214 | } 215 | 216 | /** 217 | * Generate a request for callCurl() 218 | * 219 | * @var $method string 220 | * @var $params array method params 221 | * @return mixed array|string|boolean curl-return or error 222 | */ 223 | 224 | public static function call($method, $params = []) 225 | { 226 | $arPost = [ 227 | 'method' => $method, 228 | 'params' => $params 229 | ]; 230 | if(defined('C_REST_CURRENT_ENCODING')) 231 | { 232 | $arPost[ 'params' ] = static::changeEncoding($arPost[ 'params' ]); 233 | } 234 | 235 | $result = static::callCurl($arPost); 236 | return $result; 237 | } 238 | 239 | /** 240 | * @example $arData: 241 | * $arData = [ 242 | * 'find_contact' => [ 243 | * 'method' => 'crm.duplicate.findbycomm', 244 | * 'params' => [ "entity_type" => "CONTACT", "type" => "EMAIL", "values" => array("info@bitrix24.com") ] 245 | * ], 246 | * 'get_contact' => [ 247 | * 'method' => 'crm.contact.get', 248 | * 'params' => [ "id" => '$result[find_contact][CONTACT][0]' ] 249 | * ], 250 | * 'get_company' => [ 251 | * 'method' => 'crm.company.get', 252 | * 'params' => [ "id" => '$result[get_contact][COMPANY_ID]', "select" => ["*"],] 253 | * ] 254 | * ]; 255 | * 256 | * @var $arData array 257 | * @var $halt integer 0 or 1 stop batch on error 258 | * @return array 259 | * 260 | */ 261 | 262 | public static function callBatch($arData, $halt = 0) 263 | { 264 | $arResult = []; 265 | if(is_array($arData)) 266 | { 267 | if(defined('C_REST_CURRENT_ENCODING')) 268 | { 269 | $arData = static::changeEncoding($arData); 270 | } 271 | $arDataRest = []; 272 | $i = 0; 273 | foreach($arData as $key => $data) 274 | { 275 | if(!empty($data[ 'method' ])) 276 | { 277 | $i++; 278 | if(static::BATCH_COUNT >= $i) 279 | { 280 | $arDataRest[ 'cmd' ][ $key ] = $data[ 'method' ]; 281 | if(!empty($data[ 'params' ])) 282 | { 283 | $arDataRest[ 'cmd' ][ $key ] .= '?' . http_build_query($data[ 'params' ]); 284 | } 285 | } 286 | } 287 | } 288 | if(!empty($arDataRest)) 289 | { 290 | $arDataRest[ 'halt' ] = $halt; 291 | $arPost = [ 292 | 'method' => 'batch', 293 | 'params' => $arDataRest 294 | ]; 295 | $arResult = static::callCurl($arPost); 296 | } 297 | } 298 | return $arResult; 299 | } 300 | 301 | /** 302 | * Getting a new authorization and sending a request for the 2nd time 303 | * 304 | * @var $arParams array request when authorization error returned 305 | * @return array query result from $arParams 306 | * 307 | */ 308 | 309 | private static function GetNewAuth($arParams) 310 | { 311 | $result = []; 312 | $arSettings = static::getAppSettings(); 313 | if($arSettings !== false) 314 | { 315 | $arParamsAuth = [ 316 | 'this_auth' => 'Y', 317 | 'params' => 318 | [ 319 | 'client_id' => $arSettings[ 'C_REST_CLIENT_ID' ], 320 | 'grant_type' => 'refresh_token', 321 | 'client_secret' => $arSettings[ 'C_REST_CLIENT_SECRET' ], 322 | 'refresh_token' => $arSettings[ "refresh_token" ], 323 | ] 324 | ]; 325 | $newData = static::callCurl($arParamsAuth); 326 | if(isset($newData[ 'C_REST_CLIENT_ID' ])) 327 | { 328 | unset($newData[ 'C_REST_CLIENT_ID' ]); 329 | } 330 | if(isset($newData[ 'C_REST_CLIENT_SECRET' ])) 331 | { 332 | unset($newData[ 'C_REST_CLIENT_SECRET' ]); 333 | } 334 | if(isset($newData[ 'error' ])) 335 | { 336 | unset($newData[ 'error' ]); 337 | } 338 | if(static::setAppSettings($newData)) 339 | { 340 | $arParams[ 'this_auth' ] = 'N'; 341 | $result = static::callCurl($arParams); 342 | } 343 | } 344 | return $result; 345 | } 346 | 347 | /** 348 | * @var $arSettings array settings application 349 | * @var $isInstall boolean true if install app by installApp() 350 | * @return boolean 351 | */ 352 | 353 | private static function setAppSettings($arSettings, $isInstall = false) 354 | { 355 | $return = false; 356 | if(is_array($arSettings)) 357 | { 358 | $oldData = static::getAppSettings(); 359 | if($isInstall != true && !empty($oldData) && is_array($oldData)) 360 | { 361 | $arSettings = array_merge($oldData, $arSettings); 362 | } 363 | $return = static::setSettingData($arSettings); 364 | } 365 | return $return; 366 | } 367 | 368 | /** 369 | * @return mixed setting application for query 370 | */ 371 | 372 | private static function getAppSettings() 373 | { 374 | if(defined("C_REST_WEB_HOOK_URL") && !empty(C_REST_WEB_HOOK_URL)) 375 | { 376 | $arData = [ 377 | 'client_endpoint' => C_REST_WEB_HOOK_URL, 378 | 'is_web_hook' => 'Y' 379 | ]; 380 | $isCurrData = true; 381 | } 382 | else 383 | { 384 | $arData = static::getSettingData(); 385 | $isCurrData = false; 386 | if( 387 | !empty($arData[ 'access_token' ]) && 388 | !empty($arData[ 'domain' ]) && 389 | !empty($arData[ 'refresh_token' ]) && 390 | !empty($arData[ 'application_token' ]) && 391 | !empty($arData[ 'client_endpoint' ]) 392 | ) 393 | { 394 | $isCurrData = true; 395 | } 396 | } 397 | 398 | return ($isCurrData) ? $arData : false; 399 | } 400 | 401 | /** 402 | * Can overridden this method to change the data storage location. 403 | * 404 | * @return array setting for getAppSettings() 405 | */ 406 | 407 | protected static function getSettingData() 408 | { 409 | $return = []; 410 | if(file_exists(__DIR__ . '/settings.json')) 411 | { 412 | $return = static::expandData(file_get_contents(__DIR__ . '/settings.json')); 413 | if(defined("C_REST_CLIENT_ID") && !empty(C_REST_CLIENT_ID)) 414 | { 415 | $return['C_REST_CLIENT_ID'] = C_REST_CLIENT_ID; 416 | } 417 | if(defined("C_REST_CLIENT_SECRET") && !empty(C_REST_CLIENT_SECRET)) 418 | { 419 | $return['C_REST_CLIENT_SECRET'] = C_REST_CLIENT_SECRET; 420 | } 421 | } 422 | return $return; 423 | } 424 | 425 | /** 426 | * @var $data mixed 427 | * @var $encoding boolean true - encoding to utf8, false - decoding 428 | * 429 | * @return string json_encode with encoding 430 | */ 431 | protected static function changeEncoding($data, $encoding = true) 432 | { 433 | if(is_array($data)) 434 | { 435 | $result = []; 436 | foreach ($data as $k => $item) 437 | { 438 | $k = static::changeEncoding($k, $encoding); 439 | $result[$k] = static::changeEncoding($item, $encoding); 440 | } 441 | } 442 | else 443 | { 444 | if($encoding) 445 | { 446 | $result = iconv(C_REST_CURRENT_ENCODING, "UTF-8//TRANSLIT", $data); 447 | } 448 | else 449 | { 450 | $result = iconv( "UTF-8",C_REST_CURRENT_ENCODING, $data); 451 | } 452 | } 453 | 454 | return $result; 455 | } 456 | 457 | /** 458 | * @var $data mixed 459 | * @var $debag boolean 460 | * 461 | * @return string json_encode with encoding 462 | */ 463 | protected static function wrapData($data, $debag = false) 464 | { 465 | if(defined('C_REST_CURRENT_ENCODING')) 466 | { 467 | $data = static::changeEncoding($data, true); 468 | } 469 | $return = json_encode($data, JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_APOS|JSON_HEX_QUOT); 470 | 471 | if($debag) 472 | { 473 | $e = json_last_error(); 474 | if ($e != JSON_ERROR_NONE) 475 | { 476 | if ($e == JSON_ERROR_UTF8) 477 | { 478 | return 'Failed encoding! Recommended \'UTF - 8\' or set define C_REST_CURRENT_ENCODING = current site encoding for function iconv()'; 479 | } 480 | } 481 | } 482 | 483 | return $return; 484 | } 485 | 486 | /** 487 | * @var $data mixed 488 | * @var $debag boolean 489 | * 490 | * @return string json_decode with encoding 491 | */ 492 | protected static function expandData($data) 493 | { 494 | $return = json_decode($data, true); 495 | if(defined('C_REST_CURRENT_ENCODING')) 496 | { 497 | $return = static::changeEncoding($return, false); 498 | } 499 | return $return; 500 | } 501 | 502 | /** 503 | * Can overridden this method to change the data storage location. 504 | * 505 | * @var $arSettings array settings application 506 | * @return boolean is successes save data for setSettingData() 507 | */ 508 | 509 | protected static function setSettingData($arSettings) 510 | { 511 | return (boolean)file_put_contents(__DIR__ . '/settings.json', static::wrapData($arSettings)); 512 | } 513 | 514 | /** 515 | * Can overridden this method to change the log data storage location. 516 | * 517 | * @var $arData array of logs data 518 | * @var $type string to more identification log data 519 | * @return boolean is successes save log data 520 | */ 521 | 522 | public static function setLog($arData, $type = '') 523 | { 524 | $return = false; 525 | if(!defined("C_REST_BLOCK_LOG") || C_REST_BLOCK_LOG !== true) 526 | { 527 | if(defined("C_REST_LOGS_DIR")) 528 | { 529 | $path = C_REST_LOGS_DIR; 530 | } 531 | else 532 | { 533 | $path = __DIR__ . '/logs/'; 534 | } 535 | $path .= date("Y-m-d/H") . '/'; 536 | 537 | if (!file_exists($path)) 538 | { 539 | @mkdir($path, 0775, true); 540 | } 541 | 542 | $path .= time() . '_' . $type . '_' . rand(1, 9999999) . 'log'; 543 | if(!defined("C_REST_LOG_TYPE_DUMP") || C_REST_LOG_TYPE_DUMP !== true) 544 | { 545 | $jsonLog = static::wrapData($arData); 546 | if ($jsonLog === false) 547 | { 548 | $return = file_put_contents($path . '_backup.txt', var_export($arData, true)); 549 | } 550 | else 551 | { 552 | $return = file_put_contents($path . '.json', $jsonLog); 553 | } 554 | } 555 | else 556 | { 557 | $return = file_put_contents($path . '.txt', var_export($arData, true)); 558 | } 559 | } 560 | return $return; 561 | } 562 | 563 | /** 564 | * check minimal settings server to work CRest 565 | * @var $print boolean 566 | * @return array of errors 567 | */ 568 | public static function checkServer($print = true) 569 | { 570 | $return = []; 571 | 572 | //check curl lib install 573 | if(!function_exists('curl_init')) 574 | { 575 | $return['curl_error'] = 'Need install curl lib.'; 576 | } 577 | 578 | //creat setting file 579 | file_put_contents(__DIR__ . '/settings_check.json', static::wrapData(['test'=>'data'])); 580 | if(!file_exists(__DIR__ . '/settings_check.json')) 581 | { 582 | $return['setting_creat_error'] = 'Check permission! Recommended: folders: 775, files: 664'; 583 | } 584 | unlink(__DIR__ . '/settings_check.json'); 585 | //creat logs folder and files 586 | $path = __DIR__ . '/logs/'.date("Y-m-d/H") . '/'; 587 | if(!mkdir($path, 0775, true) && !file_exists($path)) 588 | { 589 | $return['logs_folder_creat_error'] = 'Check permission! Recommended: folders: 775, files: 664'; 590 | } 591 | else 592 | { 593 | file_put_contents($path . 'test.txt', var_export(['test'=>'data'], true)); 594 | if(!file_exists($path . 'test.txt')) 595 | { 596 | $return['logs_file_creat_error'] = 'check permission! recommended: folders: 775, files: 664'; 597 | } 598 | unlink($path . 'test.txt'); 599 | } 600 | 601 | if($print === true) 602 | { 603 | if(empty($return)) 604 | { 605 | $return['success'] = 'Success!'; 606 | } 607 | echo '
';
608 | 				print_r($return);
609 | 				echo '
'; 610 | 611 | } 612 | 613 | return $return; 614 | } 615 | } -------------------------------------------------------------------------------- /src/index.php: -------------------------------------------------------------------------------- 1 | '; 7 | print_r($result); 8 | echo ''; 9 | -------------------------------------------------------------------------------- /src/install.php: -------------------------------------------------------------------------------- 1 | 6 | 7 | 8 | 9 | 14 | 15 | 16 | 17 | 18 | installation has been finished 19 | 20 | installation error 21 | 22 | 23 |