requestParser.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. /*
  3. * Serverside PhP script for requesting parsers for DSBDirect
  4. * Copyright (C) 2019 Moritz Zwerger
  5. *
  6. * This program is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU Affero General Public License as
  8. * published by the Free Software Foundation, either version 3 of the
  9. * License, or (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU Affero General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Affero General Public License
  17. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  18. */
  19. //vars
  20. $root = '/users/fynn/parserfiles'; //folder where to save the tables
  21. //max length for url content
  22. $maxFileSize = 200000; //200kb
  23. //check if url argument is passed
  24. if (!isset($_POST['url'])) {
  25. //fail because of malformed request
  26. fail();
  27. }
  28. $url = $_POST['url'];
  29. //check if url is valid url
  30. if (!filter_var($url, FILTER_VALIDATE_URL)) {
  31. //not valid
  32. fail();
  33. }
  34. //check if url is from dsb
  35. if (!startsWith($url, 'https://app.dsbcontrol.de/data/') && !startsWith($url, 'https://light.dsbcontrol.de/DSBlightWebsite/Data/')) {
  36. // url is invalid, we only allow domains from dsb
  37. fail();
  38. }
  39. //check if data folder exists. if not, create it
  40. if (!is_dir($root) && !mkdir($root, 0770, true)) {
  41. //unable to create
  42. fail();
  43. }
  44. $content = file_get_contents($url, false, null, 0, $maxFileSize);
  45. //check if content is available
  46. if ($content === false) {
  47. //error
  48. fail();
  49. }
  50. //set path and generate hash value
  51. $path = $root . '/' . sha1($content) . ".htm";
  52. //check if file already exists
  53. if (file_exists($path)) {
  54. //file already exists. No need to overwrite it.
  55. die("ok");
  56. }
  57. //write to file
  58. $file = fopen($path, "w") or fail(); //open file in write mode. If it fails throw error
  59. fwrite($file, $content); //write
  60. fclose($file); //close file handler
  61. chmod($path, 0770); //change permission
  62. //ok. return
  63. die("ok");
  64. function fail()
  65. {
  66. http_response_code(400);
  67. die('fail');
  68. }
  69. function startsWith($string, $startString)
  70. {
  71. $len = strlen($startString);
  72. return (substr($string, 0, $len) === $startString);
  73. }