1
0

GoogleCloudStorage.php 9.8 KB

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