Advertisement
vgrish

api2gis

Oct 17th, 2013
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 13.67 KB | None | 0 0
  1. <?php
  2.  
  3. Class api2gis_catalog {
  4. /**
  5. * @var string url to DG catalog API (Default: http://catalog.api.2gis.ru/)
  6. **/
  7. private $api_server = 'http://catalog.api.2gis.ru/';
  8.  
  9. /**
  10. * @var int Values 1 and 2 (Default: 1)
  11. **/
  12. private $api_http_type = 2;
  13.  
  14. /**
  15. * @var int timeout for request
  16. **/
  17. private $timeout = 3;
  18.  
  19. /**
  20. * @var string api version
  21. * @link http://api.2gis.ru/doc/firms/list/project-list/#sel=14:1,14:1
  22. **/
  23. private $api_version = '1.3';
  24.  
  25. /**
  26. * @var string response output (Default: json)
  27. * @link http://api.2gis.ru/doc/firms/list/project-list/#sel=18:1,18:1
  28. **/
  29. private $api_output = 'json';
  30.  
  31. /**
  32. * @var string api key
  33. * @link http://api.2gis.ru/doc/firms/list/project-list/#sel=9:1,9:1
  34. **/
  35. private $api_key = '';
  36.  
  37. /**
  38. * @var string city name
  39. **/
  40. private $api_city = 'владимир';
  41.  
  42. /**
  43. * @var bool fix utf-8 encode for windows-1251 sites
  44. **/
  45. private $fix_encode = true;
  46.  
  47. /**
  48. * @var array API URL action list
  49. **/
  50. private $api_url_action = array(
  51. 'rubricator' => 'rubricator', // Rubrics
  52. 'search' => 'search', // Firm search
  53. 'searchinrubric' => 'searchinrubric', // Firm search in rubric
  54. 'profile' => 'profile', // Profile
  55. 'filials' => 'firmsByFilialId' // Filials
  56. );
  57.  
  58. /**
  59. * @var array API Response code messages
  60. **/
  61. private $api_response_codes = array(
  62. '200' => 'Успешный запрос.',
  63. '400' => 'Ошибка в запросе.',
  64. '403' => 'Доступ запрещен.',
  65. '404' => 'По запросу ничего не найдено.',
  66. '500' => 'Внутренняя ошибка сервера.',
  67. '503' => 'Сервис временно не доступен.',
  68. );
  69.  
  70. /**
  71. * @var array API Response error messages
  72. **/
  73. private $api_error_codes = array(
  74. 'methodNotFound' => 'Запрошенный метод API не существует.',
  75. 'withoutResult' => 'Результаты по запросу не найдены.',
  76. 'incorrectGeography' => 'Некорректно задано значение поля «Где?» или других полей, отвечающих за географию.',
  77. 'forbidden' => 'Доступ к API запрещен для ключа, указанного в запросе.',
  78. 'unauthorized' => 'Ключ, указанный в запросе, не существует.',
  79. 'unsupportedVersion' => 'Указанная версия API не поддерживается.',
  80. 'versionIsRequired' => 'Не задана версия API.',
  81. 'unsupportedOutput' => 'Указанное значение output не поддерживается.',
  82. 'incorrectCallback' => 'Некорректно задан параметр {callback}',
  83. 'whatIsEmpty' => 'Не заполнено поле «Что?»',
  84. 'whatTooShort' => 'В поле «Что?» слишком мало символов.',
  85. 'whatTooLarge' => 'В поле «Что?» слишком много символов.',
  86. 'wherePointIsEmpty' => 'Не указана точка (при поиске по точке).',
  87. 'whereIsEmpty' => 'Не заполнено поле «Где?»',
  88. 'whereTooShort' => 'В поле «Где?» слишком мало символов.',
  89. 'whereTooLarge' => 'В поле «Где?» слишком много символов.',
  90. 'conflictingParams' => 'В запросе присутствуют взаимоисключаемые параметры.',
  91. 'incorrectLimit' => 'Некорректно задан параметр {limit}.',
  92. 'incorrectRadius' => 'Некорректно задан параметр {radius}.',
  93. 'incorrectPoint' => 'Некорректно задан параметр {point}.',
  94. 'incorrectOrder' => 'Некорректно задан параметр {order}.',
  95. 'incorrectRubricOrder' => 'Некорректно задан параметр {sort}.',
  96. 'incorrectPage' => 'екорректно задан параметр page.',
  97. 'incorrectPageSize' => 'Некорректно задан параметр {pagesize}.',
  98. 'incorrectProject' => 'Некорректно задан проект.',
  99. 'incorrectEncoding' => 'Запрос передан в неправильной кодировке.',
  100. 'firmRequired' => 'Не задан идентификатор фирмы.',
  101. 'firmIdInvalid' => 'Некорректно задан идентификатор фирмы.',
  102. 'geometryRequired' => 'Не задан идентификатор геометрии.',
  103. 'geometryIdInvalid' => 'Некорректно задаан идентификатор геометрии.',
  104. 'rubricIdInvalid' => 'Некорректно задан идентификатор рубрики.',
  105. 'hashRequired' => 'Не задан обязательный параметр {hash}.',
  106. 'hashInvalid' => 'Некорректно задан параметр {hash}.',
  107. 'serviceUnavailable' => 'Сервис временно недоступен.',
  108. 'worktimeInvalid' => 'Неправильно задан фильтр {worktime}.',
  109. 'idsRequired' => 'В запросе отсутствует список идентификаторов.',
  110. 'incorrectFormat' => 'Некорректно задан параметр {format}.',
  111. 'tooManyIds' => 'В запросе передано слишком много идентификаторов.'
  112. );
  113.  
  114. /**
  115. * Get response message by response code
  116. *
  117. * @param int $code: response code
  118. *
  119. * @return string
  120. **/
  121. private function getMessageCode($code) {
  122. return str_replace(array('{', '}'), array('<i>', '</i>'), $this->api_response_codes[$code]);
  123. }
  124.  
  125. /**
  126. * Get error message
  127. *
  128. * @param int $error: Error code
  129. *
  130. * @return string
  131. **/
  132. private function getMessageError($error) {
  133. return str_replace(array('{', '}'), array('<i>', '</i>'), $this->api_error_codes[$error]);
  134. }
  135.  
  136. /**
  137. * Fix UTF-8
  138. *
  139. * @param mixed $data
  140. * @param string $type default w (u)
  141. *
  142. * @return mixed
  143. **/
  144. private function Utf8Win($data, $type = "w") {
  145. if ($this->fix_encode) {
  146. if (is_string($data)) {
  147. static $conv = '';
  148.  
  149. $conv = array();
  150.  
  151. for ($x = 128; $x <= 143; $x++) {
  152. $conv['u'][] = chr(209).chr($x);
  153. $conv['w'][] = chr($x+112);
  154. }
  155.  
  156. for ($x = 144; $x <= 191; $x++) {
  157. $conv['u'][] = chr(208).chr($x);
  158. $conv['w'][] = chr($x+48);
  159. }
  160.  
  161. $conv['u'][] = chr(208).chr(129);
  162. $conv['w'][] = chr(168);
  163. $conv['u'][] = chr(209).chr(145);
  164. $conv['w'][] = chr(184);
  165. $conv['u'][] = chr(208).chr(135);
  166. $conv['w'][] = chr(175);
  167. $conv['u'][] = chr(209).chr(151);
  168. $conv['w'][] = chr(191);
  169. $conv['u'][] = chr(208).chr(134);
  170. $conv['w'][] = chr(178);
  171. $conv['u'][] = chr(209).chr(150);
  172. $conv['w'][] = chr(179);
  173. $conv['u'][] = chr(210).chr(144);
  174. $conv['w'][] = chr(165);
  175. $conv['u'][] = chr(210).chr(145);
  176. $conv['w'][] = chr(180);
  177. $conv['u'][] = chr(208).chr(132);
  178. $conv['w'][] = chr(170);
  179. $conv['u'][] = chr(209).chr(148);
  180. $conv['w'][] = chr(186);
  181. $conv['u'][] = chr(226).chr(132).chr(150);
  182. $conv['w'][] = chr(185);
  183.  
  184. if ($type == 'w') {
  185. $data = str_replace($conv['u'], $conv['w'], $data);
  186. } elseif ($type == 'u') {
  187. $data = str_replace($conv['w'], $conv['u'], $data);
  188. }
  189.  
  190. return str_replace(array("“","”"), array('&laquo;','&raquo;'), $data);
  191. } elseif (is_array($data)) {
  192. foreach ($data as $key => $value) {
  193. $data[$key] = $this->Utf8Win($value);
  194. }
  195. } elseif (is_object($data)) {
  196. $data_array = array();
  197.  
  198. foreach ($data as $key => $value) {
  199. $data_array[$key] = $this->Utf8Win($value);
  200. }
  201.  
  202. $data = $data_array;
  203. }
  204. }
  205.  
  206. return $data;
  207. }
  208.  
  209. /**
  210. * Generate API URL link for request
  211. *
  212. * @param string $api_action: API Action from list api_url_action
  213. * @param array $api_params
  214. *
  215. * @return string
  216. **/
  217. private function getApiURL($api_action, $api_params = array()) {
  218. if (!$this->api_url_action[$api_action]) {
  219. return $this->api_server;
  220. }
  221.  
  222. $do_params = '';
  223.  
  224. if (count($api_params)) {
  225. foreach ($api_params as $key => $value) {
  226. $do_params .= '&'.$key.'='.$value;
  227. }
  228. }
  229.  
  230. return $this->api_server.$this->api_url_action[$api_action].'?version='.$this->api_version.'&key='.$this->api_key.'&output='.$this->api_output.$do_params;
  231. }
  232.  
  233. /**
  234. * Get API Data by URL (PHP cURL Lib needed)
  235. *
  236. * @param string $url: API URL link
  237. *
  238. * @return array
  239. **/
  240. private function getRequest($url) {
  241. if (!$this->api_server) {
  242. return array(
  243. 'response_code' => 0,
  244. 'message' => 'URL not set.'
  245. );
  246. }
  247.  
  248. if ($this->fix_encode) {
  249. $url = iconv('windows-1251', 'utf-8', $url);
  250. }
  251.  
  252. if (function_exists('curl_init') && $this->api_http_type == 2) {
  253. $ch = curl_init();
  254.  
  255. curl_setopt($ch, CURLOPT_URL, $url);
  256. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  257. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  258. curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout);
  259.  
  260. $result = curl_exec($ch);
  261. $response_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);/*
  262. $errno = curl_errno($ch);
  263. $error = curl_error($ch);*/
  264.  
  265. curl_close($ch);
  266. } else {
  267. $result = @file_get_contents($url, 0, stream_context_create(
  268. array('http' => array('timeout' => $this->timeout))
  269. ));
  270.  
  271. preg_match("/HTTP\/[0\.1]{3} ([0-9]{3}) .*/i", $http_response_header[0], $response_matches);
  272.  
  273. $response_code = $response_matches[1];
  274. }
  275.  
  276. if ($this->fix_encode) {
  277. $result = $this->Utf8Win(json_decode($result));
  278. }
  279.  
  280. if ($this->api_response_codes[$response_code]) {
  281. $result['error_message'] = $this->getMessageError($result['error_code']);
  282.  
  283. return $result;
  284. } else {
  285. return array(
  286. 'response_code' => $response_code,
  287. 'message' => 'Unknown error.'
  288. );
  289. }
  290.  
  291. return $result;
  292. }
  293.  
  294. /**
  295. * Selects rubrics
  296. *
  297. * @param bool $children: If it true - select rubrics with childs (Default: false)
  298. *
  299. * @return array
  300. **/
  301. public function getRubricator($children = false) {
  302. $do_params = array(
  303. 'where' => $this->api_city
  304. );
  305.  
  306. if ($children) {
  307. $do_params['show_children'] = '1';
  308. }
  309.  
  310. return $this->getRequest($this->getApiURL('rubricator', $do_params));
  311. }
  312.  
  313. /**
  314. * Selects full profile information
  315. *
  316. * @param int $id: ID of selectable profile
  317. * @param string $hash: Hash of selectable profile
  318. *
  319. * @return array
  320. **/
  321. public function getProfile($id, $hash) {
  322. return $this->getRequest($this->getApiURL('profile', array(
  323. 'id' => $id,
  324. 'hash' => $hash
  325. )));
  326. }
  327.  
  328. /**
  329. * Selects short profiles information from rubric
  330. *
  331. * @param string $rubric: Rubric name
  332. * @param int $per_page: Number of profiles per page (Default: 30, min - 5, max - 50)
  333. * @param int $page: Page number (Default: 1)
  334. * @param string $sort_by: Sort by - name, relevance, rating, distance (Default: relevance)
  335. *
  336. * @return array
  337. **/
  338. public function getProfiles($rubric, $per_page = 30, $page = 1, $sort_by = 'name') {
  339. return $this->getRequest($this->getApiURL('searchinrubric', array(
  340. 'what' => $rubric,
  341. 'where' => $this->api_city,
  342. 'page' => $page,
  343. 'pagesize' => $per_page,
  344. 'sort' => $sort_by
  345. )));
  346. }
  347.  
  348. /**
  349. * Search profiles
  350. *
  351. * @param string $search: Searchable word
  352. * @param int $per_page: Number of profiles per page (Default: 30, min - 5, max - 50)
  353. * @param int $page: Page number (Default: 1)
  354. * @param string $sort_by: Sort by - name, relevance, rating, distance (Default: relevance)
  355. *
  356. * @return array
  357. **/
  358. public function getSearch($search, $per_page = 30, $page = 1, $sort_by = 'relevance') {
  359. return $this->getRequest($this->getApiURL('search', array(
  360. 'what' => $search,
  361. 'where' => $this->api_city,
  362. 'page' => $page,
  363. 'pagesize' => $per_page,
  364. 'sort' => $sort_by
  365. )));
  366. }
  367.  
  368. /**
  369. * Get filials group
  370. *
  371. * @param int $id: ID of filial group
  372. * @param int $per_page: Number of profiles per page (Default: 30, min - 5, max - 50)
  373. * @param int $page: Page number (Default: 1)
  374. *
  375. * @return array
  376. **/
  377. public function getFilials($id, $per_page = 30, $page = 1) {
  378. return $this->getRequest($this->getApiURL('filials', array(
  379. 'firmid' => $id,
  380. 'pagesize' => $per_page,
  381. 'page' => $page
  382. )));
  383. }
  384. }
  385.  
  386. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement