Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- Class api2gis_catalog {
- /**
- * @var string url to DG catalog API (Default: http://catalog.api.2gis.ru/)
- **/
- private $api_server = 'http://catalog.api.2gis.ru/';
- /**
- * @var int Values 1 and 2 (Default: 1)
- **/
- private $api_http_type = 2;
- /**
- * @var int timeout for request
- **/
- private $timeout = 3;
- /**
- * @var string api version
- * @link http://api.2gis.ru/doc/firms/list/project-list/#sel=14:1,14:1
- **/
- private $api_version = '1.3';
- /**
- * @var string response output (Default: json)
- * @link http://api.2gis.ru/doc/firms/list/project-list/#sel=18:1,18:1
- **/
- private $api_output = 'json';
- /**
- * @var string api key
- * @link http://api.2gis.ru/doc/firms/list/project-list/#sel=9:1,9:1
- **/
- private $api_key = '';
- /**
- * @var string city name
- **/
- private $api_city = 'владимир';
- /**
- * @var bool fix utf-8 encode for windows-1251 sites
- **/
- private $fix_encode = true;
- /**
- * @var array API URL action list
- **/
- private $api_url_action = array(
- 'rubricator' => 'rubricator', // Rubrics
- 'search' => 'search', // Firm search
- 'searchinrubric' => 'searchinrubric', // Firm search in rubric
- 'profile' => 'profile', // Profile
- 'filials' => 'firmsByFilialId' // Filials
- );
- /**
- * @var array API Response code messages
- **/
- private $api_response_codes = array(
- '200' => 'Успешный запрос.',
- '400' => 'Ошибка в запросе.',
- '403' => 'Доступ запрещен.',
- '404' => 'По запросу ничего не найдено.',
- '500' => 'Внутренняя ошибка сервера.',
- '503' => 'Сервис временно не доступен.',
- );
- /**
- * @var array API Response error messages
- **/
- private $api_error_codes = array(
- 'methodNotFound' => 'Запрошенный метод API не существует.',
- 'withoutResult' => 'Результаты по запросу не найдены.',
- 'incorrectGeography' => 'Некорректно задано значение поля «Где?» или других полей, отвечающих за географию.',
- 'forbidden' => 'Доступ к API запрещен для ключа, указанного в запросе.',
- 'unauthorized' => 'Ключ, указанный в запросе, не существует.',
- 'unsupportedVersion' => 'Указанная версия API не поддерживается.',
- 'versionIsRequired' => 'Не задана версия API.',
- 'unsupportedOutput' => 'Указанное значение output не поддерживается.',
- 'incorrectCallback' => 'Некорректно задан параметр {callback}',
- 'whatIsEmpty' => 'Не заполнено поле «Что?»',
- 'whatTooShort' => 'В поле «Что?» слишком мало символов.',
- 'whatTooLarge' => 'В поле «Что?» слишком много символов.',
- 'wherePointIsEmpty' => 'Не указана точка (при поиске по точке).',
- 'whereIsEmpty' => 'Не заполнено поле «Где?»',
- 'whereTooShort' => 'В поле «Где?» слишком мало символов.',
- 'whereTooLarge' => 'В поле «Где?» слишком много символов.',
- 'conflictingParams' => 'В запросе присутствуют взаимоисключаемые параметры.',
- 'incorrectLimit' => 'Некорректно задан параметр {limit}.',
- 'incorrectRadius' => 'Некорректно задан параметр {radius}.',
- 'incorrectPoint' => 'Некорректно задан параметр {point}.',
- 'incorrectOrder' => 'Некорректно задан параметр {order}.',
- 'incorrectRubricOrder' => 'Некорректно задан параметр {sort}.',
- 'incorrectPage' => 'екорректно задан параметр page.',
- 'incorrectPageSize' => 'Некорректно задан параметр {pagesize}.',
- 'incorrectProject' => 'Некорректно задан проект.',
- 'incorrectEncoding' => 'Запрос передан в неправильной кодировке.',
- 'firmRequired' => 'Не задан идентификатор фирмы.',
- 'firmIdInvalid' => 'Некорректно задан идентификатор фирмы.',
- 'geometryRequired' => 'Не задан идентификатор геометрии.',
- 'geometryIdInvalid' => 'Некорректно задаан идентификатор геометрии.',
- 'rubricIdInvalid' => 'Некорректно задан идентификатор рубрики.',
- 'hashRequired' => 'Не задан обязательный параметр {hash}.',
- 'hashInvalid' => 'Некорректно задан параметр {hash}.',
- 'serviceUnavailable' => 'Сервис временно недоступен.',
- 'worktimeInvalid' => 'Неправильно задан фильтр {worktime}.',
- 'idsRequired' => 'В запросе отсутствует список идентификаторов.',
- 'incorrectFormat' => 'Некорректно задан параметр {format}.',
- 'tooManyIds' => 'В запросе передано слишком много идентификаторов.'
- );
- /**
- * Get response message by response code
- *
- * @param int $code: response code
- *
- * @return string
- **/
- private function getMessageCode($code) {
- return str_replace(array('{', '}'), array('<i>', '</i>'), $this->api_response_codes[$code]);
- }
- /**
- * Get error message
- *
- * @param int $error: Error code
- *
- * @return string
- **/
- private function getMessageError($error) {
- return str_replace(array('{', '}'), array('<i>', '</i>'), $this->api_error_codes[$error]);
- }
- /**
- * Fix UTF-8
- *
- * @param mixed $data
- * @param string $type default w (u)
- *
- * @return mixed
- **/
- private function Utf8Win($data, $type = "w") {
- if ($this->fix_encode) {
- if (is_string($data)) {
- static $conv = '';
- $conv = array();
- for ($x = 128; $x <= 143; $x++) {
- $conv['u'][] = chr(209).chr($x);
- $conv['w'][] = chr($x+112);
- }
- for ($x = 144; $x <= 191; $x++) {
- $conv['u'][] = chr(208).chr($x);
- $conv['w'][] = chr($x+48);
- }
- $conv['u'][] = chr(208).chr(129);
- $conv['w'][] = chr(168);
- $conv['u'][] = chr(209).chr(145);
- $conv['w'][] = chr(184);
- $conv['u'][] = chr(208).chr(135);
- $conv['w'][] = chr(175);
- $conv['u'][] = chr(209).chr(151);
- $conv['w'][] = chr(191);
- $conv['u'][] = chr(208).chr(134);
- $conv['w'][] = chr(178);
- $conv['u'][] = chr(209).chr(150);
- $conv['w'][] = chr(179);
- $conv['u'][] = chr(210).chr(144);
- $conv['w'][] = chr(165);
- $conv['u'][] = chr(210).chr(145);
- $conv['w'][] = chr(180);
- $conv['u'][] = chr(208).chr(132);
- $conv['w'][] = chr(170);
- $conv['u'][] = chr(209).chr(148);
- $conv['w'][] = chr(186);
- $conv['u'][] = chr(226).chr(132).chr(150);
- $conv['w'][] = chr(185);
- if ($type == 'w') {
- $data = str_replace($conv['u'], $conv['w'], $data);
- } elseif ($type == 'u') {
- $data = str_replace($conv['w'], $conv['u'], $data);
- }
- return str_replace(array("“","”"), array('«','»'), $data);
- } elseif (is_array($data)) {
- foreach ($data as $key => $value) {
- $data[$key] = $this->Utf8Win($value);
- }
- } elseif (is_object($data)) {
- $data_array = array();
- foreach ($data as $key => $value) {
- $data_array[$key] = $this->Utf8Win($value);
- }
- $data = $data_array;
- }
- }
- return $data;
- }
- /**
- * Generate API URL link for request
- *
- * @param string $api_action: API Action from list api_url_action
- * @param array $api_params
- *
- * @return string
- **/
- private function getApiURL($api_action, $api_params = array()) {
- if (!$this->api_url_action[$api_action]) {
- return $this->api_server;
- }
- $do_params = '';
- if (count($api_params)) {
- foreach ($api_params as $key => $value) {
- $do_params .= '&'.$key.'='.$value;
- }
- }
- return $this->api_server.$this->api_url_action[$api_action].'?version='.$this->api_version.'&key='.$this->api_key.'&output='.$this->api_output.$do_params;
- }
- /**
- * Get API Data by URL (PHP cURL Lib needed)
- *
- * @param string $url: API URL link
- *
- * @return array
- **/
- private function getRequest($url) {
- if (!$this->api_server) {
- return array(
- 'response_code' => 0,
- 'message' => 'URL not set.'
- );
- }
- if ($this->fix_encode) {
- $url = iconv('windows-1251', 'utf-8', $url);
- }
- if (function_exists('curl_init') && $this->api_http_type == 2) {
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, $url);
- curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout);
- $result = curl_exec($ch);
- $response_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);/*
- $errno = curl_errno($ch);
- $error = curl_error($ch);*/
- curl_close($ch);
- } else {
- $result = @file_get_contents($url, 0, stream_context_create(
- array('http' => array('timeout' => $this->timeout))
- ));
- preg_match("/HTTP\/[0\.1]{3} ([0-9]{3}) .*/i", $http_response_header[0], $response_matches);
- $response_code = $response_matches[1];
- }
- if ($this->fix_encode) {
- $result = $this->Utf8Win(json_decode($result));
- }
- if ($this->api_response_codes[$response_code]) {
- $result['error_message'] = $this->getMessageError($result['error_code']);
- return $result;
- } else {
- return array(
- 'response_code' => $response_code,
- 'message' => 'Unknown error.'
- );
- }
- return $result;
- }
- /**
- * Selects rubrics
- *
- * @param bool $children: If it true - select rubrics with childs (Default: false)
- *
- * @return array
- **/
- public function getRubricator($children = false) {
- $do_params = array(
- 'where' => $this->api_city
- );
- if ($children) {
- $do_params['show_children'] = '1';
- }
- return $this->getRequest($this->getApiURL('rubricator', $do_params));
- }
- /**
- * Selects full profile information
- *
- * @param int $id: ID of selectable profile
- * @param string $hash: Hash of selectable profile
- *
- * @return array
- **/
- public function getProfile($id, $hash) {
- return $this->getRequest($this->getApiURL('profile', array(
- 'id' => $id,
- 'hash' => $hash
- )));
- }
- /**
- * Selects short profiles information from rubric
- *
- * @param string $rubric: Rubric name
- * @param int $per_page: Number of profiles per page (Default: 30, min - 5, max - 50)
- * @param int $page: Page number (Default: 1)
- * @param string $sort_by: Sort by - name, relevance, rating, distance (Default: relevance)
- *
- * @return array
- **/
- public function getProfiles($rubric, $per_page = 30, $page = 1, $sort_by = 'name') {
- return $this->getRequest($this->getApiURL('searchinrubric', array(
- 'what' => $rubric,
- 'where' => $this->api_city,
- 'page' => $page,
- 'pagesize' => $per_page,
- 'sort' => $sort_by
- )));
- }
- /**
- * Search profiles
- *
- * @param string $search: Searchable word
- * @param int $per_page: Number of profiles per page (Default: 30, min - 5, max - 50)
- * @param int $page: Page number (Default: 1)
- * @param string $sort_by: Sort by - name, relevance, rating, distance (Default: relevance)
- *
- * @return array
- **/
- public function getSearch($search, $per_page = 30, $page = 1, $sort_by = 'relevance') {
- return $this->getRequest($this->getApiURL('search', array(
- 'what' => $search,
- 'where' => $this->api_city,
- 'page' => $page,
- 'pagesize' => $per_page,
- 'sort' => $sort_by
- )));
- }
- /**
- * Get filials group
- *
- * @param int $id: ID of filial group
- * @param int $per_page: Number of profiles per page (Default: 30, min - 5, max - 50)
- * @param int $page: Page number (Default: 1)
- *
- * @return array
- **/
- public function getFilials($id, $per_page = 30, $page = 1) {
- return $this->getRequest($this->getApiURL('filials', array(
- 'firmid' => $id,
- 'pagesize' => $per_page,
- 'page' => $page
- )));
- }
- }
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement