From 13ae80e4d5e3c750dac0cc4d8950f9e5571db616 Mon Sep 17 00:00:00 2001 From: fuzegit Date: Tue, 20 Jun 2023 13:50:31 +0300 Subject: [PATCH] =?UTF-8?q?=D0=A1=D0=BE=D0=B2=D0=BC=D0=B5=D1=81=D1=82?= =?UTF-8?q?=D0=B8=D0=BC=D0=BE=D1=81=D1=82=D1=8C=20InstantCMS=202.16.0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- clientExamples/instantcms/README.md | 2 +- clientExamples/instantcms/api.php | 27 +-- manifest.en.ini | 6 +- manifest.ru.ini | 6 +- .../system/controllers/api/actions/method.php | 88 +++---- .../api/api_actions/api_content_get.php | 2 +- .../api/api_actions/api_images_upload.php | 74 +++--- package/system/controllers/api/backend.php | 21 +- .../controllers/api/backend/actions/keys.php | 21 +- package/system/controllers/api/frontend.php | 214 +++++++++--------- .../api/hooks/admin_dashboard_chart.php | 4 +- package/system/controllers/api/manifest.php | 9 - package/system/controllers/api/model.php | 13 +- 13 files changed, 245 insertions(+), 242 deletions(-) delete mode 100644 package/system/controllers/api/manifest.php diff --git a/clientExamples/instantcms/README.md b/clientExamples/instantcms/README.md index 570899b..dc8eb68 100644 --- a/clientExamples/instantcms/README.md +++ b/clientExamples/instantcms/README.md @@ -8,7 +8,7 @@ ## Использование -Заполнить константы api_key, api_point, api_point_execute своими данными. +Заполнить константы api_key, api_point, api_point_execute своими данными (example.com заменить на свой домен). Создать директорию /cache/api/. В ней будут кэшироваться ответы. Вызовы можно осуществлять из любого места кода InstantCMS diff --git a/clientExamples/instantcms/api.php b/clientExamples/instantcms/api.php index 4284eaf..668b882 100644 --- a/clientExamples/instantcms/api.php +++ b/clientExamples/instantcms/api.php @@ -86,24 +86,27 @@ public static function getMethod($name, $params = [], $cacheable = false, $is_up $api_point = self::getApiPoint(); } - $cache_file = cmsConfig::get('cache_path') . 'api/' . md5($name . serialize($params) . cmsCore::getLanguageName()) . '.dat'; + if ($cacheable) { + + $cache_file = cmsConfig::get('cache_path') . 'api/' . md5($name . serialize($params) . cmsCore::getLanguageName()) . '.dat'; + + if (is_readable($cache_file)) { - if ($cacheable && is_readable($cache_file)) { + $time_diff = (time() - filemtime($cache_file)); - $time_diff = (time() - filemtime($cache_file)); + if ($time_diff < self::cache_time) { - if ($time_diff < self::cache_time) { + $result = include $cache_file; - $result = include $cache_file; + if ($result) { + return $result; + } else { + unlink($cache_file); + } - if ($result) { - return $result; } else { unlink($cache_file); } - - } else { - unlink($cache_file); } } @@ -123,9 +126,7 @@ public static function getMethod($name, $params = [], $cacheable = false, $is_up } elseif (cmsUser::isLogged()) { - $user = cmsUser::getInstance(); - - curl_setopt($curl, CURLOPT_HTTPHEADER, ['Cookie: ' . $user->api_session_name . '=' . $user->api_session_id]); + curl_setopt($curl, CURLOPT_HTTPHEADER, ['Cookie: ' . cmsUser::sessionGet('user_session:session_name') . '=' . cmsUser::sessionGet('user_session:session_id')]); } elseif (cmsUser::isSessionSet('guest_session:session_id')) { diff --git a/manifest.en.ini b/manifest.en.ini index f5fbf9a..598370e 100755 --- a/manifest.en.ini +++ b/manifest.en.ini @@ -5,12 +5,12 @@ addon_id = "600" [version] major = "2" -minor = "3" +minor = "4" build = "0" -date = "20200409" +date = "20230620" [depends] -core = "2.11.0" +core = "2.14.0" [author] name = "InstantCMS Team" diff --git a/manifest.ru.ini b/manifest.ru.ini index 8e15aac..1778c7c 100755 --- a/manifest.ru.ini +++ b/manifest.ru.ini @@ -5,12 +5,12 @@ addon_id = "600" [version] major = "2" -minor = "3" +minor = "4" build = "0" -date = "20200409" +date = "20230620" [depends] -core = "2.11.0" +core = "2.14.0" [author] name = "InstantCMS Team" diff --git a/package/system/controllers/api/actions/method.php b/package/system/controllers/api/actions/method.php index 7cac239..8583203 100755 --- a/package/system/controllers/api/actions/method.php +++ b/package/system/controllers/api/actions/method.php @@ -2,14 +2,14 @@ /******************************************************************************/ // // // InstantMedia // -// http://instantmedia.ru/, support@instantmedia.ru // -// written by Fuze // +// http://instantmedia.ru/ // +// written by Fuze // // // /******************************************************************************/ class actionApiMethod extends cmsAction { - private $method_params = array(); + private $method_params = []; private $method_controller_name = null; private $method_action_name = null; @@ -18,21 +18,19 @@ class actionApiMethod extends cmsAction { * @var object */ private $method_controller = null; + /** * Объект класса api метода * @var object */ - private $method_action = null; + private $method_action = null; - public function __construct($controller, $params=array()){ + public function __construct($controller, $params = []) { parent::__construct($controller, $params); $this->loadApiKey(); - // для метода after ставим коллбэк, нам не нужен вывод на экран шаблона - $this->setCallback('after', array(array($controller, 'renderJSON'))); - } /** @@ -44,7 +42,10 @@ public function __construct($controller, $params=array()){ private function initMethod($method_name) { $this->method_name = $method_name; - if(empty($this->method_name)){ return $this; } + + if (!$this->method_name) { + return $this; + } $segments = explode('.', $method_name); @@ -53,7 +54,7 @@ private function initMethod($method_name) { $this->method_controller_name = trim($segments[0]); - if ($this->method_controller_name && !preg_match('/^[a-z]{1}[a-z0-9_]*$/', $this->method_controller_name)){ + if ($this->method_controller_name && !preg_match('/^[a-z]{1}[a-z0-9_]*$/', $this->method_controller_name)) { $this->method_controller_name = null; } @@ -61,32 +62,29 @@ private function initMethod($method_name) { $this->method_controller_name = null; } - if($this->method_controller_name){ + if ($this->method_controller_name) { $this->method_controller = cmsCore::getController($this->method_controller_name, $this->request); } - } // действие if (isset($segments[1])) { $this->method_action_name = trim($segments[1]); - if ($this->method_action_name && !preg_match('/^[a-z]{1}[a-z0-9_]*$/', $this->method_action_name)){ + if ($this->method_action_name && !preg_match('/^[a-z]{1}[a-z0-9_]*$/', $this->method_action_name)) { $this->method_action_name = null; } - if($this->method_action_name && $this->method_controller !== null){ - $this->method_controller->current_action = 'api_'.$this->method_controller_name.'_'.$this->method_action_name; + if ($this->method_action_name && $this->method_controller !== null) { + $this->method_controller->current_action = 'api_' . $this->method_controller_name . '_' . $this->method_action_name; } - } // Параметры действия - if (count($segments) > 2){ + if (count($segments) > 2) { $this->method_params = array_slice($segments, 2); } return $this; - } /** @@ -279,7 +277,6 @@ public function run($method_name = null){ // действия после успешного запроса return $this->afterRequest(); - } /** @@ -289,25 +286,25 @@ public function run($method_name = null){ private function afterRequest() { // записываем в лог, если включено - if(!empty($this->options['log_success'])){ - $this->model->log(array( - 'request_time' => number_format(cmsCore::getTime(), 4), - 'method' => $this->method_name, - 'key_id' => $this->key['id'] - )); + if (!empty($this->options['log_success'])) { + + $this->model->log([ + 'request_time' => number_format((microtime(true) - $this->start_time), 4), + 'method' => $this->method_name, + 'key_id' => $this->key['id'] + ]); } return true; - } private function validateMethodParams() { - if(empty($this->method_action->request_params)){ + if (empty($this->method_action->request_params)) { return false; } - $errors = array(); + $errors = []; // валидация аналогична валидации форм foreach ($this->method_action->request_params as $param_name => $rules) { @@ -320,19 +317,20 @@ private function validateMethodParams() { $this->request->set($param_name, $value); - } elseif(!is_null($value) && isset($rules['default'])){ + } elseif (!is_null($value) && isset($rules['default'])) { $value = $this->request->get($param_name, $rules['default']); // для применения типизации переменной $this->request->set($param_name, $value); - } - if(!empty($rules['rules'])){ + if (!empty($rules['rules'])) { foreach ($rules['rules'] as $rule) { - if (!$rule) { continue; } + if (!$rule) { + continue; + } $validate_function = "validate_{$rule[0]}"; @@ -340,7 +338,7 @@ private function validateMethodParams() { unset($rule[0]); - $result = call_user_func_array(array($this, $validate_function), $rule); + $result = call_user_func_array([$this, $validate_function], $rule); // если получилось false, то дальше не проверяем, т.к. // ошибка уже найдена @@ -348,16 +346,15 @@ private function validateMethodParams() { $errors[$param_name] = $result; break; } - } } - } - if (!sizeof($errors)) { return false; } + if (!sizeof($errors)) { + return false; + } return $errors; - } /** @@ -367,23 +364,27 @@ private function validateMethodParams() { public function checkRequest() { $parent_succes = parent::checkRequest(); - if(!$parent_succes){ return false; } - if(empty($this->method_name) || + if (!$parent_succes) { + return false; + } + + if (empty($this->method_name) || empty($this->method_controller_name) || - $this->method_controller === null){ + $this->method_controller === null) { + return $this->error(3); } - if(empty($this->method_action_name)){ + if (empty($this->method_action_name)) { return $this->error(8); } - if(!$this->method_controller->isEnabled()){ + if (!$this->method_controller->isEnabled()) { return $this->error(23); } - $check_method_name = $this->method_controller_name.'.'.$this->method_action_name; + $check_method_name = $this->method_controller_name . '.' . $this->method_action_name; $is_view = !$this->key['key_methods']['allow'] || in_array($check_method_name, $this->key['key_methods']['allow']); $is_hide = $this->key['key_methods']['disallow'] && in_array($check_method_name, $this->key['key_methods']['disallow']); @@ -394,7 +395,6 @@ public function checkRequest() { } return true; - } } diff --git a/package/system/controllers/api/api_actions/api_content_get.php b/package/system/controllers/api/api_actions/api_content_get.php index 568d15b..49680cc 100644 --- a/package/system/controllers/api/api_actions/api_content_get.php +++ b/package/system/controllers/api/api_actions/api_content_get.php @@ -154,7 +154,7 @@ public function run($ctype_name){ if (empty($this->ctype['options']['list_on'])) { return; } // параметры - $perpage = (empty($this->ctype['options']['limit']) ? content::perpage : $this->ctype['options']['limit']); + $perpage = (empty($this->ctype['options']['limit']) ? 10 : $this->ctype['options']['limit']); $page = $this->request->get('page'); $hide_root = !empty($this->ctype['options']['is_empty_root']) && $this->cat['id'] == 1; diff --git a/package/system/controllers/api/api_actions/api_images_upload.php b/package/system/controllers/api/api_actions/api_images_upload.php index 2b9db02..467cca1 100644 --- a/package/system/controllers/api/api_actions/api_images_upload.php +++ b/package/system/controllers/api/api_actions/api_images_upload.php @@ -27,81 +27,87 @@ class actionImagesApiImagesUpload extends cmsAction { public function validateApiRequest() { - $result = $this->cms_uploader->setAllowedMime($this->allowed_mime)-> - upload($this->request->get('name'), $this->getAllowedExtensions()); + $name = $this->request->get('name'); - if ($result['success']){ - if (!$this->cms_uploader->isImage($result['path'])){ + // устанавливаем разрешенные типы изображений + $this->cms_uploader->setAllowedMime($this->allowed_mime); - files_delete_file($result['path'], 2); + cmsEventsManager::hook('images_before_upload', array($name, $this->cms_uploader), null, $this->request); - return array( - 'error_msg' => LANG_UPLOAD_ERR_MIME - ); + // Непосредственно загружаем + $result = $this->cms_uploader->upload($name); + // Начинаем работу с изображением + if ($result['success']){ + + try { + $image = new cmsImages($result['path']); + } catch (Exception $exc) { + $result['success'] = false; + $result['error'] = LANG_UPLOAD_ERR_MIME; } + } + // Не получилось, удаляем исходник, показываем ошибку if (!$result['success']){ - if(!empty($result['path'])){ files_delete_file($result['path'], 2); } - return array( 'error_msg' => $result['error'] ); - } + // Переданные пресеты $sizes = $this->request->get('presets'); - $file_name = $this->request->get('file_name', ''); - if ($sizes && preg_match('/([a-z0-9_,]+)$/i', $sizes)){ + if (!empty($sizes)){ $sizes = explode(',', $sizes); } else { $sizes = array_keys((array)$this->model->getPresetsList()); $sizes[] = 'original'; } - $result['paths'] = array(); + // Результирующий массив изображений после конвертации + $result['paths'] = []; + // Дополняем оригиналом, если нужно if (in_array('original', $sizes, true)){ - $result['paths']['original'] = $result['url']; + $result['paths']['original'] = array( + 'path' => $result['url'], + 'url' => $this->cms_config->upload_host_abs . '/' . $result['url'] + ); } + // Получаем пресеты $presets = $this->model->orderByList(array( - array('by' => 'is_square', 'to' => 'asc'), - array('by' => 'width', 'to' => 'desc') + ['by' => 'is_square', 'to' => 'asc'], + ['by' => 'width', 'to' => 'desc'] ))->getPresets(); + list($result, $presets, $sizes) = cmsEventsManager::hook('images_after_upload', array($result, $presets, $sizes), null, $this->request); + + // Создаём изображения по пресетам foreach($presets as $p){ if (!in_array($p['name'], $sizes, true)){ continue; } - if($file_name){ - $this->cms_uploader->setFileName($file_name.' '.$p['name']); - } - - $path = $this->cms_uploader->resizeImage($result['path'], array( - 'width' => $p['width'], - 'height' => $p['height'], - 'is_square' => $p['is_square'], - 'quality' => (($p['is_watermark'] && $p['wm_image']) ? 100 : $p['quality']) // потом уже при наложении ватермарка будет правильное качество - )); - - if (!$path) { continue; } + $resized_path = $image->resizeByPreset($p); - if ($p['is_watermark'] && $p['wm_image']){ - img_add_watermark($path, $p['wm_image']['original'], $p['wm_origin'], $p['wm_margin'], $p['quality']); - } + if (!$resized_path) { continue; } - $result['paths'][$p['name']] = $path; + $result['paths'][$p['name']] = [ + 'path' => $resized_path, + 'url' => $this->cms_config->upload_host_abs . '/' . $resized_path + ]; } + list($result, $presets, $sizes) = cmsEventsManager::hook('images_after_resize', array($result, $presets, $sizes), null, $this->request); + if (!in_array('original', $sizes, true)){ files_delete_file($result['path'], 2); } @@ -109,11 +115,9 @@ public function validateApiRequest() { unset($result['path']); if(!$result['paths']){ - return array( 'error_msg' => LANG_UPLOAD_ERR_NO_FILE ); - } $this->result['items'] = $result['paths']; diff --git a/package/system/controllers/api/backend.php b/package/system/controllers/api/backend.php index 4730914..d2e6e74 100644 --- a/package/system/controllers/api/backend.php +++ b/package/system/controllers/api/backend.php @@ -2,8 +2,8 @@ /******************************************************************************/ // // // InstantMedia // -// http://instantmedia.ru/, support@instantmedia.ru // -// written by Fuze // +// http://instantmedia.ru/ // +// written by Fuze // // // /******************************************************************************/ @@ -11,21 +11,22 @@ class backendApi extends cmsBackend { public $useDefaultOptionsAction = true; - public function actionIndex(){ + public function actionIndex() { $this->redirectToAction('options'); } - public function getBackendMenu(){ - return array( - array( + public function getBackendMenu() { + + return [ + [ 'title' => LANG_OPTIONS, 'url' => href_to($this->root_url, 'options') - ), - array( + ], + [ 'title' => LANG_API_KEYS, 'url' => href_to($this->root_url, 'keys') - ) - ); + ] + ]; } } diff --git a/package/system/controllers/api/backend/actions/keys.php b/package/system/controllers/api/backend/actions/keys.php index 76786c2..5539844 100644 --- a/package/system/controllers/api/backend/actions/keys.php +++ b/package/system/controllers/api/backend/actions/keys.php @@ -2,31 +2,31 @@ /******************************************************************************/ // // // InstantMedia // -// http://instantmedia.ru/, support@instantmedia.ru // -// written by Fuze // +// http://instantmedia.ru/ // +// written by Fuze // // // /******************************************************************************/ class actionApiKeys extends cmsAction { - public function run(){ + public function run() { $grid = $this->loadDataGrid('keys'); if ($this->request->isAjax()) { - $this->model->setPerPage(admin::perpage); + $this->model->setPerPage(30); - $filter = array(); + $filter = []; $filter_str = $this->request->get('filter', ''); - if ($filter_str){ + if ($filter_str) { parse_str($filter_str, $filter); $this->model->applyGridFilter($grid, $filter); } $total = $this->model->getCount('api_keys'); - $perpage = isset($filter['perpage']) ? $filter['perpage'] : admin::perpage; + $perpage = isset($filter['perpage']) ? $filter['perpage'] : 30; $pages = ceil($total / $perpage); $data = $this->model->get('api_keys'); @@ -34,13 +34,10 @@ public function run(){ $this->cms_template->renderGridRowsJSON($grid, $data, $total, $pages); $this->halt(); - } - return $this->cms_template->render('backend/keys', array( + return $this->cms_template->render('backend/keys', [ 'grid' => $grid - )); - + ]); } - } diff --git a/package/system/controllers/api/frontend.php b/package/system/controllers/api/frontend.php index ebb3460..a5c2c7a 100755 --- a/package/system/controllers/api/frontend.php +++ b/package/system/controllers/api/frontend.php @@ -2,35 +2,38 @@ /******************************************************************************/ // // // InstantMedia // -// http://instantmedia.ru/, support@instantmedia.ru // -// written by Fuze // +// http://instantmedia.ru/ // +// written by Fuze // // // /******************************************************************************/ class api extends cmsFrontend { - protected $useOptions = true; + protected $useOptions = true; - private $output_success = array(); - private $output_error = array(); + private $output_success = []; + private $output_error = []; - public $key = null; + public $key = null; public $method_name = null; - public function __construct($request){ + public $start_time = null; - cmsCore::startTimer(); + public function __construct($request) { + + $this->start_time = microtime(true); parent::__construct($request); // устанавливаем ошибку по-умолчанию $this->setError(1); - } public function loadApiKey() { - if($this->key !== null){ return $this; } + if ($this->key !== null) { + return $this; + } $headers = apache_request_headers(); @@ -39,7 +42,6 @@ public function loadApiKey() { $this->key = $this->model->getKey($api_key); return $this; - } /** @@ -48,20 +50,19 @@ public function loadApiKey() { */ public function checkRequest() { - if(empty($this->key)){ + if (empty($this->key)) { return $this->error(101); } - if($this->key['ip_access'] && !string_in_mask_list(cmsUser::getIp(), $this->key['ip_access'])){ + if ($this->key['ip_access'] && !string_in_mask_list(cmsUser::getIp(), $this->key['ip_access'])) { return $this->error(15); } - if(!$this->key['is_pub']){ + if (!$this->key['is_pub']) { return $this->error(2); } return true; - } public function actionIndex() { @@ -74,14 +75,12 @@ public function actionIndex() { */ public function actionExecute() { - $this->setCallback('after', array(array($this, 'renderJSON'))); - $this->loadApiKey(); // если передан ip адрес, считаем его адресом посетителя // для различных проверок компонентов // т.к. движок определяет ip адрес места запроса - if($this->request->has('ip')){ + if ($this->request->has('ip')) { $ip = $this->request->get('ip', ''); @@ -90,43 +89,47 @@ public function actionExecute() { } // совместимость - if(method_exists('cmsUser', 'setIp')){ + if (method_exists('cmsUser', 'setIp')) { cmsUser::setIp($ip); } - } - if(!$this->checkRequest()){ + if (!$this->checkRequest()) { return false; } $code = $this->request->get('code', ''); - if(!$code){ return $this->error(100); } + if (!$code) { + return $this->error(100); + } $methods = json_decode($code, true); if (json_last_error() !== JSON_ERROR_NONE || !$methods) { return $this->error(12); } - $response = array(); + $response = []; $max_method_count = 10; - if(count($methods) > $max_method_count){ + if (count($methods) > $max_method_count) { return $this->error(13); } foreach ($methods as $method_param) { - if(empty($method_param['method'])){ return $this->error(13); } + if (empty($method_param['method'])) { + return $this->error(13); + } - $this->request->setData(!empty($method_param['params']) ? $method_param['params'] : array()); + $this->request->setData(!empty($method_param['params']) ? $method_param['params'] : []); - $method_result = $this->runExternalAction('method', array($method_param['method'])); + $method_result = $this->runExternalAction('method', [$method_param['method']]); - if(!$method_result){ return $this->error(13); } + if (!$method_result) { + return $this->error(13); + } $response[!empty($method_param['key']) ? $method_param['key'] : $method_param['method']] = $this->output_success['response']; - } $this->setSuccess($response); @@ -138,21 +141,21 @@ public function actionExecute() { * @param string $action_name * @return boolean */ - public function after($action_name){ + public function after($action_name) { parent::after($action_name); - if(!$this->cms_user->is_logged && $this->output_success){ - $this->output_success['session'] = array( + if (!$this->cms_user->is_logged && $this->output_success) { + + $this->output_success['session'] = [ 'session_name' => session_name(), 'session_id' => session_id() - ); + ]; } - $this->processCallback('after', array()); + $this->renderJSON(); return true; - } /** @@ -161,16 +164,17 @@ public function after($action_name){ */ public function setSuccess($api_request_result) { - $success = array( + $success = [ 'response' => $api_request_result - ); + ]; + + if ($this->cms_config->debug && cmsUser::isAdmin()) { - if ($this->cms_config->debug && cmsUser::isAdmin()){ - $success['debug'] = array( + $success['debug'] = [ 'time' => cmsDebugging::getTime('cms', 4), - 'mem' => round(memory_get_usage(true)/1024/1024, 2), + 'mem' => round(memory_get_usage(true) / 1024 / 1024, 2), 'data' => cmsDebugging::getPointsData() - ); + ]; } $this->output_success = $success; @@ -183,27 +187,29 @@ public function setSuccess($api_request_result) { * @param string $error_msg * @param array $request_params */ - public function setError($error_code, $error_msg = '', $request_params = array()) { + public function setError($error_code, $error_msg = '', $request_params = []) { + + if ($error_msg) { - if($error_msg){ - $this->output_error['error'] = array( + $this->output_error['error'] = [ 'error_code' => ($error_code ? $error_code : 0), 'error_msg' => $error_msg, 'request_params' => $request_params - ); + ]; + } else { - $this->output_error['error'] = array( + + $this->output_error['error'] = [ 'error_code' => $error_code, 'error_msg' => constant('LANG_API_ERROR' . $error_code), 'request_params' => $request_params - ); + ]; } // если уже есть результат, очищаем его - $this->output_success = array(); + $this->output_success = []; return $this; - } /** @@ -212,22 +218,22 @@ public function setError($error_code, $error_msg = '', $request_params = array() * @param string $error_msg * @param array $request_params */ - public function error($error_code, $error_msg = '', $request_params = array()) { + public function error($error_code, $error_msg = '', $request_params = []) { // записываем в лог ошибку, если включена их фиксация - if(!empty($this->options['log_error'])){ - $this->model->log(array( - 'request_time' => number_format(cmsCore::getTime(), 4), - 'error' => $error_code, - 'method' => $this->method_name, - 'key_id' => (!empty($this->key['id']) ? $this->key['id'] : null) - )); + if (!empty($this->options['log_error'])) { + + $this->model->log([ + 'request_time' => number_format((microtime(true) - $this->start_time), 4), + 'error' => $error_code, + 'method' => $this->method_name, + 'key_id' => (!empty($this->key['id']) ? $this->key['id'] : null) + ]); } $this->setError($error_code, $error_msg, $request_params); return false; - } /** @@ -246,27 +252,32 @@ public function renderJSON() { // apache_request_headers replicement for nginx if (!function_exists('apache_request_headers')) { + function apache_request_headers() { - foreach($_SERVER as $key=>$value) { + foreach ($_SERVER as $key => $value) { if (substr($key, 0, 5) == 'HTTP_') { - $key=str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($key, 5))))); - $out[$key]=$value; - }else{ - $out[$key]=$value; + $key = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($key, 5))))); + $out[$key] = $value; + } else { + $out[$key] = $value; } } return $out; + } } -function api_image_src($images, $size_preset = false){ + +function api_image_src($images, $size_preset = false) { $config = cmsConfig::getInstance(); - if (!is_array($images)){ + if (!is_array($images)) { $images = cmsModel::yamlToArray($images); } - if (!$images){ return null; } + if (!$images) { + return null; + } $result = array(); @@ -283,36 +294,38 @@ function api_image_src($images, $size_preset = false){ } return $result; - } + function form_to_params($form) { $params = array('csrf_token' => array( - 'title' => 'csrf_token', - 'fields' => array( - array( - 'title' => null, - 'data' => array ( - 'type' => 'hidden' - ), - 'type' => 'string', - 'name' => 'csrf_token', - 'rules' => array ( - array ('required') - ), - 'var_type' => 'string', - 'items' => null, - 'placeholder' => null, - 'default' => cmsForm::getCSRFToken() + 'title' => 'csrf_token', + 'fields' => array( + array( + 'title' => null, + 'data' => array( + 'type' => 'hidden' + ), + 'type' => 'string', + 'name' => 'csrf_token', + 'rules' => array( + array('required') + ), + 'var_type' => 'string', + 'items' => null, + 'placeholder' => null, + 'default' => cmsForm::getCSRFToken() + ) ) - ) )); $structure = $form->getStructure(); - foreach($structure as $key => $fieldset){ + foreach ($structure as $key => $fieldset) { - if (empty($fieldset['childs'])) { continue; } + if (empty($fieldset['childs'])) { + continue; + } $param = array( 'title' => (!empty($fieldset['title']) ? $fieldset['title'] : null), @@ -320,36 +333,35 @@ function form_to_params($form) { 'fields' => array() ); - foreach($fieldset['childs'] as $field){ + foreach ($fieldset['childs'] as $field) { $param['fields'][$field->getName()] = array( - 'title' => $field->title, + 'title' => $field->title, 'field_type' => isset($field->field_type) ? $field->field_type : $field->class, // совместимость - 'type' => (!empty($field->type) ? $field->type : null), - 'name' => $field->getName(), - 'rules' => $field->getRules(), - 'var_type' => $field->var_type, - 'items' => (method_exists($field, 'getListItems') ? $field->getListItems() : null), - 'options' => (!empty($field->options) ? $field->options : null), + 'type' => (!empty($field->type) ? $field->type : null), + 'name' => $field->getName(), + 'rules' => $field->getRules(), + 'var_type' => $field->var_type, + 'items' => (method_exists($field, 'getListItems') ? $field->getListItems() : null), + 'options' => (!empty($field->options) ? $field->options : null), 'attributes' => (!empty($field->attributes) ? $field->attributes : null), - 'hint' => (!empty($field->hint) ? $field->hint : null), - 'units' => (!empty($field->units) ? $field->units : null), - 'default' => (isset($field->default) ? $field->default : null) + 'hint' => (!empty($field->hint) ? $field->hint : null), + 'units' => (!empty($field->units) ? $field->units : null), + 'default' => (isset($field->default) ? $field->default : null) ); - } $params[$key] = $param; - } return $params; - } + function get_sig() { $ip = cmsUser::getIp(); - return md5($ip.md5(md5(cmsConfig::get('host')).md5(cmsConfig::get('db_base')).sprintf('%u',ip2long($ip)))); + return md5($ip . md5(md5(cmsConfig::get('host')) . md5(cmsConfig::get('db_base')) . sprintf('%u', ip2long($ip)))); } + function check_sig($sig) { return $sig === get_sig(); } diff --git a/package/system/controllers/api/hooks/admin_dashboard_chart.php b/package/system/controllers/api/hooks/admin_dashboard_chart.php index af44dec..8dea588 100644 --- a/package/system/controllers/api/hooks/admin_dashboard_chart.php +++ b/package/system/controllers/api/hooks/admin_dashboard_chart.php @@ -2,8 +2,8 @@ /******************************************************************************/ // // // InstantMedia // -// http://instantmedia.ru/, support@instantmedia.ru // -// written by Fuze // +// http://instantmedia.ru/ // +// written by Fuze // // // /******************************************************************************/ diff --git a/package/system/controllers/api/manifest.php b/package/system/controllers/api/manifest.php deleted file mode 100644 index e8d6bfb..0000000 --- a/package/system/controllers/api/manifest.php +++ /dev/null @@ -1,9 +0,0 @@ - array( - 'admin_dashboard_chart' - ) - - ); diff --git a/package/system/controllers/api/model.php b/package/system/controllers/api/model.php index 54e92fd..db6b106 100644 --- a/package/system/controllers/api/model.php +++ b/package/system/controllers/api/model.php @@ -2,8 +2,8 @@ /******************************************************************************/ // // // InstantMedia // -// http://instantmedia.ru/, support@instantmedia.ru // -// written by Fuze // +// http://instantmedia.ru/ // +// written by Fuze // // // /******************************************************************************/ @@ -11,20 +11,19 @@ class modelApi extends cmsModel { public function getKey($id) { - if(is_numeric($id)){ + if (is_numeric($id)) { $field = 'id'; } else { $field = 'api_key'; } - $key = $this->filterEqual($field, $id)->getItem('api_keys'); + $key = $this->filterEqual($field, $id)->getItem('api_keys'); - if($key){ + if ($key) { $key['key_methods'] = cmsModel::yamlToArray($key['key_methods']); } return $key; - } public function deleteKey($id) { @@ -33,7 +32,6 @@ public function deleteKey($id) { $this->delete('api_logs', $id, 'key_id'); return true; - } public function log($data) { @@ -41,7 +39,6 @@ public function log($data) { $this->insert('api_logs', $data); return false; - } }