MongoGridFS.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  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. $file = $this->insertFile($record, $options);
  214. $length = $this->insertChunksFromFile($handle, $file);
  215. // Add length and MD5 if they were not present before
  216. $update = [];
  217. if (! isset($record['length'])) {
  218. $update['length'] = $length;
  219. }
  220. if (! isset($record['md5'])) {
  221. $update['md5'] = $this->getMd5ForFile($file['_id']);
  222. }
  223. if (count($update)) {
  224. $this->update(['_id' => $file['_id']], ['$set' => $update]);
  225. }
  226. return $file['_id'];
  227. }
  228. /**
  229. * Saves an uploaded file directly from a POST to the database
  230. *
  231. * @link http://www.php.net/manual/en/mongogridfs.storeupload.php
  232. * @param string $name The name attribute of the uploaded file, from <input type="file" name="something"/>.
  233. * @param array $metadata An array of extra fields for the uploaded file.
  234. * @return mixed Returns the _id of the uploaded file.
  235. * @throws MongoGridFSException
  236. */
  237. public function storeUpload($name, array $metadata = [])
  238. {
  239. if (! isset($_FILES[$name]) || $_FILES[$name]['error'] !== UPLOAD_ERR_OK) {
  240. throw new MongoGridFSException("Could not find uploaded file $name");
  241. }
  242. if (! isset($_FILES[$name]['tmp_name'])) {
  243. throw new MongoGridFSException("Couldn't find tmp_name in the \$_FILES array. Are you sure the upload worked?");
  244. }
  245. $uploadedFile = $_FILES[$name];
  246. $uploadedFile['tmp_name'] = (array) $uploadedFile['tmp_name'];
  247. $uploadedFile['name'] = (array) $uploadedFile['name'];
  248. if (count($uploadedFile['tmp_name']) > 1) {
  249. foreach ($uploadedFile['tmp_name'] as $key => $file) {
  250. $metadata['filename'] = $uploadedFile['name'][$key];
  251. $this->storeFile($file, $metadata);
  252. }
  253. return null;
  254. } else {
  255. $metadata += ['filename' => array_pop($uploadedFile['name'])];
  256. return $this->storeFile(array_pop($uploadedFile['tmp_name']), $metadata);
  257. }
  258. }
  259. /**
  260. * Creates the index on the chunks collection
  261. */
  262. private function createChunksIndex()
  263. {
  264. $this->chunks->createIndex(['files_id' => 1, 'n' => 1], ['unique' => true]);
  265. }
  266. /**
  267. * Inserts a single chunk into the database
  268. *
  269. * @param mixed $fileId
  270. * @param string $data
  271. * @param int $chunkNumber
  272. * @return array|bool
  273. */
  274. private function insertChunk($fileId, $data, $chunkNumber)
  275. {
  276. $chunk = [
  277. 'files_id' => $fileId,
  278. 'n' => $chunkNumber,
  279. 'data' => new MongoBinData($data),
  280. ];
  281. return $this->chunks->insert($chunk);
  282. }
  283. /**
  284. * Splits a string into chunks and writes them to the database
  285. *
  286. * @param string $bytes
  287. * @param array $record
  288. */
  289. private function insertChunksFromBytes($bytes, $record)
  290. {
  291. $chunkSize = $record['chunkSize'];
  292. $fileId = $record['_id'];
  293. $i = 0;
  294. $chunks = str_split($bytes, $chunkSize);
  295. foreach ($chunks as $chunk) {
  296. $this->insertChunk($fileId, $chunk, $i++);
  297. }
  298. }
  299. /**
  300. * Reads chunks from a file and writes them to the database
  301. *
  302. * @param resource $handle
  303. * @param array $record
  304. * @return int Returns the number of bytes written to the database
  305. */
  306. private function insertChunksFromFile($handle, $record)
  307. {
  308. $written = 0;
  309. $offset = 0;
  310. $i = 0;
  311. $fileId = $record['_id'];
  312. $chunkSize = $record['chunkSize'];
  313. rewind($handle);
  314. while (! feof($handle)) {
  315. $data = stream_get_contents($handle, $chunkSize);
  316. $this->insertChunk($fileId, $data, $i++);
  317. $written += strlen($data);
  318. $offset += $chunkSize;
  319. }
  320. return $written;
  321. }
  322. /**
  323. * Writes a file record to the database
  324. *
  325. * @param $record
  326. * @param array $options
  327. * @return array
  328. */
  329. private function insertFile($record, array $options = [])
  330. {
  331. $record += [
  332. '_id' => new MongoId(),
  333. 'uploadDate' => new MongoDate(),
  334. 'chunkSize' => self::DEFAULT_CHUNK_SIZE,
  335. ];
  336. $this->insert($record, $options);
  337. return $record;
  338. }
  339. /**
  340. * Returns the MD5 string for a file previously stored to the database
  341. *
  342. * @param $id
  343. * @return string
  344. */
  345. private function getMd5ForFile($id)
  346. {
  347. $result = $this->db->command(['filemd5' => $id, 'root' => $this->prefix]);
  348. return $result['md5'];
  349. }
  350. }