GoogleCloudStorage.php 9.9 KB

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