MongoDB.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  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. if (class_exists('MongoDB', false)) {
  16. return;
  17. }
  18. use Alcaeus\MongoDbAdapter\Helper;
  19. use Alcaeus\MongoDbAdapter\TypeConverter;
  20. use Alcaeus\MongoDbAdapter\ExceptionConverter;
  21. use MongoDB\Model\CollectionInfo;
  22. /**
  23. * Instances of this class are used to interact with a database.
  24. * @link http://www.php.net/manual/en/class.mongodb.php
  25. */
  26. class MongoDB
  27. {
  28. use Helper\ReadPreference;
  29. use Helper\SlaveOkay;
  30. use Helper\WriteConcern;
  31. const PROFILING_OFF = 0;
  32. const PROFILING_SLOW = 1;
  33. const PROFILING_ON = 2;
  34. /**
  35. * @var MongoClient
  36. */
  37. protected $connection;
  38. /**
  39. * @var \MongoDB\Database
  40. */
  41. protected $db;
  42. /**
  43. * @var string
  44. */
  45. protected $name;
  46. /**
  47. * Creates a new database
  48. *
  49. * This method is not meant to be called directly. The preferred way to create an instance of MongoDB is through {@see Mongo::__get()} or {@see Mongo::selectDB()}.
  50. * @link http://www.php.net/manual/en/mongodb.construct.php
  51. * @param MongoClient $conn Database connection.
  52. * @param string $name Database name.
  53. * @throws Exception
  54. */
  55. public function __construct(MongoClient $conn, $name)
  56. {
  57. $this->checkDatabaseName($name);
  58. $this->connection = $conn;
  59. $this->name = (string) $name;
  60. $this->setReadPreferenceFromArray($conn->getReadPreference());
  61. $this->setWriteConcernFromArray($conn->getWriteConcern());
  62. $this->createDatabaseObject();
  63. }
  64. /**
  65. * @return \MongoDB\Database
  66. * @internal This method is not part of the ext-mongo API
  67. */
  68. public function getDb()
  69. {
  70. return $this->db;
  71. }
  72. /**
  73. * The name of this database
  74. *
  75. * @link http://www.php.net/manual/en/mongodb.--tostring.php
  76. * @return string Returns this database's name.
  77. */
  78. public function __toString()
  79. {
  80. return $this->name;
  81. }
  82. /**
  83. * Gets a collection
  84. *
  85. * @link http://www.php.net/manual/en/mongodb.get.php
  86. * @param string $name The name of the collection.
  87. * @return MongoCollection
  88. */
  89. public function __get($name)
  90. {
  91. // Handle w and wtimeout properties that replicate data stored in $readPreference
  92. if ($name === 'w' || $name === 'wtimeout') {
  93. return $this->getWriteConcern()[$name];
  94. }
  95. return $this->selectCollection($name);
  96. }
  97. /**
  98. * @param string $name
  99. * @param mixed $value
  100. */
  101. public function __set($name, $value)
  102. {
  103. if ($name === 'w' || $name === 'wtimeout') {
  104. trigger_error("The '{$name}' property is read-only", E_USER_DEPRECATED);
  105. }
  106. }
  107. /**
  108. * Returns information about collections in this database
  109. *
  110. * @link http://www.php.net/manual/en/mongodb.getcollectioninfo.php
  111. * @param array $options An array of options for listing the collections.
  112. * @return array
  113. */
  114. public function getCollectionInfo(array $options = [])
  115. {
  116. $includeSystemCollections = false;
  117. // The includeSystemCollections option is no longer supported in the command
  118. if (isset($options['includeSystemCollections'])) {
  119. $includeSystemCollections = $options['includeSystemCollections'];
  120. unset($options['includeSystemCollections']);
  121. }
  122. try {
  123. $collections = $this->db->listCollections($options);
  124. } catch (\MongoDB\Driver\Exception\Exception $e) {
  125. throw ExceptionConverter::toLegacy($e);
  126. }
  127. $getCollectionInfo = function (CollectionInfo $collectionInfo) {
  128. return [
  129. 'name' => $collectionInfo->getName(),
  130. 'options' => $collectionInfo->getOptions(),
  131. ];
  132. };
  133. $eligibleCollections = array_filter(
  134. iterator_to_array($collections),
  135. $this->getSystemCollectionFilterClosure($includeSystemCollections)
  136. );
  137. return array_map($getCollectionInfo, $eligibleCollections);
  138. }
  139. /**
  140. * Get all collections from this database
  141. *
  142. * @link http://www.php.net/manual/en/mongodb.getcollectionnames.php
  143. * @param array $options An array of options for listing the collections.
  144. * @return array Returns the names of the all the collections in the database as an array
  145. */
  146. public function getCollectionNames(array $options = [])
  147. {
  148. $includeSystemCollections = false;
  149. // The includeSystemCollections option is no longer supported in the command
  150. if (isset($options['includeSystemCollections'])) {
  151. $includeSystemCollections = $options['includeSystemCollections'];
  152. unset($options['includeSystemCollections']);
  153. }
  154. try {
  155. $collections = $this->db->listCollections($options);
  156. } catch (\MongoDB\Driver\Exception\Exception $e) {
  157. throw ExceptionConverter::toLegacy($e);
  158. }
  159. $getCollectionName = function (CollectionInfo $collectionInfo) {
  160. return $collectionInfo->getName();
  161. };
  162. $eligibleCollections = array_filter(
  163. iterator_to_array($collections),
  164. $this->getSystemCollectionFilterClosure($includeSystemCollections)
  165. );
  166. return array_map($getCollectionName, $eligibleCollections);
  167. }
  168. /**
  169. * @return MongoClient
  170. * @internal This method is not part of the ext-mongo API
  171. */
  172. public function getConnection()
  173. {
  174. return $this->connection;
  175. }
  176. /**
  177. * Fetches toolkit for dealing with files stored in this database
  178. *
  179. * @link http://www.php.net/manual/en/mongodb.getgridfs.php
  180. * @param string $prefix The prefix for the files and chunks collections.
  181. * @return MongoGridFS Returns a new gridfs object for this database.
  182. */
  183. public function getGridFS($prefix = "fs")
  184. {
  185. return new \MongoGridFS($this, $prefix);
  186. }
  187. /**
  188. * Gets this database's profiling level
  189. *
  190. * @link http://www.php.net/manual/en/mongodb.getprofilinglevel.php
  191. * @return int Returns the profiling level.
  192. */
  193. public function getProfilingLevel()
  194. {
  195. $result = $this->command(['profile' => -1]);
  196. return ($result['ok'] && isset($result['was'])) ? $result['was'] : 0;
  197. }
  198. /**
  199. * Sets this database's profiling level
  200. *
  201. * @link http://www.php.net/manual/en/mongodb.setprofilinglevel.php
  202. * @param int $level Profiling level.
  203. * @return int Returns the previous profiling level.
  204. */
  205. public function setProfilingLevel($level)
  206. {
  207. $result = $this->command(['profile' => $level]);
  208. return ($result['ok'] && isset($result['was'])) ? $result['was'] : 0;
  209. }
  210. /**
  211. * Drops this database
  212. *
  213. * @link http://www.php.net/manual/en/mongodb.drop.php
  214. * @return array Returns the database response.
  215. */
  216. public function drop()
  217. {
  218. return TypeConverter::toLegacy($this->db->drop());
  219. }
  220. /**
  221. * Repairs and compacts this database
  222. *
  223. * @link http://www.php.net/manual/en/mongodb.repair.php
  224. * @param bool $preserve_cloned_files [optional] <p>If cloned files should be kept if the repair fails.</p>
  225. * @param bool $backup_original_files [optional] <p>If original files should be backed up.</p>
  226. * @return array <p>Returns db response.</p>
  227. */
  228. public function repair($preserve_cloned_files = FALSE, $backup_original_files = FALSE)
  229. {
  230. $command = [
  231. 'repairDatabase' => 1,
  232. 'preserveClonedFilesOnFailure' => $preserve_cloned_files,
  233. 'backupOriginalFiles' => $backup_original_files,
  234. ];
  235. return $this->command($command);
  236. }
  237. /**
  238. * Gets a collection
  239. *
  240. * @link http://www.php.net/manual/en/mongodb.selectcollection.php
  241. * @param string $name <b>The collection name.</b>
  242. * @throws Exception if the collection name is invalid.
  243. * @return MongoCollection Returns a new collection object.
  244. */
  245. public function selectCollection($name)
  246. {
  247. return new MongoCollection($this, $name);
  248. }
  249. /**
  250. * Creates a collection
  251. *
  252. * @link http://www.php.net/manual/en/mongodb.createcollection.php
  253. * @param string $name The name of the collection.
  254. * @param array $options
  255. * @return MongoCollection Returns a collection object representing the new collection.
  256. */
  257. public function createCollection($name, $options)
  258. {
  259. try {
  260. if (isset($options['capped'])) {
  261. $options['capped'] = (bool) $options['capped'];
  262. }
  263. $this->db->createCollection($name, $options);
  264. } catch (\MongoDB\Driver\Exception\Exception $e) {
  265. return false;
  266. }
  267. return $this->selectCollection($name);
  268. }
  269. /**
  270. * Drops a collection
  271. *
  272. * @link http://www.php.net/manual/en/mongodb.dropcollection.php
  273. * @param MongoCollection|string $coll MongoCollection or name of collection to drop.
  274. * @return array Returns the database response.
  275. *
  276. * @deprecated Use MongoCollection::drop() instead.
  277. */
  278. public function dropCollection($coll)
  279. {
  280. if ($coll instanceof MongoCollection) {
  281. $coll = $coll->getName();
  282. }
  283. return TypeConverter::toLegacy($this->db->dropCollection((string) $coll));
  284. }
  285. /**
  286. * Get a list of collections in this database
  287. *
  288. * @link http://www.php.net/manual/en/mongodb.listcollections.php
  289. * @param array $options
  290. * @return MongoCollection[] Returns a list of MongoCollections.
  291. */
  292. public function listCollections(array $options = [])
  293. {
  294. return array_map([$this, 'selectCollection'], $this->getCollectionNames($options));
  295. }
  296. /**
  297. * Creates a database reference
  298. *
  299. * @link http://www.php.net/manual/en/mongodb.createdbref.php
  300. * @param string $collection The collection to which the database reference will point.
  301. * @param mixed $document_or_id
  302. * @return array Returns a database reference array.
  303. */
  304. public function createDBRef($collection, $document_or_id)
  305. {
  306. if ($document_or_id instanceof \MongoId) {
  307. $id = $document_or_id;
  308. } elseif (is_object($document_or_id)) {
  309. if (! isset($document_or_id->_id)) {
  310. $id = $document_or_id;
  311. } else {
  312. $id = $document_or_id->_id;
  313. }
  314. } elseif (is_array($document_or_id)) {
  315. if (! isset($document_or_id['_id'])) {
  316. return null;
  317. }
  318. $id = $document_or_id['_id'];
  319. } else {
  320. $id = $document_or_id;
  321. }
  322. return MongoDBRef::create($collection, $id);
  323. }
  324. /**
  325. * Fetches the document pointed to by a database reference
  326. *
  327. * @link http://www.php.net/manual/en/mongodb.getdbref.php
  328. * @param array $ref A database reference.
  329. * @return array Returns the document pointed to by the reference.
  330. */
  331. public function getDBRef(array $ref)
  332. {
  333. $db = (isset($ref['$db']) && $ref['$db'] !== $this->name) ? $this->connection->selectDB($ref['$db']) : $this;
  334. return MongoDBRef::get($db, $ref);
  335. }
  336. /**
  337. * Runs JavaScript code on the database server.
  338. *
  339. * @link http://www.php.net/manual/en/mongodb.execute.php
  340. * @param MongoCode|string $code Code to execute.
  341. * @param array $args [optional] Arguments to be passed to code.
  342. * @return array Returns the result of the evaluation.
  343. */
  344. public function execute($code, array $args = [])
  345. {
  346. return $this->command(['eval' => $code, 'args' => $args]);
  347. }
  348. /**
  349. * Execute a database command
  350. *
  351. * @link http://www.php.net/manual/en/mongodb.command.php
  352. * @param array $data The query to send.
  353. * @param array $options
  354. * @return array Returns database response.
  355. */
  356. public function command(array $data, $options = [], &$hash = null)
  357. {
  358. try {
  359. $cursor = new \MongoCommandCursor($this->connection, $this->name, $data);
  360. $cursor->setReadPreference($this->getReadPreference());
  361. return iterator_to_array($cursor)[0];
  362. } catch (\MongoDB\Driver\Exception\Exception $e) {
  363. return ExceptionConverter::toResultArray($e);
  364. }
  365. }
  366. /**
  367. * Check if there was an error on the most recent db operation performed
  368. *
  369. * @link http://www.php.net/manual/en/mongodb.lasterror.php
  370. * @return array Returns the error, if there was one.
  371. */
  372. public function lastError()
  373. {
  374. return $this->command(array('getLastError' => 1));
  375. }
  376. /**
  377. * Checks for the last error thrown during a database operation
  378. *
  379. * @link http://www.php.net/manual/en/mongodb.preverror.php
  380. * @return array Returns the error and the number of operations ago it occurred.
  381. */
  382. public function prevError()
  383. {
  384. return $this->command(array('getPrevError' => 1));
  385. }
  386. /**
  387. * Clears any flagged errors on the database
  388. *
  389. * @link http://www.php.net/manual/en/mongodb.reseterror.php
  390. * @return array Returns the database response.
  391. */
  392. public function resetError()
  393. {
  394. return $this->command(array('resetError' => 1));
  395. }
  396. /**
  397. * Creates a database error
  398. *
  399. * @link http://www.php.net/manual/en/mongodb.forceerror.php
  400. * @return boolean Returns the database response.
  401. */
  402. public function forceError()
  403. {
  404. return $this->command(array('forceerror' => 1));
  405. }
  406. /**
  407. * Log in to this database
  408. *
  409. * @link http://www.php.net/manual/en/mongodb.authenticate.php
  410. * @param string $username The username.
  411. * @param string $password The password (in plaintext).
  412. * @return array Returns database response. If the login was successful, it will return 1.
  413. *
  414. * @deprecated This method is not implemented, supply authentication credentials through the connection string instead.
  415. */
  416. public function authenticate($username, $password)
  417. {
  418. throw new \Exception('The MongoDB::authenticate method is not supported. Please supply authentication credentials through the connection string');
  419. }
  420. /**
  421. * {@inheritdoc}
  422. */
  423. public function setReadPreference($readPreference, $tags = null)
  424. {
  425. $result = $this->setReadPreferenceFromParameters($readPreference, $tags);
  426. $this->createDatabaseObject();
  427. return $result;
  428. }
  429. /**
  430. * {@inheritdoc}
  431. */
  432. public function setWriteConcern($wstring, $wtimeout = 0)
  433. {
  434. $result = $this->setWriteConcernFromParameters($wstring, $wtimeout);
  435. $this->createDatabaseObject();
  436. return $result;
  437. }
  438. protected function notImplemented()
  439. {
  440. throw new \Exception('Not implemented');
  441. }
  442. /**
  443. * @return \MongoDB\Database
  444. */
  445. private function createDatabaseObject()
  446. {
  447. $options = [
  448. 'readPreference' => $this->readPreference,
  449. 'writeConcern' => $this->writeConcern,
  450. ];
  451. if ($this->db === null) {
  452. $this->db = $this->connection->getClient()->selectDatabase($this->name, $options);
  453. } else {
  454. $this->db = $this->db->withOptions($options);
  455. }
  456. }
  457. private function checkDatabaseName($name)
  458. {
  459. if (empty($name)) {
  460. throw new \Exception('Database name cannot be empty');
  461. }
  462. if (strlen($name) >= 64) {
  463. throw new \Exception('Database name cannot exceed 63 characters');
  464. }
  465. if (strpos($name, chr(0)) !== false) {
  466. throw new \Exception('Database name cannot contain null bytes');
  467. }
  468. $invalidCharacters = ['.', '$', '/', ' ', '\\'];
  469. foreach ($invalidCharacters as $char) {
  470. if (strchr($name, $char) !== false) {
  471. throw new \Exception('Database name contains invalid characters');
  472. }
  473. }
  474. }
  475. /**
  476. * @param bool $includeSystemCollections
  477. * @return Closure
  478. */
  479. private function getSystemCollectionFilterClosure($includeSystemCollections = false) {
  480. return function (CollectionInfo $collectionInfo) use ($includeSystemCollections) {
  481. return $includeSystemCollections || ! preg_match('#^system\.#', $collectionInfo->getName());
  482. };
  483. }
  484. /**
  485. * @return array
  486. */
  487. public function __sleep()
  488. {
  489. return ['connection', 'name'];
  490. }
  491. }