PageRenderTime 110ms CodeModel.GetById 32ms RepoModel.GetById 0ms app.codeStats 0ms

/fuel/core/classes/controller/rest.php

https://bitbucket.org/sriedel/iccrm-wip
PHP | 450 lines | 275 code | 68 blank | 107 comment | 37 complexity | 97ab99c7262bd25ddb6b540166672cd4 MD5 | raw file
Possible License(s): MIT
  1. <?php
  2. namespace Fuel\Core;
  3. abstract class Controller_Rest extends \Controller
  4. {
  5. /**
  6. * @var null|string Set this in a controller to use a default format
  7. */
  8. protected $rest_format = null;
  9. /**
  10. * @var array contains a list of method properties such as limit, log and level
  11. */
  12. protected $methods = array();
  13. /**
  14. * @var integer status code to return in case a not defined action is called
  15. */
  16. protected $no_method_status = 405;
  17. /**
  18. * @var integer status code to return in case the called action doesn't return data
  19. */
  20. protected $no_data_status = 204;
  21. /**
  22. * @var string the detected response format
  23. */
  24. protected $format = null;
  25. /**
  26. * @var integer response http status
  27. */
  28. protected $http_status = null;
  29. /**
  30. * @var string xml basenode name
  31. */
  32. protected $xml_basenode = null;
  33. /**
  34. * @var array List all supported methods
  35. */
  36. protected $_supported_formats = array(
  37. 'xml' => 'application/xml',
  38. 'rawxml' => 'application/xml',
  39. 'json' => 'application/json',
  40. 'jsonp'=> 'text/javascript',
  41. 'serialized' => 'application/vnd.php.serialized',
  42. 'php' => 'text/plain',
  43. 'html' => 'text/html',
  44. 'csv' => 'application/csv',
  45. );
  46. public function before()
  47. {
  48. parent::before();
  49. // Some Methods cant have a body
  50. $this->request->body = null;
  51. // Which format should the data be returned in?
  52. $this->request->lang = $this->_detect_lang();
  53. $this->response = \Response::forge();
  54. }
  55. public function after($response)
  56. {
  57. // If the response is an array
  58. if (is_array($response))
  59. {
  60. // set the response
  61. $response = $this->response($response);
  62. }
  63. // If the response is a Response object, we will use their
  64. // instead of ours.
  65. if ( ! $response instanceof Response)
  66. {
  67. $response = $this->response;
  68. }
  69. return parent::after($response);
  70. }
  71. /**
  72. * Router
  73. *
  74. * Requests are not made to methods directly The request will be for an "object".
  75. * this simply maps the object and method to the correct Controller method.
  76. *
  77. * @param string
  78. * @param array
  79. */
  80. public function router($resource, array $arguments)
  81. {
  82. \Config::load('rest', true);
  83. // If no (or an invalid) format is given, auto detect the format
  84. if (is_null($this->format) or ! array_key_exists($this->format, $this->_supported_formats))
  85. {
  86. // auto-detect the format
  87. $this->format = array_key_exists(\Input::extension(), $this->_supported_formats) ? \Input::extension() : $this->_detect_format();
  88. }
  89. //Check method is authorized if required
  90. if (\Config::get('rest.auth') == 'basic')
  91. {
  92. $valid_login = $this->_prepare_basic_auth();
  93. }
  94. elseif (\Config::get('rest.auth') == 'digest')
  95. {
  96. $valid_login = $this->_prepare_digest_auth();
  97. }
  98. //If the request passes auth then execute as normal
  99. if(\Config::get('rest.auth') == '' or $valid_login)
  100. {
  101. // If they call user, go to $this->post_user();
  102. $controller_method = strtolower(\Input::method()) . '_' . $resource;
  103. // Fall back to action_ if no rest method is provided
  104. if ( ! method_exists($this, $controller_method))
  105. {
  106. $controller_method = 'action_'.$resource;
  107. }
  108. // If method is not available, set status code to 404
  109. if (method_exists($this, $controller_method))
  110. {
  111. return call_user_func_array(array($this, $controller_method), $arguments);
  112. }
  113. else
  114. {
  115. $this->response->status = $this->no_method_status;
  116. return;
  117. }
  118. }
  119. else
  120. {
  121. $this->response(array('status'=> 0, 'error'=> 'Not Authorized'), 401);
  122. }
  123. }
  124. /**
  125. * Response
  126. *
  127. * Takes pure data and optionally a status code, then creates the response
  128. *
  129. * @param mixed
  130. * @param int
  131. * @return object Response instance
  132. */
  133. protected function response($data = array(), $http_status = null)
  134. {
  135. if ((is_array($data) and empty($data)) or ($data == ''))
  136. {
  137. $this->response->status = $this->no_data_status;
  138. return $this->response;
  139. }
  140. $http_status or $http_status = $this->http_status;
  141. // If the format method exists, call and return the output in that format
  142. if (method_exists('Format', 'to_'.$this->format))
  143. {
  144. // Set the correct format header
  145. $this->response->set_header('Content-Type', $this->_supported_formats[$this->format]);
  146. // Handle XML output
  147. if ($this->format === 'xml')
  148. {
  149. // Detect basenode
  150. $xml_basenode = $this->xml_basenode;
  151. $xml_basenode or $xml_basenode = \Config::get('rest.xml_basenode', 'xml');
  152. // Set the XML response
  153. $this->response->body(\Format::forge($data)->{'to_'.$this->format}(null, null, $xml_basenode));
  154. }
  155. else
  156. {
  157. // Set the formatted response
  158. $this->response->body(\Format::forge($data)->{'to_'.$this->format}());
  159. }
  160. // Set the reponse http status
  161. $http_status and $this->response->status = $http_status;
  162. }
  163. // Format not supported, output directly
  164. else
  165. {
  166. $this->response->body($data);
  167. }
  168. return $this->response;
  169. }
  170. /**
  171. * Set the Response http status.
  172. *
  173. * @param integer $status response http status code
  174. * @return void
  175. */
  176. protected function http_status($status)
  177. {
  178. $this->http_status = $status;
  179. }
  180. /**
  181. * Detect format
  182. *
  183. * Detect which format should be used to output the data
  184. *
  185. * @return string
  186. */
  187. protected function _detect_format()
  188. {
  189. // A format has been passed as an argument in the URL and it is supported
  190. if (\Input::param('format') and $this->_supported_formats[\Input::param('format')])
  191. {
  192. return \Input::param('format');
  193. }
  194. // Otherwise, check the HTTP_ACCEPT (if it exists and we are allowed)
  195. if (\Input::server('HTTP_ACCEPT') and \Config::get('rest.ignore_http_accept') !== true)
  196. {
  197. // Split the Accept header and build an array of quality scores for each format
  198. $fragments = new \CachingIterator(new \ArrayIterator(preg_split('/[,;]/', \Input::server('HTTP_ACCEPT'))));
  199. $acceptable = array();
  200. $next_is_quality = false;
  201. foreach ($fragments as $fragment)
  202. {
  203. $quality = 1;
  204. // Skip the fragment if it is a quality score
  205. if ($next_is_quality)
  206. {
  207. $next_is_quality = false;
  208. continue;
  209. }
  210. // If next fragment exists and is a quality score, set the quality score
  211. elseif ($fragments->hasNext())
  212. {
  213. $next = $fragments->getInnerIterator()->current();
  214. if (strpos($next, 'q=') === 0)
  215. {
  216. list($key, $quality) = explode('=', $next);
  217. $next_is_quality = true;
  218. }
  219. }
  220. $acceptable[$fragment] = $quality;
  221. }
  222. // Sort the formats by score in descending order
  223. uasort($acceptable, function($a, $b)
  224. {
  225. $a = (float) $a;
  226. $b = (float) $b;
  227. return ($a > $b) ? -1 : 1;
  228. });
  229. // Check each of the acceptable formats against the supported formats
  230. foreach ($acceptable as $pattern => $quality)
  231. {
  232. // The Accept header can contain wildcards in the format
  233. $find = array('*', '/');
  234. $replace = array('.*', '\/');
  235. $pattern = '/^' . str_replace($find, $replace, $pattern) . '$/';
  236. foreach ($this->_supported_formats as $format => $mime)
  237. {
  238. if (preg_match($pattern, $mime))
  239. {
  240. return $format;
  241. }
  242. }
  243. }
  244. } // End HTTP_ACCEPT checking
  245. // Well, none of that has worked! Let's see if the controller has a default
  246. if ( ! empty($this->rest_format))
  247. {
  248. return $this->rest_format;
  249. }
  250. // Just use the default format
  251. return \Config::get('rest.default_format');
  252. }
  253. /**
  254. * Detect language(s)
  255. *
  256. * What language do they want it in?
  257. *
  258. * @return null|array|string
  259. */
  260. protected function _detect_lang()
  261. {
  262. if (!$lang = \Input::server('HTTP_ACCEPT_LANGUAGE'))
  263. {
  264. return null;
  265. }
  266. // They might have sent a few, make it an array
  267. if (strpos($lang, ',') !== false)
  268. {
  269. $langs = explode(',', $lang);
  270. $return_langs = array();
  271. foreach ($langs as $lang)
  272. {
  273. // Remove weight and strip space
  274. list($lang) = explode(';', $lang);
  275. $return_langs[] = trim($lang);
  276. }
  277. return $return_langs;
  278. }
  279. // Nope, just return the string
  280. return $lang;
  281. }
  282. // SECURITY FUNCTIONS ---------------------------------------------------------
  283. protected function _check_login($username = '', $password = null)
  284. {
  285. if (empty($username))
  286. {
  287. return false;
  288. }
  289. $valid_logins = \Config::get('rest.valid_logins');
  290. if (!array_key_exists($username, $valid_logins))
  291. {
  292. return false;
  293. }
  294. // If actually null (not empty string) then do not check it
  295. if ($password !== null and $valid_logins[$username] != $password)
  296. {
  297. return false;
  298. }
  299. return true;
  300. }
  301. protected function _prepare_basic_auth()
  302. {
  303. $username = null;
  304. $password = null;
  305. // mod_php
  306. if (\Input::server('PHP_AUTH_USER'))
  307. {
  308. $username = \Input::server('PHP_AUTH_USER');
  309. $password = \Input::server('PHP_AUTH_PW');
  310. }
  311. // most other servers
  312. elseif (\Input::server('HTTP_AUTHENTICATION'))
  313. {
  314. if (strpos(strtolower(\Input::server('HTTP_AUTHENTICATION')), 'basic') === 0)
  315. {
  316. list($username, $password) = explode(':', base64_decode(substr(\Input::server('HTTP_AUTHORIZATION'), 6)));
  317. }
  318. }
  319. if ( ! static::_check_login($username, $password))
  320. {
  321. static::_force_login();
  322. return false;
  323. }
  324. return true;
  325. }
  326. protected function _prepare_digest_auth()
  327. {
  328. $uniqid = uniqid(""); // Empty argument for backward compatibility
  329. // We need to test which server authentication variable to use
  330. // because the PHP ISAPI module in IIS acts different from CGI
  331. if (\Input::server('PHP_AUTH_DIGEST'))
  332. {
  333. $digest_string = \Input::server('PHP_AUTH_DIGEST');
  334. }
  335. elseif (\Input::server('HTTP_AUTHORIZATION'))
  336. {
  337. $digest_string = \Input::server('HTTP_AUTHORIZATION');
  338. }
  339. else
  340. {
  341. $digest_string = '';
  342. }
  343. /* The $_SESSION['error_prompted'] variabile is used to ask
  344. the password again if none given or if the user enters
  345. a wrong auth. informations. */
  346. if (empty($digest_string))
  347. {
  348. static::_force_login($uniqid);
  349. return false;
  350. }
  351. // We need to retrieve authentication informations from the $auth_data variable
  352. preg_match_all('@(username|nonce|uri|nc|cnonce|qop|response)=[\'"]?([^\'",]+)@', $digest_string, $matches);
  353. $digest = array_combine($matches[1], $matches[2]);
  354. if ( ! array_key_exists('username', $digest) or ! static::_check_login($digest['username']))
  355. {
  356. static::_force_login($uniqid);
  357. return false;
  358. }
  359. $valid_logins = \Config::get('rest.valid_logins');
  360. $valid_pass = $valid_logins[$digest['username']];
  361. // This is the valid response expected
  362. $A1 = md5($digest['username'] . ':' . \Config::get('rest.realm') . ':' . $valid_pass);
  363. $A2 = md5(strtoupper(\Input::method()) . ':' . $digest['uri']);
  364. $valid_response = md5($A1 . ':' . $digest['nonce'] . ':' . $digest['nc'] . ':' . $digest['cnonce'] . ':' . $digest['qop'] . ':' . $A2);
  365. if ($digest['response'] != $valid_response)
  366. {
  367. return false;
  368. }
  369. return true;
  370. }
  371. protected function _force_login($nonce = '')
  372. {
  373. if (\Config::get('rest.auth') == 'basic')
  374. {
  375. $this->response->set_header('WWW-Authenticate', 'Basic realm="'. \Config::get('rest.realm') . '"');
  376. }
  377. elseif (\Config::get('rest.auth') == 'digest')
  378. {
  379. $this->response->set_header('WWW-Authenticate', 'Digest realm="' . \Config::get('rest.realm') . '", qop="auth", nonce="' . $nonce . '", opaque="' . md5(\Config::get('rest.realm')) . '"');
  380. }
  381. }
  382. }