GoogleCloudStorage.php 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. <?php
  2. namespace PrivateBin\Data;
  3. use Exception;
  4. use Google\Cloud\Core\Exception\NotFoundException;
  5. use Google\Cloud\Storage\StorageClient;
  6. use PrivateBin\Json;
  7. class GoogleCloudStorage extends AbstractData
  8. {
  9. /**
  10. * returns a Google Cloud Storage data backend.
  11. *
  12. * @access public
  13. * @static
  14. * @param array $options
  15. * @return GoogleCloudStorage
  16. */
  17. public static function getInstance(array $options)
  18. {
  19. $bucket = null;
  20. $prefix = 'pastes';
  21. if (getenv('PRIVATEBIN_GCS_BUCKET')) {
  22. $bucket = getenv('PRIVATEBIN_GCS_BUCKET');
  23. }
  24. if (is_array($options) && array_key_exists('bucket', $options)) {
  25. $bucket = $options['bucket'];
  26. }
  27. if (is_array($options) && array_key_exists('prefix', $options)) {
  28. $prefix = $options['prefix'];
  29. }
  30. if (!(self::$_instance instanceof self)) {
  31. self::$_instance = new self($bucket, $prefix);
  32. }
  33. return self::$_instance;
  34. }
  35. protected $_client = null;
  36. protected $_bucket = null;
  37. protected $_prefix = 'pastes';
  38. public function __construct($bucket, $prefix)
  39. {
  40. parent::__construct();
  41. $this->_client = class_exists('StorageClientStub', false) ?
  42. new \StorageClientStub(array()) :
  43. new StorageClient(array('suppressKeyFileNotice' => true));
  44. $this->_bucket = $this->_client->bucket($bucket);
  45. if ($prefix != null) {
  46. $this->_prefix = $prefix;
  47. }
  48. }
  49. /**
  50. * returns the google storage object key for $pasteid in $this->_bucket.
  51. * @param $pasteid string to get the key for
  52. * @return string
  53. */
  54. private function _getKey($pasteid)
  55. {
  56. if ($this->_prefix != '') {
  57. return $this->_prefix . '/' . $pasteid;
  58. }
  59. return $pasteid;
  60. }
  61. /**
  62. * Uploads the payload in the $this->_bucket under the specified key.
  63. * The entire payload is stored as a JSON document. The metadata is replicated
  64. * as the GCS object's metadata except for the fields attachment, attachmentname
  65. * and salt.
  66. *
  67. * @param $key string to store the payload under
  68. * @param $payload array to store
  69. * @return bool true if successful, otherwise false.
  70. */
  71. private function upload($key, $payload)
  72. {
  73. $metadata = array_key_exists('meta', $payload) ? $payload['meta'] : array();
  74. unset($metadata['attachment'], $metadata['attachmentname'], $metadata['salt']);
  75. foreach ($metadata as $k => $v) {
  76. $metadata[$k] = strval($v);
  77. }
  78. try {
  79. $this->_bucket->upload(Json::encode($payload), array(
  80. 'name' => $key,
  81. 'chunkSize' => 262144,
  82. 'predefinedAcl' => 'private',
  83. 'metadata' => array(
  84. 'content-type' => 'application/json',
  85. 'metadata' => $metadata,
  86. ),
  87. ));
  88. } catch (Exception $e) {
  89. error_log('failed to upload ' . $key . ' to ' . $this->_bucket->name() . ', ' .
  90. trim(preg_replace('/\s\s+/', ' ', $e->getMessage())));
  91. return false;
  92. }
  93. return true;
  94. }
  95. /**
  96. * @inheritDoc
  97. */
  98. public function create($pasteid, array $paste)
  99. {
  100. if ($this->exists($pasteid)) {
  101. return false;
  102. }
  103. return $this->upload($this->_getKey($pasteid), $paste);
  104. }
  105. /**
  106. * @inheritDoc
  107. */
  108. public function read($pasteid)
  109. {
  110. try {
  111. $o = $this->_bucket->object($this->_getKey($pasteid));
  112. $data = $o->downloadAsString();
  113. return Json::decode($data);
  114. } catch (NotFoundException $e) {
  115. return false;
  116. } catch (Exception $e) {
  117. error_log('failed to read ' . $pasteid . ' from ' . $this->_bucket->name() . ', ' .
  118. trim(preg_replace('/\s\s+/', ' ', $e->getMessage())));
  119. return false;
  120. }
  121. }
  122. /**
  123. * @inheritDoc
  124. */
  125. public function delete($pasteid)
  126. {
  127. $name = $this->_getKey($pasteid);
  128. try {
  129. foreach ($this->_bucket->objects(array('prefix' => $name . '/discussion/')) as $comment) {
  130. try {
  131. $this->_bucket->object($comment->name())->delete();
  132. } catch (NotFoundException $e) {
  133. // ignore if already deleted.
  134. }
  135. }
  136. } catch (NotFoundException $e) {
  137. // there are no discussions associated with the paste
  138. }
  139. try {
  140. $this->_bucket->object($name)->delete();
  141. } catch (NotFoundException $e) {
  142. // ignore if already deleted
  143. }
  144. }
  145. /**
  146. * @inheritDoc
  147. */
  148. public function exists($pasteid)
  149. {
  150. $o = $this->_bucket->object($this->_getKey($pasteid));
  151. return $o->exists();
  152. }
  153. /**
  154. * @inheritDoc
  155. */
  156. public function createComment($pasteid, $parentid, $commentid, array $comment)
  157. {
  158. if ($this->existsComment($pasteid, $parentid, $commentid)) {
  159. return false;
  160. }
  161. $key = $this->_getKey($pasteid) . '/discussion/' . $parentid . '/' . $commentid;
  162. return $this->upload($key, $comment);
  163. }
  164. /**
  165. * @inheritDoc
  166. */
  167. public function readComments($pasteid)
  168. {
  169. $comments = array();
  170. $prefix = $this->_getKey($pasteid) . '/discussion/';
  171. try {
  172. foreach ($this->_bucket->objects(array('prefix' => $prefix)) as $key) {
  173. $comment = JSON::decode($this->_bucket->object($key->name())->downloadAsString());
  174. $comment['id'] = basename($key->name());
  175. $slot = $this->getOpenSlot($comments, (int) $comment['meta']['created']);
  176. $comments[$slot] = $comment;
  177. }
  178. } catch (NotFoundException $e) {
  179. // no comments found
  180. }
  181. return $comments;
  182. }
  183. /**
  184. * @inheritDoc
  185. */
  186. public function existsComment($pasteid, $parentid, $commentid)
  187. {
  188. $name = $this->_getKey($pasteid) . '/discussion/' . $parentid . '/' . $commentid;
  189. $o = $this->_bucket->object($name);
  190. return $o->exists();
  191. }
  192. /**
  193. * @inheritDoc
  194. */
  195. public function purgeValues($namespace, $time)
  196. {
  197. $path = 'config/' . $namespace;
  198. try {
  199. foreach ($this->_bucket->objects(array('prefix' => $path)) as $object) {
  200. $name = $object->name();
  201. if (strlen($name) > strlen($path) && substr($name, strlen($path), 1) !== '/') {
  202. continue;
  203. }
  204. $info = $object->info();
  205. if (key_exists('metadata', $info) && key_exists('value', $info['metadata'])) {
  206. $value = $info['metadata']['value'];
  207. if (is_numeric($value) && intval($value) < $time) {
  208. try {
  209. $object->delete();
  210. } catch (NotFoundException $e) {
  211. // deleted by another instance.
  212. }
  213. }
  214. }
  215. }
  216. } catch (NotFoundException $e) {
  217. // no objects in the bucket yet
  218. }
  219. }
  220. /**
  221. * For GoogleCloudStorage, the value will also be stored in the metadata for the
  222. * namespaces traffic_limiter and purge_limiter.
  223. * @inheritDoc
  224. */
  225. public function setValue($value, $namespace, $key = '')
  226. {
  227. if ($key === '') {
  228. $key = 'config/' . $namespace;
  229. } else {
  230. $key = 'config/' . $namespace . '/' . $key;
  231. }
  232. $metadata = array('namespace' => $namespace);
  233. if ($namespace != 'salt') {
  234. $metadata['value'] = strval($value);
  235. }
  236. try {
  237. $this->_bucket->upload($value, array(
  238. 'name' => $key,
  239. 'chunkSize' => 262144,
  240. 'predefinedAcl' => 'private',
  241. 'metadata' => array(
  242. 'content-type' => 'application/json',
  243. 'metadata' => $metadata,
  244. ),
  245. ));
  246. } catch (Exception $e) {
  247. error_log('failed to set key ' . $key . ' to ' . $this->_bucket->name() . ', ' .
  248. trim(preg_replace('/\s\s+/', ' ', $e->getMessage())));
  249. return false;
  250. }
  251. return true;
  252. }
  253. /**
  254. * @inheritDoc
  255. */
  256. public function getValue($namespace, $key = '')
  257. {
  258. if ($key === '') {
  259. $key = 'config/' . $namespace;
  260. } else {
  261. $key = 'config/' . $namespace . '/' . $key;
  262. }
  263. try {
  264. $o = $this->_bucket->object($key);
  265. return $o->downloadAsString();
  266. } catch (NotFoundException $e) {
  267. return '';
  268. }
  269. }
  270. /**
  271. * @inheritDoc
  272. */
  273. protected function _getExpiredPastes($batchsize)
  274. {
  275. $expired = array();
  276. $now = time();
  277. $prefix = $this->_prefix;
  278. if ($prefix != '') {
  279. $prefix = $prefix . '/';
  280. }
  281. try {
  282. foreach ($this->_bucket->objects(array('prefix' => $prefix)) as $object) {
  283. $metadata = $object->info()['metadata'];
  284. if ($metadata != null && array_key_exists('expire_date', $metadata)) {
  285. $expire_at = intval($metadata['expire_date']);
  286. if ($expire_at != 0 && $expire_at < $now) {
  287. array_push($expired, basename($object->name()));
  288. }
  289. }
  290. if (count($expired) > $batchsize) {
  291. break;
  292. }
  293. }
  294. } catch (NotFoundException $e) {
  295. // no objects in the bucket yet
  296. }
  297. return $expired;
  298. }
  299. }