MongoGridFS.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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. protected $database;
  39. protected $ensureIndexes = false;
  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. */
  51. public function __construct(MongoDB $db, $prefix = "fs", $chunks = null)
  52. {
  53. if ($chunks) {
  54. trigger_error(E_DEPRECATED, "The 'chunks' argument is deprecated and ignored");
  55. }
  56. if (empty($prefix)) {
  57. throw new \InvalidArgumentException('prefix can not be empty');
  58. }
  59. $this->database = $db;
  60. $this->filesName = $prefix . '.files';
  61. $this->chunksName = $prefix . '.chunks';
  62. $this->chunks = $db->selectCollection($this->chunksName);
  63. parent::__construct($db, $this->filesName);
  64. }
  65. /**
  66. * Drops the files and chunks collections
  67. * @link http://php.net/manual/en/mongogridfs.drop.php
  68. * @return array The database response
  69. */
  70. public function drop()
  71. {
  72. $this->chunks->drop();
  73. parent::drop();
  74. }
  75. /**
  76. * @link http://php.net/manual/en/mongogridfs.find.php
  77. * @param array $query The query
  78. * @param array $fields Fields to return
  79. * @return MongoGridFSCursor A MongoGridFSCursor
  80. */
  81. public function find(array $query = array(), array $fields = array())
  82. {
  83. $cursor = new MongoGridFSCursor($this, $this->db->getConnection(), (string)$this, $query, $fields);
  84. $cursor->setReadPreference($this->getReadPreference());
  85. return $cursor;
  86. }
  87. /**
  88. * Stores a file in the database
  89. * @link http://php.net/manual/en/mongogridfs.storefile.php
  90. * @param string $filename The name of the file
  91. * @param array $extra Other metadata to add to the file saved
  92. * @param array $options Options for the store. "safe": Check that this store succeeded
  93. * @return mixed Returns the _id of the saved object
  94. */
  95. public function storeFile($filename, array $extra = array(), array $options = array())
  96. {
  97. if (is_string($filename)) {
  98. $md5 = md5_file($filename);
  99. $shortName = basename($filename);
  100. $filename = fopen($filename, 'r');
  101. }
  102. if (! is_resource($filename)) {
  103. throw new \InvalidArgumentException();
  104. }
  105. $length = fstat($filename)['size'];
  106. $extra['chunkSize'] = isset($extra['chunkSize']) ? $extra['chunkSize']: self::DEFAULT_CHUNK_SIZE;
  107. $extra['_id'] = isset($extra['_id']) ?: new MongoId();
  108. $extra['length'] = $length;
  109. $extra['md5'] = isset($md5) ? $md5 : $this->calculateMD5($filename);
  110. $extra['filename'] = isset($extra['filename']) ? $extra['filename'] : $shortName;
  111. $fileDocument = $this->insertFile($extra);
  112. $this->insertChunksFromFile($filename, $fileDocument);
  113. return $fileDocument['_id'];
  114. }
  115. /**
  116. * Chunkifies and stores bytes in the database
  117. * @link http://php.net/manual/en/mongogridfs.storebytes.php
  118. * @param string $bytes A string of bytes to store
  119. * @param array $extra Other metadata to add to the file saved
  120. * @param array $options Options for the store. "safe": Check that this store succeeded
  121. * @return mixed The _id of the object saved
  122. */
  123. public function storeBytes($bytes, array $extra = array(), array $options = array())
  124. {
  125. $length = mb_strlen($bytes, '8bit');
  126. $extra['chunkSize'] = isset($extra['chunkSize']) ? $extra['chunkSize'] : self::DEFAULT_CHUNK_SIZE;
  127. $extra['_id'] = isset($extra['_id']) ?: new MongoId();
  128. $extra['length'] = $length;
  129. $extra['md5'] = md5($bytes);
  130. $file = $this->insertFile($extra);
  131. $this->insertChunksFromBytes($bytes, $file);
  132. return $file['_id'];
  133. }
  134. /**
  135. * Returns a single file matching the criteria
  136. * @link http://www.php.net/manual/en/mongogridfs.findone.php
  137. * @param array $query The fields for which to search.
  138. * @param array $fields Fields of the results to return.
  139. * @return MongoGridFSFile|null
  140. */
  141. public function findOne(array $query = [], array $fields = [], array $options = [])
  142. {
  143. $file = parent::findOne($query, $fields);
  144. if (! $file) {
  145. return;
  146. }
  147. return new MongoGridFSFile($this, $file);
  148. }
  149. /**
  150. * Removes files from the collections
  151. * @link http://www.php.net/manual/en/mongogridfs.remove.php
  152. * @param array $criteria Description of records to remove.
  153. * @param array $options Options for remove. Valid options are: "safe"- Check that the remove succeeded.
  154. * @throws MongoCursorException
  155. * @return boolean
  156. */
  157. public function remove(array $criteria = [], array $options = [])
  158. {
  159. $matchingFiles = parent::find($criteria, ['_id' => 1]);
  160. $ids = [];
  161. foreach ($matchingFiles as $file) {
  162. $ids[] = $file['_id'];
  163. }
  164. $this->chunks->remove(['files_id' => ['$in' => $ids]], ['justOne' => false]);
  165. return parent::remove($criteria, ['justOne' => false] + $options);
  166. }
  167. /**
  168. * Delete a file from the database
  169. * @link http://php.net/manual/en/mongogridfs.delete.php
  170. * @param mixed $id _id of the file to remove
  171. * @return boolean Returns true if the remove was successfully sent to the database.
  172. */
  173. public function delete($id)
  174. {
  175. if (is_string($id)) {
  176. $id = new MongoId($id);
  177. }
  178. if (! $id instanceof MongoId) {
  179. return false;
  180. }
  181. $this->chunks->remove(['files_id' => $id], ['justOne' => false]);
  182. return parent::remove(['_id' => $id]);
  183. }
  184. /**
  185. * Saves an uploaded file directly from a POST to the database
  186. * @link http://www.php.net/manual/en/mongogridfs.storeupload.php
  187. * @param string $name The name attribute of the uploaded file, from <input type="file" name="something"/>.
  188. * @param array $metadata An array of extra fields for the uploaded file.
  189. * @return mixed Returns the _id of the uploaded file.
  190. */
  191. public function storeUpload($name, array $metadata = array())
  192. {
  193. if (! isset($_FILES[$name]) || $_FILES[$name]['error'] !== UPLOAD_ERR_OK) {
  194. throw new \InvalidArgumentException();
  195. }
  196. $metadata += ['filename' => $_FILES[$name]['name']];
  197. return $this->storeFile($_FILES[$name]['tmp_name'], $metadata);
  198. }
  199. /**
  200. * Retrieve a file from the database
  201. * @link http://www.php.net/manual/en/mongogridfs.get.php
  202. * @param mixed $id _id of the file to find.
  203. * @return MongoGridFSFile|null Returns the file, if found, or NULL.
  204. */
  205. public function __get($id)
  206. {
  207. if (is_string($id)) {
  208. $id = new MongoId($id);
  209. }
  210. if (! $id instanceof MongoId) {
  211. return false;
  212. }
  213. return $this->findOne(['_id' => $id]);
  214. }
  215. /**
  216. * Stores a file in the database
  217. * @link http://php.net/manual/en/mongogridfs.put.php
  218. * @param string $filename The name of the file
  219. * @param array $extra Other metadata to add to the file saved
  220. * @return mixed Returns the _id of the saved object
  221. */
  222. public function put($filename, array $extra = array())
  223. {
  224. return $this->storeFile($filename, $extra);
  225. }
  226. private function ensureIndexes()
  227. {
  228. if ($this->ensureIndexes) {
  229. return;
  230. }
  231. $this->ensureFilesIndex();
  232. $this->ensureChunksIndex();
  233. $this->ensuredIndexes = true;
  234. }
  235. private function ensureChunksIndex()
  236. {
  237. foreach ($this->chunks->getIndexInfo() as $index) {
  238. if (isset($index['unique']) && $index['unique'] && $index['key'] === ['files_id' => 1, 'n' => 1]) {
  239. return;
  240. }
  241. }
  242. $this->chunks->createIndex(['files_id' => 1, 'n' => 1], ['unique' => true]);
  243. }
  244. private function ensureFilesIndex()
  245. {
  246. foreach ($this->getIndexInfo() as $index) {
  247. if ($index['key'] === ['filename' => 1, 'uploadDate' => 1]) {
  248. return;
  249. }
  250. }
  251. $this->createIndex(['filename' => 1, 'uploadDate' => 1]);
  252. }
  253. private function insertChunksFromFile($file, $fileInfo)
  254. {
  255. $length = $fileInfo['length'];
  256. $chunkSize = $fileInfo['chunkSize'];
  257. $fileId = $fileInfo['_id'];
  258. $offset = 0;
  259. $i = 0;
  260. rewind($file);
  261. while ($offset < $length) {
  262. $data = stream_get_contents($file, $chunkSize);
  263. $this->insertChunk($fileId, $data, $i++);
  264. $offset += $chunkSize;
  265. }
  266. }
  267. private function calculateMD5($file)
  268. {
  269. // XXX: this could be really a bad idea with big files...
  270. rewind($file);
  271. $data = stream_get_contents($file);
  272. return md5($data);
  273. }
  274. private function insertChunksFromBytes($bytes, $fileInfo)
  275. {
  276. $length = $fileInfo['length'];
  277. $chunkSize = $fileInfo['chunkSize'];
  278. $fileId = $fileInfo['_id'];
  279. $i = 0;
  280. $chunks = str_split($bytes, $chunkSize);
  281. foreach ($chunks as $chunk) {
  282. $this->insertChunk($fileId, $chunk, $i++);
  283. }
  284. }
  285. private function insertChunk($id, $data, $chunkNumber)
  286. {
  287. $chunk = [
  288. 'files_id' => $id,
  289. 'n' => $chunkNumber,
  290. 'data' => new MongoBinData($data),
  291. ];
  292. return $this->chunks->insert($chunk);
  293. }
  294. private function insertFile($metadata)
  295. {
  296. $this->ensureIndexes();
  297. $metadata['uploadDate'] = new MongoDate();
  298. $this->insert($metadata);
  299. return $metadata;
  300. }
  301. }