Request.php 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. <?php declare(strict_types=1);
  2. /**
  3. * PrivateBin
  4. *
  5. * a zero-knowledge paste bin
  6. *
  7. * @link https://github.com/PrivateBin/PrivateBin
  8. * @copyright 2012 Sébastien SAUVAGE (sebsauvage.net)
  9. * @license https://www.opensource.org/licenses/zlib-license.php The zlib/libpng License
  10. */
  11. namespace PrivateBin;
  12. use Exception;
  13. /**
  14. * Request
  15. *
  16. * parses request parameters and provides helper functions for routing
  17. */
  18. class Request
  19. {
  20. /**
  21. * MIME type for JSON
  22. *
  23. * @const string
  24. */
  25. const MIME_JSON = 'application/json';
  26. /**
  27. * MIME type for HTML
  28. *
  29. * @const string
  30. */
  31. const MIME_HTML = 'text/html';
  32. /**
  33. * MIME type for XHTML
  34. *
  35. * @const string
  36. */
  37. const MIME_XHTML = 'application/xhtml+xml';
  38. /**
  39. * Input stream to use for PUT parameter parsing
  40. *
  41. * @access private
  42. * @var string
  43. */
  44. private static $_inputStream = 'php://input';
  45. /**
  46. * Operation to perform
  47. *
  48. * @access private
  49. * @var string
  50. */
  51. private $_operation = 'view';
  52. /**
  53. * Request parameters
  54. *
  55. * @access private
  56. * @var array
  57. */
  58. private $_params = array();
  59. /**
  60. * If we are in a JSON API context
  61. *
  62. * @access private
  63. * @var bool
  64. */
  65. private $_isJsonApi = false;
  66. /**
  67. * Return the paste ID of the current paste.
  68. *
  69. * @access private
  70. * @return string
  71. */
  72. private function getPasteId()
  73. {
  74. foreach ($_GET as $key => $value) {
  75. // only return if value is empty and key is 16 hex chars
  76. if (($value === '') && strlen($key) === 16 && ctype_xdigit($key)) {
  77. return $key;
  78. }
  79. }
  80. return 'invalid id';
  81. }
  82. /**
  83. * Constructor
  84. *
  85. * @access public
  86. */
  87. public function __construct()
  88. {
  89. // decide if we are in JSON API or HTML context
  90. $this->_isJsonApi = $this->_detectJsonRequest();
  91. // parse parameters, depending on request type
  92. switch (array_key_exists('REQUEST_METHOD', $_SERVER) ? $_SERVER['REQUEST_METHOD'] : 'GET') {
  93. case 'DELETE':
  94. case 'PUT':
  95. case 'POST':
  96. // it might be a creation or a deletion, the latter is detected below
  97. $this->_operation = 'create';
  98. try {
  99. $this->_params = Json::decode(
  100. file_get_contents(self::$_inputStream)
  101. );
  102. } catch (Exception $e) {
  103. // ignore error, $this->_params will remain empty
  104. }
  105. break;
  106. default:
  107. $this->_params = filter_var_array($_GET, array(
  108. 'deletetoken' => FILTER_SANITIZE_SPECIAL_CHARS,
  109. 'jsonld' => FILTER_SANITIZE_SPECIAL_CHARS,
  110. 'link' => FILTER_SANITIZE_URL,
  111. 'pasteid' => FILTER_SANITIZE_SPECIAL_CHARS,
  112. 'shortenviayourls' => FILTER_SANITIZE_SPECIAL_CHARS,
  113. ), false);
  114. }
  115. if (
  116. !array_key_exists('pasteid', $this->_params) &&
  117. !array_key_exists('jsonld', $this->_params) &&
  118. !array_key_exists('link', $this->_params) &&
  119. array_key_exists('QUERY_STRING', $_SERVER) &&
  120. !empty($_SERVER['QUERY_STRING'])
  121. ) {
  122. $this->_params['pasteid'] = $this->getPasteId();
  123. }
  124. // prepare operation, depending on current parameters
  125. if (array_key_exists('pasteid', $this->_params) && !empty($this->_params['pasteid'])) {
  126. if (array_key_exists('deletetoken', $this->_params) && !empty($this->_params['deletetoken'])) {
  127. $this->_operation = 'delete';
  128. } elseif ($this->_operation != 'create') {
  129. $this->_operation = 'read';
  130. }
  131. } elseif (array_key_exists('jsonld', $this->_params) && !empty($this->_params['jsonld'])) {
  132. $this->_operation = 'jsonld';
  133. } elseif (array_key_exists('link', $this->_params) && !empty($this->_params['link'])) {
  134. if (strpos($this->getRequestUri(), '/shortenviayourls') !== false || array_key_exists('shortenviayourls', $this->_params)) {
  135. $this->_operation = 'yourlsproxy';
  136. }
  137. }
  138. }
  139. /**
  140. * Get current operation
  141. *
  142. * @access public
  143. * @return string
  144. */
  145. public function getOperation()
  146. {
  147. return $this->_operation;
  148. }
  149. /**
  150. * Get data of paste or comment
  151. *
  152. * @access public
  153. * @return array
  154. */
  155. public function getData()
  156. {
  157. $data = array(
  158. 'adata' => $this->getParam('adata'),
  159. );
  160. $required_keys = array('v', 'ct');
  161. $meta = $this->getParam('meta');
  162. if (empty($meta)) {
  163. $required_keys[] = 'pasteid';
  164. $required_keys[] = 'parentid';
  165. } else {
  166. $data['meta'] = $meta;
  167. }
  168. foreach ($required_keys as $key) {
  169. $data[$key] = $this->getParam($key, $key == 'v' ? 1 : '');
  170. }
  171. // forcing a cast to int or float
  172. $data['v'] = $data['v'] + 0;
  173. return $data;
  174. }
  175. /**
  176. * Get a request parameter
  177. *
  178. * @access public
  179. * @param string $param
  180. * @param string $default
  181. * @return string
  182. */
  183. public function getParam($param, $default = '')
  184. {
  185. return array_key_exists($param, $this->_params) ?
  186. $this->_params[$param] : $default;
  187. }
  188. /**
  189. * Get host as requested by the client
  190. *
  191. * @access public
  192. * @return string
  193. */
  194. public function getHost()
  195. {
  196. $host = array_key_exists('HTTP_HOST', $_SERVER) ? filter_var($_SERVER['HTTP_HOST'], FILTER_SANITIZE_URL) : '';
  197. return empty($host) ? 'localhost' : $host;
  198. }
  199. /**
  200. * Get request URI
  201. *
  202. * @access public
  203. * @return string
  204. */
  205. public function getRequestUri()
  206. {
  207. $uri = array_key_exists('REQUEST_URI', $_SERVER) ? filter_var($_SERVER['REQUEST_URI'], FILTER_SANITIZE_URL) : '';
  208. return empty($uri) ? '/' : $uri;
  209. }
  210. /**
  211. * If we are in a JSON API context
  212. *
  213. * @access public
  214. * @return bool
  215. */
  216. public function isJsonApiCall()
  217. {
  218. return $this->_isJsonApi;
  219. }
  220. /**
  221. * Override the default input stream source, used for unit testing
  222. *
  223. * @param string $input
  224. */
  225. public static function setInputStream($input)
  226. {
  227. self::$_inputStream = $input;
  228. }
  229. /**
  230. * Detect the clients supported media type and decide if its a JSON API call or not
  231. *
  232. * Adapted from: https://stackoverflow.com/questions/3770513/detect-browser-language-in-php#3771447
  233. *
  234. * @access private
  235. * @return bool
  236. */
  237. private function _detectJsonRequest()
  238. {
  239. $hasAcceptHeader = array_key_exists('HTTP_ACCEPT', $_SERVER);
  240. $acceptHeader = $hasAcceptHeader ? $_SERVER['HTTP_ACCEPT'] : '';
  241. // simple cases
  242. if (
  243. (array_key_exists('HTTP_X_REQUESTED_WITH', $_SERVER) &&
  244. $_SERVER['HTTP_X_REQUESTED_WITH'] == 'JSONHttpRequest') ||
  245. ($hasAcceptHeader &&
  246. strpos($acceptHeader, self::MIME_JSON) !== false &&
  247. strpos($acceptHeader, self::MIME_HTML) === false &&
  248. strpos($acceptHeader, self::MIME_XHTML) === false)
  249. ) {
  250. return true;
  251. }
  252. // advanced case: media type negotiation
  253. if ($hasAcceptHeader) {
  254. $mediaTypes = array();
  255. foreach (explode(',', trim($acceptHeader)) as $mediaTypeRange) {
  256. if (preg_match(
  257. '#(\*/\*|[a-z\-]+/[a-z\-+*]+(?:\s*;\s*[^q]\S*)*)(?:\s*;\s*q\s*=\s*(0(?:\.\d{0,3})|1(?:\.0{0,3})))?#',
  258. trim($mediaTypeRange), $match
  259. )) {
  260. if (!isset($match[2])) {
  261. $match[2] = '1.0';
  262. } else {
  263. $match[2] = (string) floatval($match[2]);
  264. if ($match[2] === '0.0') {
  265. continue;
  266. }
  267. }
  268. if (!isset($mediaTypes[$match[2]])) {
  269. $mediaTypes[$match[2]] = array();
  270. }
  271. $mediaTypes[$match[2]][] = strtolower($match[1]);
  272. }
  273. }
  274. krsort($mediaTypes);
  275. foreach ($mediaTypes as $acceptedQuality => $acceptedValues) {
  276. foreach ($acceptedValues as $acceptedValue) {
  277. if (
  278. strpos($acceptedValue, self::MIME_HTML) === 0 ||
  279. strpos($acceptedValue, self::MIME_XHTML) === 0
  280. ) {
  281. return false;
  282. } elseif (strpos($acceptedValue, self::MIME_JSON) === 0) {
  283. return true;
  284. }
  285. }
  286. }
  287. }
  288. return false;
  289. }
  290. }