Skip to content

Commit 14d2557

Browse files
committed
Корректировка функции конвертации формы в массив данных,
Пример класса для работы с API под InstantCMS
1 parent a66977a commit 14d2557

File tree

3 files changed

+240
-1
lines changed

3 files changed

+240
-1
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
# InstantCMS JSON API client class
2+
3+
Класс для работы с API с сайта на базе InstantCMS
4+
5+
## Установка
6+
7+
Файл api.php скопировать по пути /system/core/api.php
8+
9+
## Использование
10+
11+
Вызовы можно осуществлять из любого места кода InstantCMS
12+
13+
Обычные методы
14+
```php
15+
// Без кэширования ответа
16+
$result = cmsApi::getMethod('auth.login', ['sig' => 'qwerty', 'email' => 'test@example.com', 'password' => '123456']);
17+
// С кэшированием ответа
18+
$result = cmsApi::getMethod('auth.login', ['sig' => 'qwerty', 'email' => 'test@example.com', 'password' => '123456'], true);
19+
```
20+
21+
Метод execute
22+
```php
23+
$result = cmsApi::getExecute([
24+
[
25+
'method' => 'geo.get',
26+
'key' => 'countries',
27+
'params' => [
28+
'type' => 'countries'
29+
]
30+
],
31+
[
32+
'method' => 'users.get_user',
33+
'key' => 'profile',
34+
'params' => [
35+
'user_id' => $user_id
36+
]
37+
]
38+
]);
39+
```
40+
41+
## Ссылки
42+
43+
* [Официальный сайт InstantCMS](https://instantcms.ru/)
44+
* [Документация компонента](https://docs.instantcms.ru/manual/components/api)

clientExamples/instantcms/api.php

Lines changed: 194 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,194 @@
1+
<?php
2+
final class cmsApi {
3+
4+
/**
5+
* Время кеширования ответа в секундах
6+
*/
7+
const cache_time = 300;
8+
9+
/**
10+
* Ключ API
11+
*/
12+
const api_key = 'YOU_KEY';
13+
14+
/**
15+
* Паттерн базового url для методов API
16+
*/
17+
const api_point = 'https://example.com/%s/method/';
18+
19+
/**
20+
* Паттерн базового url для метода execute
21+
*/
22+
const api_point_execute = 'https://example.com/%s/';
23+
24+
/**
25+
* Кешированный результат от вызова метода users.get_sig
26+
* @var string
27+
*/
28+
private static $signature = null;
29+
30+
/**
31+
* Возвращает базовый url для метода execute
32+
* @return string
33+
*/
34+
public static function getApiExecutePoint() {
35+
return sprintf(self::api_point_execute, cmsCore::getLanguageName());
36+
}
37+
38+
/**
39+
* Возвращает базовый url для обычных методов
40+
* @return string
41+
*/
42+
public static function getApiPoint() {
43+
return sprintf(self::api_point, cmsCore::getLanguageName());
44+
}
45+
46+
/**
47+
* Возвращает сигнатуры csrf_token или sig
48+
* @param string $name csrf_token или sig
49+
* @return string
50+
*/
51+
public static function getSignature($name = 'csrf_token') {
52+
53+
if (self::$signature === null) {
54+
55+
$response = self::getMethod('users.get_sig');
56+
57+
self::$signature = $response['response'];
58+
59+
}
60+
61+
return isset(self::$signature[$name]) ? self::$signature[$name] : self::$signature;
62+
63+
}
64+
65+
/**
66+
* Запрашивает метод API
67+
*
68+
* @param string $name Имя метода
69+
* @param array $params Параметры методы
70+
* @param boolean $cacheable Кэшировать ответ
71+
* @param boolean $is_upload Флаг, что мы загружаем файлы
72+
* @param string $api_point Базовый url запроса
73+
* @return array
74+
*/
75+
public static function getMethod($name, $params = [], $cacheable = false, $is_upload = false, $api_point = false) {
76+
77+
if (!function_exists('curl_init')) {
78+
return [
79+
'error' => [
80+
'error_msg' => 'Please, install curl'
81+
]
82+
];
83+
}
84+
85+
if(!$api_point){
86+
$api_point = self::getApiPoint();
87+
}
88+
89+
$cache_file = cmsConfig::get('cache_path') . 'api/' . md5($name . serialize($params) . cmsCore::getLanguageName()) . '.dat';
90+
91+
if ($cacheable && is_readable($cache_file)) {
92+
93+
$time_diff = (time() - filemtime($cache_file));
94+
95+
if ($time_diff < self::cache_time) {
96+
97+
$result = include $cache_file;
98+
99+
if ($result) {
100+
return $result;
101+
} else {
102+
unlink($cache_file);
103+
}
104+
105+
} else {
106+
unlink($cache_file);
107+
}
108+
}
109+
110+
$curl = curl_init();
111+
112+
if (isset($params['cookie'])) {
113+
114+
$cookie = [];
115+
116+
foreach ($params['cookie'] as $k => $v) {
117+
$cookie[] = $k . '=' . $v;
118+
}
119+
120+
curl_setopt($curl, CURLOPT_HTTPHEADER, ['Cookie: ' . implode('; ', $cookie)]);
121+
122+
unset($params['cookie']);
123+
124+
} elseif (cmsUser::isLogged()) {
125+
126+
$user = cmsUser::getInstance();
127+
128+
curl_setopt($curl, CURLOPT_HTTPHEADER, ['Cookie: ' . $user->api_session_name . '=' . $user->api_session_id]);
129+
130+
} elseif (cmsUser::isSessionSet('guest_session:session_id')) {
131+
132+
curl_setopt($curl, CURLOPT_HTTPHEADER, ['Cookie: ' . cmsUser::sessionGet('guest_session:session_name') . '=' . cmsUser::sessionGet('guest_session:session_id')]);
133+
}
134+
135+
$params['api_key'] = self::api_key;
136+
$params['ip'] = cmsUser::getIp();
137+
138+
$params_string = !$is_upload ? http_build_query($params) : $params;
139+
140+
curl_setopt($curl, CURLOPT_URL, $api_point . $name);
141+
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
142+
curl_setopt($curl, CURLOPT_HEADER, false);
143+
curl_setopt($curl, CURLOPT_TIMEOUT, 5);
144+
curl_setopt($curl, CURLOPT_POSTFIELDS, $params_string);
145+
146+
$_data = curl_exec($curl);
147+
148+
if (!$_data) {
149+
return [
150+
'error' => [
151+
'error_msg' => LANG_API_ERROR
152+
]
153+
];
154+
}
155+
156+
$data = json_decode($_data, true);
157+
158+
curl_close($curl);
159+
160+
if ($data === false) {
161+
return [
162+
'error' => [
163+
'error_msg' => json_last_error_msg()
164+
]
165+
];
166+
}
167+
168+
if (isset($data['session'])) {
169+
cmsUser::sessionSet('guest_session:session_name', $data['session']['session_name']);
170+
cmsUser::sessionSet('guest_session:session_id', $data['session']['session_id']);
171+
}
172+
173+
if ($cacheable) {
174+
file_put_contents($cache_file, '<?php return ' . var_export($data, true) . ';');
175+
}
176+
177+
return $data;
178+
179+
}
180+
181+
/**
182+
* Выполняет метод execute
183+
* https://docs.instantcms.ru/manual/components/api/methods/execute
184+
*
185+
* @param array $params Параметр code метода в виде массива
186+
* @param boolean $cacheable Кэшировать ответ
187+
* @param boolean $is_upload Флаг, что мы загружаем файлы
188+
* @return array
189+
*/
190+
public static function getExecute($params, $cacheable = false, $is_upload = false) {
191+
return self::getMethod('execute', ['code' => json_encode($params)], $cacheable, $is_upload, self::getApiExecutePoint());
192+
}
193+
194+
}

package/system/controllers/api/frontend.php

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -324,11 +324,12 @@ function form_to_params($form) {
324324

325325
$param['fields'][$field->getName()] = array(
326326
'title' => $field->title,
327-
'type' => $field->class,
327+
'type' => isset($field->field_type) ? $field->field_type : $field->class, // совместимость
328328
'name' => $field->getName(),
329329
'rules' => $field->getRules(),
330330
'var_type' => $field->var_type,
331331
'items' => (method_exists($field, 'getListItems') ? $field->getListItems() : null),
332+
'attributes' => (!empty($field->attributes) ? $field->attributes : null),
332333
'hint' => (!empty($field->hint) ? $field->hint : null),
333334
'units' => (!empty($field->units) ? $field->units : null),
334335
'default' => (isset($field->default) ? $field->default : null)

0 commit comments

Comments
 (0)