YourlsProxy.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. * YourlsProxy
  14. *
  15. * Forwards a URL for shortening to YOURLS (your own URL shortener) and stores
  16. * the result.
  17. */
  18. class YourlsProxy extends AbstractProxy
  19. {
  20. /**
  21. * constructor
  22. *
  23. * initializes and runs YourlsProxy
  24. *
  25. * @access public
  26. * @param string $link
  27. */
  28. public function __construct(Configuration $conf, $link)
  29. {
  30. parent::__construct($conf, $link);
  31. }
  32. /**
  33. * Overrides the abstract parent function to get contents from YOURLS API.
  34. *
  35. * @access protected
  36. * @return string
  37. */
  38. protected function _getcontents(Configuration $conf, string $link)
  39. {
  40. $yourls_api_url = $conf->getKey('apiurl', 'yourls');
  41. if (empty($yourls_api_url)) {
  42. return null;
  43. }
  44. return file_get_contents(
  45. $yourls_api_url, false, stream_context_create(
  46. array(
  47. 'http' => array(
  48. 'method' => 'POST',
  49. 'header' => "Content-Type: application/x-www-form-urlencoded\r\n",
  50. 'content' => http_build_query(
  51. array(
  52. 'signature' => $conf->getKey('signature', 'yourls'),
  53. 'format' => 'json',
  54. 'action' => 'shorturl',
  55. 'url' => $link,
  56. )
  57. ),
  58. ),
  59. )
  60. )
  61. );
  62. }
  63. /**
  64. * Extracts the short URL from the YOURLS API response.
  65. *
  66. * @access protected
  67. * @param array $data
  68. * @return ?string
  69. */
  70. protected function _extractShortUrl(array $data): ?string
  71. {
  72. if (
  73. !is_null($data) &&
  74. array_key_exists('statusCode', $data) &&
  75. $data['statusCode'] == 200 &&
  76. array_key_exists('shorturl', $data)
  77. ) {
  78. return $data['shorturl'];
  79. }
  80. return null;
  81. }
  82. }