ShlinkProxy.php 2.0 KB

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