MongoGridFS.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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. $file = $this->insertFile($record, $options);
  180. $this->insertChunksFromBytes($bytes, $file);
  181. return $file['_id'];
  182. }
  183. /**
  184. * Stores a file in the database
  185. *
  186. * @link http://php.net/manual/en/mongogridfs.storefile.php
  187. * @param string $filename The name of the file
  188. * @param array $extra Other metadata to add to the file saved
  189. * @param array $options Options for the store. "safe": Check that this store succeeded
  190. * @return mixed Returns the _id of the saved object
  191. * @throws MongoGridFSException
  192. * @throws Exception
  193. */
  194. public function storeFile($filename, array $extra = [], array $options = [])
  195. {
  196. $this->createChunksIndex();
  197. $record = $extra;
  198. if (is_string($filename)) {
  199. $record += [
  200. 'md5' => md5_file($filename),
  201. 'length' => filesize($filename),
  202. 'filename' => $filename,
  203. ];
  204. $handle = fopen($filename, 'r');
  205. if (! $handle) {
  206. throw new MongoGridFSException('could not open file: ' . $filename);
  207. }
  208. } elseif (! is_resource($filename)) {
  209. throw new \Exception('first argument must be a string or stream resource');
  210. } else {
  211. $handle = $filename;
  212. }
  213. $md5 = null;
  214. $file = $this->insertFile($record, $options);
  215. $length = $this->insertChunksFromFile($handle, $file, $md5);
  216. // Add length and MD5 if they were not present before
  217. $update = [];
  218. if (! isset($record['length'])) {
  219. $update['length'] = $length;
  220. }
  221. if (! isset($record['md5'])) {
  222. $update['md5'] = $md5;
  223. }
  224. if (count($update)) {
  225. $this->update(['_id' => $file['_id']], ['$set' => $update]);
  226. }
  227. return $file['_id'];
  228. }
  229. /**
  230. * Saves an uploaded file directly from a POST to the database
  231. *
  232. * @link http://www.php.net/manual/en/mongogridfs.storeupload.php
  233. * @param string $name The name attribute of the uploaded file, from <input type="file" name="something"/>.
  234. * @param array $metadata An array of extra fields for the uploaded file.
  235. * @return mixed Returns the _id of the uploaded file.
  236. * @throws MongoGridFSException
  237. */
  238. public function storeUpload($name, array $metadata = [])
  239. {
  240. if (! isset($_FILES[$name]) || $_FILES[$name]['error'] !== UPLOAD_ERR_OK) {
  241. throw new MongoGridFSException("Could not find uploaded file $name");
  242. }
  243. if (! isset($_FILES[$name]['tmp_name'])) {
  244. throw new MongoGridFSException("Couldn't find tmp_name in the \$_FILES array. Are you sure the upload worked?");
  245. }
  246. $uploadedFile = $_FILES[$name];
  247. $uploadedFile['tmp_name'] = (array) $uploadedFile['tmp_name'];
  248. $uploadedFile['name'] = (array) $uploadedFile['name'];
  249. if (count($uploadedFile['tmp_name']) > 1) {
  250. foreach ($uploadedFile['tmp_name'] as $key => $file) {
  251. $metadata['filename'] = $uploadedFile['name'][$key];
  252. $this->storeFile($file, $metadata);
  253. }
  254. return null;
  255. } else {
  256. $metadata += ['filename' => array_pop($uploadedFile['name'])];
  257. return $this->storeFile(array_pop($uploadedFile['tmp_name']), $metadata);
  258. }
  259. }
  260. /**
  261. * Creates the index on the chunks collection
  262. */
  263. private function createChunksIndex()
  264. {
  265. $this->chunks->createIndex(['files_id' => 1, 'n' => 1], ['unique' => true]);
  266. }
  267. /**
  268. * Inserts a single chunk into the database
  269. *
  270. * @param mixed $fileId
  271. * @param string $data
  272. * @param int $chunkNumber
  273. * @return array|bool
  274. */
  275. private function insertChunk($fileId, $data, $chunkNumber)
  276. {
  277. $chunk = [
  278. 'files_id' => $fileId,
  279. 'n' => $chunkNumber,
  280. 'data' => new MongoBinData($data),
  281. ];
  282. return $this->chunks->insert($chunk);
  283. }
  284. /**
  285. * Splits a string into chunks and writes them to the database
  286. *
  287. * @param string $bytes
  288. * @param array $record
  289. */
  290. private function insertChunksFromBytes($bytes, $record)
  291. {
  292. $chunkSize = $record['chunkSize'];
  293. $fileId = $record['_id'];
  294. $i = 0;
  295. $chunks = str_split($bytes, $chunkSize);
  296. foreach ($chunks as $chunk) {
  297. $this->insertChunk($fileId, $chunk, $i++);
  298. }
  299. }
  300. /**
  301. * Reads chunks from a file and writes them to the database
  302. *
  303. * @param resource $handle
  304. * @param array $record
  305. * @param string $md5
  306. * @return int Returns the number of bytes written to the database
  307. */
  308. private function insertChunksFromFile($handle, $record, &$md5)
  309. {
  310. $written = 0;
  311. $offset = 0;
  312. $i = 0;
  313. $fileId = $record['_id'];
  314. $chunkSize = $record['chunkSize'];
  315. $hash = hash_init('md5');
  316. rewind($handle);
  317. while (! feof($handle)) {
  318. $data = stream_get_contents($handle, $chunkSize);
  319. hash_update($hash, $data);
  320. $this->insertChunk($fileId, $data, $i++);
  321. $written += strlen($data);
  322. $offset += $chunkSize;
  323. }
  324. $md5 = hash_final($hash);
  325. return $written;
  326. }
  327. /**
  328. * Writes a file record to the database
  329. *
  330. * @param $record
  331. * @param array $options
  332. * @return array
  333. */
  334. private function insertFile($record, array $options = [])
  335. {
  336. $record += [
  337. '_id' => new MongoId(),
  338. 'uploadDate' => new MongoDate(),
  339. 'chunkSize' => self::DEFAULT_CHUNK_SIZE,
  340. ];
  341. $this->insert($record, $options);
  342. return $record;
  343. }
  344. }