MongoDB.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  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. // @todo do away with __debugInfo once https://jira.mongodb.org/browse/PHPLIB-226 is fixed
  129. $info = $collectionInfo->__debugInfo();
  130. return array_filter(
  131. [
  132. 'name' => $collectionInfo->getName(),
  133. 'type' => isset($info['type']) ? $info['type'] : null,
  134. 'options' => $collectionInfo->getOptions(),
  135. 'info' => isset($info['info']) ? (array) $info['info'] : null,
  136. 'idIndex' => isset($info['idIndex']) ? (array) $info['idIndex'] : null,
  137. ],
  138. function ($item) { return $item !== null; }
  139. );
  140. };
  141. $eligibleCollections = array_filter(
  142. iterator_to_array($collections),
  143. $this->getSystemCollectionFilterClosure($includeSystemCollections)
  144. );
  145. return array_map($getCollectionInfo, $eligibleCollections);
  146. }
  147. /**
  148. * Get all collections from this database
  149. *
  150. * @link http://www.php.net/manual/en/mongodb.getcollectionnames.php
  151. * @param array $options An array of options for listing the collections.
  152. * @return array Returns the names of the all the collections in the database as an array
  153. */
  154. public function getCollectionNames(array $options = [])
  155. {
  156. $includeSystemCollections = false;
  157. // The includeSystemCollections option is no longer supported in the command
  158. if (isset($options['includeSystemCollections'])) {
  159. $includeSystemCollections = $options['includeSystemCollections'];
  160. unset($options['includeSystemCollections']);
  161. }
  162. try {
  163. $collections = $this->db->listCollections($options);
  164. } catch (\MongoDB\Driver\Exception\Exception $e) {
  165. throw ExceptionConverter::toLegacy($e);
  166. }
  167. $getCollectionName = function (CollectionInfo $collectionInfo) {
  168. return $collectionInfo->getName();
  169. };
  170. $eligibleCollections = array_filter(
  171. iterator_to_array($collections),
  172. $this->getSystemCollectionFilterClosure($includeSystemCollections)
  173. );
  174. return array_map($getCollectionName, $eligibleCollections);
  175. }
  176. /**
  177. * @return MongoClient
  178. * @internal This method is not part of the ext-mongo API
  179. */
  180. public function getConnection()
  181. {
  182. return $this->connection;
  183. }
  184. /**
  185. * Fetches toolkit for dealing with files stored in this database
  186. *
  187. * @link http://www.php.net/manual/en/mongodb.getgridfs.php
  188. * @param string $prefix The prefix for the files and chunks collections.
  189. * @return MongoGridFS Returns a new gridfs object for this database.
  190. */
  191. public function getGridFS($prefix = "fs")
  192. {
  193. return new \MongoGridFS($this, $prefix);
  194. }
  195. /**
  196. * Gets this database's profiling level
  197. *
  198. * @link http://www.php.net/manual/en/mongodb.getprofilinglevel.php
  199. * @return int Returns the profiling level.
  200. */
  201. public function getProfilingLevel()
  202. {
  203. $result = $this->command(['profile' => -1]);
  204. return ($result['ok'] && isset($result['was'])) ? $result['was'] : 0;
  205. }
  206. /**
  207. * Sets this database's profiling level
  208. *
  209. * @link http://www.php.net/manual/en/mongodb.setprofilinglevel.php
  210. * @param int $level Profiling level.
  211. * @return int Returns the previous profiling level.
  212. */
  213. public function setProfilingLevel($level)
  214. {
  215. $result = $this->command(['profile' => $level]);
  216. return ($result['ok'] && isset($result['was'])) ? $result['was'] : 0;
  217. }
  218. /**
  219. * Drops this database
  220. *
  221. * @link http://www.php.net/manual/en/mongodb.drop.php
  222. * @return array Returns the database response.
  223. */
  224. public function drop()
  225. {
  226. return TypeConverter::toLegacy($this->db->drop());
  227. }
  228. /**
  229. * Repairs and compacts this database
  230. *
  231. * @link http://www.php.net/manual/en/mongodb.repair.php
  232. * @param bool $preserve_cloned_files [optional] <p>If cloned files should be kept if the repair fails.</p>
  233. * @param bool $backup_original_files [optional] <p>If original files should be backed up.</p>
  234. * @return array <p>Returns db response.</p>
  235. */
  236. public function repair($preserve_cloned_files = false, $backup_original_files = false)
  237. {
  238. $command = [
  239. 'repairDatabase' => 1,
  240. 'preserveClonedFilesOnFailure' => $preserve_cloned_files,
  241. 'backupOriginalFiles' => $backup_original_files,
  242. ];
  243. return $this->command($command);
  244. }
  245. /**
  246. * Gets a collection
  247. *
  248. * @link http://www.php.net/manual/en/mongodb.selectcollection.php
  249. * @param string $name <b>The collection name.</b>
  250. * @throws Exception if the collection name is invalid.
  251. * @return MongoCollection Returns a new collection object.
  252. */
  253. public function selectCollection($name)
  254. {
  255. return new MongoCollection($this, $name);
  256. }
  257. /**
  258. * Creates a collection
  259. *
  260. * @link http://www.php.net/manual/en/mongodb.createcollection.php
  261. * @param string $name The name of the collection.
  262. * @param array $options
  263. * @return MongoCollection Returns a collection object representing the new collection.
  264. */
  265. public function createCollection($name, $options = [])
  266. {
  267. try {
  268. if (isset($options['capped'])) {
  269. $options['capped'] = (bool) $options['capped'];
  270. }
  271. $this->db->createCollection($name, $options);
  272. } catch (\MongoDB\Driver\Exception\Exception $e) {
  273. return false;
  274. }
  275. return $this->selectCollection($name);
  276. }
  277. /**
  278. * Drops a collection
  279. *
  280. * @link http://www.php.net/manual/en/mongodb.dropcollection.php
  281. * @param MongoCollection|string $coll MongoCollection or name of collection to drop.
  282. * @return array Returns the database response.
  283. *
  284. * @deprecated Use MongoCollection::drop() instead.
  285. */
  286. public function dropCollection($coll)
  287. {
  288. if ($coll instanceof MongoCollection) {
  289. $coll = $coll->getName();
  290. }
  291. return TypeConverter::toLegacy($this->db->dropCollection((string) $coll));
  292. }
  293. /**
  294. * Get a list of collections in this database
  295. *
  296. * @link http://www.php.net/manual/en/mongodb.listcollections.php
  297. * @param array $options
  298. * @return MongoCollection[] Returns a list of MongoCollections.
  299. */
  300. public function listCollections(array $options = [])
  301. {
  302. return array_map([$this, 'selectCollection'], $this->getCollectionNames($options));
  303. }
  304. /**
  305. * Creates a database reference
  306. *
  307. * @link http://www.php.net/manual/en/mongodb.createdbref.php
  308. * @param string $collection The collection to which the database reference will point.
  309. * @param mixed $document_or_id
  310. * @return array Returns a database reference array.
  311. */
  312. public function createDBRef($collection, $document_or_id)
  313. {
  314. if ($document_or_id instanceof \MongoId) {
  315. $id = $document_or_id;
  316. } elseif (is_object($document_or_id)) {
  317. if (! isset($document_or_id->_id)) {
  318. $id = $document_or_id;
  319. } else {
  320. $id = $document_or_id->_id;
  321. }
  322. } elseif (is_array($document_or_id)) {
  323. if (! isset($document_or_id['_id'])) {
  324. return null;
  325. }
  326. $id = $document_or_id['_id'];
  327. } else {
  328. $id = $document_or_id;
  329. }
  330. return MongoDBRef::create($collection, $id);
  331. }
  332. /**
  333. * Fetches the document pointed to by a database reference
  334. *
  335. * @link http://www.php.net/manual/en/mongodb.getdbref.php
  336. * @param array $ref A database reference.
  337. * @return array Returns the document pointed to by the reference.
  338. */
  339. public function getDBRef(array $ref)
  340. {
  341. $db = (isset($ref['$db']) && $ref['$db'] !== $this->name) ? $this->connection->selectDB($ref['$db']) : $this;
  342. return MongoDBRef::get($db, $ref);
  343. }
  344. /**
  345. * Runs JavaScript code on the database server.
  346. *
  347. * @link http://www.php.net/manual/en/mongodb.execute.php
  348. * @param MongoCode|string $code Code to execute.
  349. * @param array $args [optional] Arguments to be passed to code.
  350. * @return array Returns the result of the evaluation.
  351. */
  352. public function execute($code, array $args = [])
  353. {
  354. return $this->command(['eval' => $code, 'args' => $args]);
  355. }
  356. /**
  357. * Execute a database command
  358. *
  359. * @link http://www.php.net/manual/en/mongodb.command.php
  360. * @param array $data The query to send.
  361. * @param array $options
  362. * @return array Returns database response.
  363. */
  364. public function command(array $data, $options = [], &$hash = null)
  365. {
  366. try {
  367. $cursor = new \MongoCommandCursor($this->connection, $this->name, $data);
  368. $cursor->setReadPreference($this->getReadPreference());
  369. return iterator_to_array($cursor)[0];
  370. } catch (\MongoDB\Driver\Exception\Exception $e) {
  371. return ExceptionConverter::toResultArray($e);
  372. }
  373. }
  374. /**
  375. * Check if there was an error on the most recent db operation performed
  376. *
  377. * @link http://www.php.net/manual/en/mongodb.lasterror.php
  378. * @return array Returns the error, if there was one.
  379. */
  380. public function lastError()
  381. {
  382. return $this->command(array('getLastError' => 1));
  383. }
  384. /**
  385. * Checks for the last error thrown during a database operation
  386. *
  387. * @link http://www.php.net/manual/en/mongodb.preverror.php
  388. * @return array Returns the error and the number of operations ago it occurred.
  389. */
  390. public function prevError()
  391. {
  392. return $this->command(array('getPrevError' => 1));
  393. }
  394. /**
  395. * Clears any flagged errors on the database
  396. *
  397. * @link http://www.php.net/manual/en/mongodb.reseterror.php
  398. * @return array Returns the database response.
  399. */
  400. public function resetError()
  401. {
  402. return $this->command(array('resetError' => 1));
  403. }
  404. /**
  405. * Creates a database error
  406. *
  407. * @link http://www.php.net/manual/en/mongodb.forceerror.php
  408. * @return boolean Returns the database response.
  409. */
  410. public function forceError()
  411. {
  412. return $this->command(array('forceerror' => 1));
  413. }
  414. /**
  415. * Log in to this database
  416. *
  417. * @link http://www.php.net/manual/en/mongodb.authenticate.php
  418. * @param string $username The username.
  419. * @param string $password The password (in plaintext).
  420. * @return array Returns database response. If the login was successful, it will return 1.
  421. *
  422. * @deprecated This method is not implemented, supply authentication credentials through the connection string instead.
  423. */
  424. public function authenticate($username, $password)
  425. {
  426. throw new \Exception('The MongoDB::authenticate method is not supported. Please supply authentication credentials through the connection string');
  427. }
  428. /**
  429. * {@inheritdoc}
  430. */
  431. public function setReadPreference($readPreference, $tags = null)
  432. {
  433. $result = $this->setReadPreferenceFromParameters($readPreference, $tags);
  434. $this->createDatabaseObject();
  435. return $result;
  436. }
  437. /**
  438. * {@inheritdoc}
  439. */
  440. public function setWriteConcern($wstring, $wtimeout = 0)
  441. {
  442. $result = $this->setWriteConcernFromParameters($wstring, $wtimeout);
  443. $this->createDatabaseObject();
  444. return $result;
  445. }
  446. protected function notImplemented()
  447. {
  448. throw new \Exception('Not implemented');
  449. }
  450. /**
  451. * @return \MongoDB\Database
  452. */
  453. private function createDatabaseObject()
  454. {
  455. $options = [
  456. 'readPreference' => $this->readPreference,
  457. 'writeConcern' => $this->writeConcern,
  458. ];
  459. if ($this->db === null) {
  460. $this->db = $this->connection->getClient()->selectDatabase($this->name, $options);
  461. } else {
  462. $this->db = $this->db->withOptions($options);
  463. }
  464. }
  465. private function checkDatabaseName($name)
  466. {
  467. if (empty($name)) {
  468. throw new \Exception('Database name cannot be empty');
  469. }
  470. if (strlen($name) >= 64) {
  471. throw new \Exception('Database name cannot exceed 63 characters');
  472. }
  473. if (strpos($name, chr(0)) !== false) {
  474. throw new \Exception('Database name cannot contain null bytes');
  475. }
  476. $invalidCharacters = ['.', '$', '/', ' ', '\\'];
  477. foreach ($invalidCharacters as $char) {
  478. if (strchr($name, $char) !== false) {
  479. throw new \Exception('Database name contains invalid characters');
  480. }
  481. }
  482. }
  483. /**
  484. * @param bool $includeSystemCollections
  485. * @return Closure
  486. */
  487. private function getSystemCollectionFilterClosure($includeSystemCollections = false)
  488. {
  489. return function (CollectionInfo $collectionInfo) use ($includeSystemCollections) {
  490. return $includeSystemCollections || ! preg_match('#^system\.#', $collectionInfo->getName());
  491. };
  492. }
  493. /**
  494. * @return array
  495. */
  496. public function __sleep()
  497. {
  498. return ['connection', 'name'];
  499. }
  500. }