1
0

GoogleCloudStorage.php 11 KB

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