ShlinkProxy.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. /**
  13. * ShlinkProxy
  14. *
  15. * Forwards a URL for shortening to shlink and stores the result.
  16. */
  17. class ShlinkProxy extends AbstractProxy
  18. {
  19. /**
  20. * constructor
  21. *
  22. * initializes and runs ShlinkProxy
  23. *
  24. * @access public
  25. * @param string $link
  26. */
  27. public function __construct(Configuration $conf, $link)
  28. {
  29. parent::__construct($conf, $link);
  30. }
  31. /**
  32. * Overrides the abstract parent function to get contents from Shlink API.
  33. *
  34. * @access protected
  35. * @return string
  36. */
  37. protected function _getcontents(Configuration $conf, string $link)
  38. {
  39. $shlink_api_url = $conf->getKey('apiurl', 'shlink');
  40. $shlink_api_key = $conf->getKey('apikey', 'shlink');
  41. if (empty($shlink_api_url) || empty($shlink_api_key)) {
  42. return;
  43. }
  44. $body = array(
  45. 'longUrl' => $link,
  46. );
  47. return file_get_contents(
  48. $shlink_api_url, false, stream_context_create(
  49. array(
  50. 'http' => array(
  51. 'method' => 'POST',
  52. 'header' => "Content-Type: application/json\r\n" .
  53. 'X-Api-Key: ' . $shlink_api_key . "\r\n",
  54. 'content' => Json::encode($body),
  55. ),
  56. )
  57. )
  58. );
  59. }
  60. /**
  61. * Extracts the short URL from the shlink API response.
  62. *
  63. * @access protected
  64. * @param array $data
  65. * @return ?string
  66. */
  67. protected function _extractShortUrl(array $data): ?string
  68. {
  69. if (
  70. !is_null($data) &&
  71. array_key_exists('shortUrl', $data)
  72. ) {
  73. return $data['shortUrl'];
  74. }
  75. return null;
  76. }
  77. }