MongoGridFS.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. <?php
  2. /*
  3. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  4. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  5. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  6. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  7. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  8. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  9. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  10. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  11. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  12. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  13. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  14. */
  15. class MongoGridFS extends MongoCollection
  16. {
  17. const DEFAULT_CHUNK_SIZE = 262144; // 256 kb
  18. const ASCENDING = 1;
  19. const DESCENDING = -1;
  20. /**
  21. * @link http://php.net/manual/en/class.mongogridfs.php#mongogridfs.props.chunks
  22. * @var $chunks MongoCollection
  23. */
  24. public $chunks;
  25. /**
  26. * @link http://php.net/manual/en/class.mongogridfs.php#mongogridfs.props.filesname
  27. * @var $filesName string
  28. */
  29. protected $filesName;
  30. /**
  31. * @link http://php.net/manual/en/class.mongogridfs.php#mongogridfs.props.chunksname
  32. * @var $chunksName string
  33. */
  34. protected $chunksName;
  35. /**
  36. * @var MongoDB
  37. */
  38. private $database;
  39. private $prefix;
  40. /**
  41. * Files as stored across two collections, the first containing file meta
  42. * information, the second containing chunks of the actual file. By default,
  43. * fs.files and fs.chunks are the collection names used.
  44. *
  45. * @link http://php.net/manual/en/mongogridfs.construct.php
  46. * @param MongoDB $db Database
  47. * @param string $prefix [optional] <p>Optional collection name prefix.</p>
  48. * @param mixed $chunks [optional]
  49. * @return MongoGridFS
  50. * @throws \Exception
  51. */
  52. public function __construct(MongoDB $db, $prefix = "fs", $chunks = null)
  53. {
  54. if ($chunks) {
  55. trigger_error("The 'chunks' argument is deprecated and ignored", E_DEPRECATED);
  56. }
  57. if (empty($prefix)) {
  58. throw new \Exception('MongoGridFS::__construct(): invalid prefix');
  59. }
  60. $this->database = $db;
  61. $this->prefix = $prefix;
  62. $this->filesName = $prefix . '.files';
  63. $this->chunksName = $prefix . '.chunks';
  64. $this->chunks = $db->selectCollection($this->chunksName);
  65. parent::__construct($db, $this->filesName);
  66. }
  67. /**
  68. * Delete a file from the database
  69. *
  70. * @link http://php.net/manual/en/mongogridfs.delete.php
  71. * @param mixed $id _id of the file to remove
  72. * @return boolean Returns true if the remove was successfully sent to the database.
  73. */
  74. public function delete($id)
  75. {
  76. $this->createChunksIndex();
  77. $this->chunks->remove(['files_id' => $id], ['justOne' => false]);
  78. return parent::remove(['_id' => $id]);
  79. }
  80. /**
  81. * Drops the files and chunks collections
  82. * @link http://php.net/manual/en/mongogridfs.drop.php
  83. * @return array The database response
  84. */
  85. public function drop()
  86. {
  87. $this->chunks->drop();
  88. return parent::drop();
  89. }
  90. /**
  91. * @link http://php.net/manual/en/mongogridfs.find.php
  92. * @param array $query The query
  93. * @param array $fields Fields to return
  94. * @param array $options Options for the find command
  95. * @return MongoGridFSCursor A MongoGridFSCursor
  96. */
  97. public function find(array $query = [], array $fields = [])
  98. {
  99. $cursor = new MongoGridFSCursor($this, $this->db->getConnection(), (string) $this, $query, $fields);
  100. $cursor->setReadPreference($this->getReadPreference());
  101. return $cursor;
  102. }
  103. /**
  104. * Returns a single file matching the criteria
  105. *
  106. * @link http://www.php.net/manual/en/mongogridfs.findone.php
  107. * @param array $query The fields for which to search.
  108. * @param array $fields Fields of the results to return.
  109. * @param array $options Options for the find command
  110. * @return MongoGridFSFile|null
  111. */
  112. public function findOne(array $query = [], array $fields = [], array $options = [])
  113. {
  114. if (is_string($query)) {
  115. $query = ['filename' => $query];
  116. }
  117. $items = iterator_to_array($this->find($query, $fields)->limit(1));
  118. return current($items);
  119. }
  120. /**
  121. * Retrieve a file from the database
  122. *
  123. * @link http://www.php.net/manual/en/mongogridfs.get.php
  124. * @param mixed $id _id of the file to find.
  125. * @return MongoGridFSFile|null
  126. */
  127. public function get($id)
  128. {
  129. return $this->findOne(['_id' => $id]);
  130. }
  131. /**
  132. * Stores a file in the database
  133. *
  134. * @link http://php.net/manual/en/mongogridfs.put.php
  135. * @param string $filename The name of the file
  136. * @param array $extra Other metadata to add to the file saved
  137. * @param array $options An array of options for the insert operations executed against the chunks and files collections.
  138. * @return mixed Returns the _id of the saved object
  139. */
  140. public function put($filename, array $extra = [], array $options = [])
  141. {
  142. return $this->storeFile($filename, $extra, $options);
  143. }
  144. /**
  145. * Removes files from the collections
  146. *
  147. * @link http://www.php.net/manual/en/mongogridfs.remove.php
  148. * @param array $criteria Description of records to remove.
  149. * @param array $options Options for remove.
  150. * @throws MongoCursorException
  151. * @return boolean
  152. */
  153. public function remove(array $criteria = [], array $options = [])
  154. {
  155. $this->createChunksIndex();
  156. $matchingFiles = parent::find($criteria, ['_id' => 1]);
  157. $ids = [];
  158. foreach ($matchingFiles as $file) {
  159. $ids[] = $file['_id'];
  160. }
  161. $this->chunks->remove(['files_id' => ['$in' => $ids]], ['justOne' => false] + $options);
  162. return parent::remove(['_id' => ['$in' => $ids]], ['justOne' => false] + $options);
  163. }
  164. /**
  165. * Chunkifies and stores bytes in the database
  166. * @link http://php.net/manual/en/mongogridfs.storebytes.php
  167. * @param string $bytes A string of bytes to store
  168. * @param array $extra Other metadata to add to the file saved
  169. * @param array $options Options for the store. "safe": Check that this store succeeded
  170. * @return mixed The _id of the object saved
  171. */
  172. public function storeBytes($bytes, array $extra = [], array $options = [])
  173. {
  174. $this->createChunksIndex();
  175. $record = $extra + [
  176. 'length' => mb_strlen($bytes, '8bit'),
  177. 'md5' => md5($bytes),
  178. ];
  179. try {
  180. $file = $this->insertFile($record, $options);
  181. } catch (MongoException $e) {
  182. throw new MongoGridFSException('Cannot insert file record', 0, $e);
  183. }
  184. try {
  185. $this->insertChunksFromBytes($bytes, $file);
  186. } catch (MongoException $e) {
  187. $this->delete($file['_id']);
  188. throw new MongoGridFSException('Error while inserting chunks', 0, $e);
  189. }
  190. return $file['_id'];
  191. }
  192. /**
  193. * Stores a file in the database
  194. *
  195. * @link http://php.net/manual/en/mongogridfs.storefile.php
  196. * @param string $filename The name of the file
  197. * @param array $extra Other metadata to add to the file saved
  198. * @param array $options Options for the store. "safe": Check that this store succeeded
  199. * @return mixed Returns the _id of the saved object
  200. * @throws MongoGridFSException
  201. * @throws Exception
  202. */
  203. public function storeFile($filename, array $extra = [], array $options = [])
  204. {
  205. $this->createChunksIndex();
  206. $record = $extra;
  207. if (is_string($filename)) {
  208. $record += [
  209. 'md5' => md5_file($filename),
  210. 'length' => filesize($filename),
  211. 'filename' => $filename,
  212. ];
  213. $handle = fopen($filename, 'r');
  214. if (! $handle) {
  215. throw new MongoGridFSException('could not open file: ' . $filename);
  216. }
  217. } elseif (! is_resource($filename)) {
  218. throw new \Exception('first argument must be a string or stream resource');
  219. } else {
  220. $handle = $filename;
  221. }
  222. $md5 = null;
  223. try {
  224. $file = $this->insertFile($record, $options);
  225. } catch (MongoException $e) {
  226. throw new MongoGridFSException('Cannot insert file record', 0, $e);
  227. }
  228. try {
  229. $length = $this->insertChunksFromFile($handle, $file, $md5);
  230. } catch (MongoException $e) {
  231. $this->delete($file['_id']);
  232. throw new MongoGridFSException('Error while inserting chunks', 0, $e);
  233. }
  234. // Add length and MD5 if they were not present before
  235. $update = [];
  236. if (! isset($record['length'])) {
  237. $update['length'] = $length;
  238. }
  239. if (! isset($record['md5'])) {
  240. try {
  241. $update['md5'] = $md5;
  242. } catch (MongoException $e) {
  243. throw new MongoGridFSException('Error computing MD5 checksum', 0, $e);
  244. }
  245. }
  246. if (count($update)) {
  247. try {
  248. $result = $this->update(['_id' => $file['_id']], ['$set' => $update]);
  249. if (! $this->isOKResult($result)) {
  250. throw new MongoGridFSException('Error updating file record');
  251. }
  252. } catch (MongoException $e) {
  253. $this->delete($file['_id']);
  254. throw new MongoGridFSException('Error updating file record', 0, $e);
  255. }
  256. }
  257. return $file['_id'];
  258. }
  259. /**
  260. * Saves an uploaded file directly from a POST to the database
  261. *
  262. * @link http://www.php.net/manual/en/mongogridfs.storeupload.php
  263. * @param string $name The name attribute of the uploaded file, from <input type="file" name="something"/>.
  264. * @param array $metadata An array of extra fields for the uploaded file.
  265. * @return mixed Returns the _id of the uploaded file.
  266. * @throws MongoGridFSException
  267. */
  268. public function storeUpload($name, array $metadata = [])
  269. {
  270. if (! isset($_FILES[$name]) || $_FILES[$name]['error'] !== UPLOAD_ERR_OK) {
  271. throw new MongoGridFSException("Could not find uploaded file $name");
  272. }
  273. if (! isset($_FILES[$name]['tmp_name'])) {
  274. throw new MongoGridFSException("Couldn't find tmp_name in the \$_FILES array. Are you sure the upload worked?");
  275. }
  276. $uploadedFile = $_FILES[$name];
  277. $uploadedFile['tmp_name'] = (array) $uploadedFile['tmp_name'];
  278. $uploadedFile['name'] = (array) $uploadedFile['name'];
  279. if (count($uploadedFile['tmp_name']) > 1) {
  280. foreach ($uploadedFile['tmp_name'] as $key => $file) {
  281. $metadata['filename'] = $uploadedFile['name'][$key];
  282. $this->storeFile($file, $metadata);
  283. }
  284. return null;
  285. } else {
  286. $metadata += ['filename' => array_pop($uploadedFile['name'])];
  287. return $this->storeFile(array_pop($uploadedFile['tmp_name']), $metadata);
  288. }
  289. }
  290. /**
  291. * Creates the index on the chunks collection
  292. */
  293. private function createChunksIndex()
  294. {
  295. try {
  296. $this->chunks->createIndex(['files_id' => 1, 'n' => 1], ['unique' => true]);
  297. } catch (MongoDuplicateKeyException $e) {}
  298. }
  299. /**
  300. * Inserts a single chunk into the database
  301. *
  302. * @param mixed $fileId
  303. * @param string $data
  304. * @param int $chunkNumber
  305. * @return array|bool
  306. */
  307. private function insertChunk($fileId, $data, $chunkNumber)
  308. {
  309. $chunk = [
  310. 'files_id' => $fileId,
  311. 'n' => $chunkNumber,
  312. 'data' => new MongoBinData($data),
  313. ];
  314. $result = $this->chunks->insert($chunk);
  315. if (! $this->isOKResult($result)) {
  316. throw new \MongoException('error inserting chunk');
  317. }
  318. return $result;
  319. }
  320. /**
  321. * Splits a string into chunks and writes them to the database
  322. *
  323. * @param string $bytes
  324. * @param array $record
  325. */
  326. private function insertChunksFromBytes($bytes, $record)
  327. {
  328. $chunkSize = $record['chunkSize'];
  329. $fileId = $record['_id'];
  330. $i = 0;
  331. $chunks = str_split($bytes, $chunkSize);
  332. foreach ($chunks as $chunk) {
  333. $this->insertChunk($fileId, $chunk, $i++);
  334. }
  335. }
  336. /**
  337. * Reads chunks from a file and writes them to the database
  338. *
  339. * @param resource $handle
  340. * @param array $record
  341. * @param string $md5
  342. * @return int Returns the number of bytes written to the database
  343. */
  344. private function insertChunksFromFile($handle, $record, &$md5)
  345. {
  346. $written = 0;
  347. $offset = 0;
  348. $i = 0;
  349. $fileId = $record['_id'];
  350. $chunkSize = $record['chunkSize'];
  351. $hash = hash_init('md5');
  352. rewind($handle);
  353. while (! feof($handle)) {
  354. $data = stream_get_contents($handle, $chunkSize);
  355. hash_update($hash, $data);
  356. $this->insertChunk($fileId, $data, $i++);
  357. $written += strlen($data);
  358. $offset += $chunkSize;
  359. }
  360. $md5 = hash_final($hash);
  361. return $written;
  362. }
  363. /**
  364. * Writes a file record to the database
  365. *
  366. * @param $record
  367. * @param array $options
  368. * @return array
  369. */
  370. private function insertFile($record, array $options = [])
  371. {
  372. $record += [
  373. '_id' => new MongoId(),
  374. 'uploadDate' => new MongoDate(),
  375. 'chunkSize' => self::DEFAULT_CHUNK_SIZE,
  376. ];
  377. $result = $this->insert($record, $options);
  378. if (! $this->isOKResult($result)) {
  379. throw new \MongoException('error inserting file');
  380. }
  381. return $record;
  382. }
  383. private function isOKResult($result)
  384. {
  385. return (is_array($result) && $result['ok'] == 1.0) ||
  386. (is_bool($result) && $result);
  387. }
  388. }