1
0

Request.php 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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 PrivateBin\Exception\JsonException;
  13. use PrivateBin\Model\Paste;
  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 = [];
  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 document.
  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. $key = (string) $key;
  78. if (empty($value) && Paste::isValidId($key)) {
  79. return $key;
  80. }
  81. }
  82. return 'invalid id';
  83. }
  84. /**
  85. * Constructor
  86. *
  87. * @access public
  88. */
  89. public function __construct()
  90. {
  91. // decide if we are in JSON API or HTML context
  92. $this->_isJsonApi = $this->_detectJsonRequest();
  93. // parse parameters, depending on request type
  94. switch ($_SERVER['REQUEST_METHOD'] ?? 'GET') {
  95. case 'DELETE':
  96. case 'PUT':
  97. case 'POST':
  98. // it might be a creation or a deletion, the latter is detected below
  99. $this->_operation = 'create';
  100. try {
  101. $data = file_get_contents(self::$_inputStream);
  102. $this->_params = Json::decode($data);
  103. } catch (JsonException $e) {
  104. // ignore error, $this->_params will remain empty
  105. }
  106. break;
  107. default:
  108. $this->_params = filter_var_array($_GET, [
  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. 'shortenviashlink' => FILTER_SANITIZE_SPECIAL_CHARS,
  115. ], false);
  116. }
  117. if (
  118. !array_key_exists('pasteid', $this->_params) &&
  119. !array_key_exists('jsonld', $this->_params) &&
  120. !array_key_exists('link', $this->_params) &&
  121. array_key_exists('QUERY_STRING', $_SERVER) &&
  122. !empty($_SERVER['QUERY_STRING'])
  123. ) {
  124. $this->_params['pasteid'] = $this->getPasteId();
  125. }
  126. // prepare operation, depending on current parameters
  127. if (array_key_exists('pasteid', $this->_params) && !empty($this->_params['pasteid'])) {
  128. if (array_key_exists('deletetoken', $this->_params) && !empty($this->_params['deletetoken'])) {
  129. $this->_operation = 'delete';
  130. } elseif ($this->_operation !== 'create') {
  131. $this->_operation = 'read';
  132. }
  133. } elseif (array_key_exists('jsonld', $this->_params) && !empty($this->_params['jsonld'])) {
  134. $this->_operation = 'jsonld';
  135. } elseif (array_key_exists('link', $this->_params) && !empty($this->_params['link'])) {
  136. if (str_contains($this->getRequestUri(), '/shortenviayourls') || array_key_exists('shortenviayourls', $this->_params)) {
  137. $this->_operation = 'yourlsproxy';
  138. }
  139. if (str_contains($this->getRequestUri(), '/shortenviashlink') || array_key_exists('shortenviashlink', $this->_params)) {
  140. $this->_operation = 'shlinkproxy';
  141. }
  142. }
  143. }
  144. /**
  145. * Get current operation
  146. *
  147. * @access public
  148. * @return string
  149. */
  150. public function getOperation()
  151. {
  152. return $this->_operation;
  153. }
  154. /**
  155. * Get data of paste or comment
  156. *
  157. * @access public
  158. * @return array
  159. */
  160. public function getData()
  161. {
  162. $data = [
  163. 'adata' => $this->getParam('adata'),
  164. ];
  165. $required_keys = ['v', 'ct'];
  166. $meta = $this->getParam('meta');
  167. if (empty($meta)) {
  168. $required_keys[] = 'pasteid';
  169. $required_keys[] = 'parentid';
  170. } else {
  171. $data['meta'] = $meta;
  172. }
  173. foreach ($required_keys as $key) {
  174. $data[$key] = $this->getParam($key, $key === 'v' ? 1 : '');
  175. }
  176. // forcing a cast to int or float
  177. $data['v'] = $data['v'] + 0;
  178. return $data;
  179. }
  180. /**
  181. * Get a request parameter
  182. *
  183. * @access public
  184. * @param string $param
  185. * @param string $default
  186. * @return string
  187. */
  188. public function getParam($param, $default = '')
  189. {
  190. return $this->_params[$param] ?? $default;
  191. }
  192. /**
  193. * Get host as requested by the client
  194. *
  195. * @access public
  196. * @return string
  197. */
  198. public function getHost()
  199. {
  200. $host = array_key_exists('HTTP_HOST', $_SERVER) ? filter_var($_SERVER['HTTP_HOST'], FILTER_SANITIZE_URL) : '';
  201. return empty($host) ? 'localhost' : $host;
  202. }
  203. /**
  204. * Get request URI path without GET parameters
  205. *
  206. * @access public
  207. * @return string
  208. */
  209. public function getRequestUri()
  210. {
  211. $uri = array_key_exists('REQUEST_URI', $_SERVER) ? filter_var($_SERVER['REQUEST_URI'], FILTER_SANITIZE_URL) : '';
  212. return empty($uri) ? '/' : parse_url($uri, PHP_URL_PATH);
  213. }
  214. /**
  215. * If we are in a JSON API context
  216. *
  217. * @access public
  218. * @return bool
  219. */
  220. public function isJsonApiCall()
  221. {
  222. return $this->_isJsonApi;
  223. }
  224. /**
  225. * Override the default input stream source, used for unit testing
  226. *
  227. * @param string $input
  228. */
  229. public static function setInputStream($input)
  230. {
  231. self::$_inputStream = $input;
  232. }
  233. /**
  234. * Detect the clients supported media type and decide if its a JSON API call or not
  235. *
  236. * Adapted from: https://stackoverflow.com/questions/3770513/detect-browser-language-in-php#3771447
  237. *
  238. * @access private
  239. * @return bool
  240. */
  241. private function _detectJsonRequest()
  242. {
  243. $acceptHeader = $_SERVER['HTTP_ACCEPT'] ?? '';
  244. // simple cases
  245. if (
  246. ($_SERVER['HTTP_X_REQUESTED_WITH'] ?? '') === 'JSONHttpRequest' ||
  247. (
  248. str_contains($acceptHeader, self::MIME_JSON) &&
  249. !str_contains($acceptHeader, self::MIME_HTML) &&
  250. !str_contains($acceptHeader, self::MIME_XHTML)
  251. )
  252. ) {
  253. return true;
  254. }
  255. // advanced case: media type negotiation
  256. if (!empty($acceptHeader)) {
  257. $mediaTypes = [];
  258. foreach (explode(',', trim($acceptHeader)) as $mediaTypeRange) {
  259. if (preg_match(
  260. '#(\*/\*|[a-z\-]+/[a-z\-+*]+(?:\s*;\s*[^q]\S*)*)(?:\s*;\s*q\s*=\s*(0(?:\.\d{0,3})|1(?:\.0{0,3})))?#',
  261. trim($mediaTypeRange), $match
  262. )) {
  263. if (!isset($match[2])) {
  264. $match[2] = '1.0';
  265. } else {
  266. $match[2] = (string) floatval($match[2]);
  267. if ($match[2] === '0.0') {
  268. continue;
  269. }
  270. }
  271. if (!isset($mediaTypes[$match[2]])) {
  272. $mediaTypes[$match[2]] = [];
  273. }
  274. $mediaTypes[$match[2]][] = strtolower($match[1]);
  275. }
  276. }
  277. krsort($mediaTypes);
  278. foreach ($mediaTypes as $acceptedQuality => $acceptedValues) {
  279. foreach ($acceptedValues as $acceptedValue) {
  280. if (
  281. str_starts_with($acceptedValue, self::MIME_HTML) ||
  282. str_starts_with($acceptedValue, self::MIME_XHTML)
  283. ) {
  284. return false;
  285. } elseif (str_starts_with($acceptedValue, self::MIME_JSON)) {
  286. return true;
  287. }
  288. }
  289. }
  290. }
  291. return false;
  292. }
  293. }