Request.php 9.0 KB

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