GoogleCloudStorage.php 10 KB

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