GoogleCloudStorage.php 10 KB

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