ChhotoProxy.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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 JsonException;
  13. use PrivateBin\Configuration;
  14. use PrivateBin\Json;
  15. /**
  16. * ChhotoProxy
  17. *
  18. * Forwards a URL for shortening to Chhoto URL and stores the result.
  19. */
  20. class ChhotoProxy 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', 'chhoto');
  31. }
  32. /**
  33. * Overrides the abstract parent function to get contents from Chhoto 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. $apiKey = $conf->getKey('apikey', 'chhoto');
  43. $body = [
  44. 'shortlink' => '', // empty = auto-generate
  45. 'longlink' => $link,
  46. 'expiry_delay' => 0, // 0 = never expire
  47. 'notes' => 'PrivateBin paste',
  48. ];
  49. try {
  50. return [
  51. 'method' => 'POST',
  52. 'header' => "Content-Type: application/json\r\n" .
  53. 'X-API-Key: ' . $apiKey . "\r\n" .
  54. "Accept: application/json\r\n",
  55. 'content' => Json::encode($body),
  56. ];
  57. } catch (JsonException $e) {
  58. error_log('[' . get_class($this) . '] Error encoding body: ' . $e->getMessage());
  59. return [];
  60. }
  61. }
  62. /**
  63. * Extracts the short URL from the Chhoto API response.
  64. *
  65. * @access protected
  66. * @param array $data
  67. * @return ?string
  68. */
  69. protected function _extractShortUrl(array $data): ?string
  70. {
  71. // Chhoto usually returns "shorturl"
  72. if (!empty($data['shorturl'])) {
  73. return $data['shorturl'];
  74. }
  75. // Fallback for older versions that return only the slug
  76. if (!empty($data['shortlink'])) {
  77. $apiUrl = $this->_getProxyUrl(new Configuration()); // not ideal, but works
  78. return $apiUrl . ltrim($data['shortlink'], '/');
  79. }
  80. return null;
  81. }
  82. }