Security update to Drupal 8.4.6
[yaffs-website] / vendor / doctrine / cache / lib / Doctrine / Common / Cache / ExtMongoDBCache.php
1 <?php
2
3 declare(strict_types=1);
4
5 /*
6  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
7  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
8  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
9  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
10  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
11  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
12  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
13  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
14  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
15  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
16  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
17  *
18  * This software consists of voluntary contributions made by many individuals
19  * and is licensed under the MIT license. For more information, see
20  * <http://www.doctrine-project.org>.
21  */
22
23 namespace Doctrine\Common\Cache;
24
25 use MongoDB\BSON\Binary;
26 use MongoDB\BSON\UTCDateTime;
27 use MongoDB\Collection;
28 use MongoDB\Database;
29 use MongoDB\Driver\Exception\Exception;
30 use MongoDB\Model\BSONDocument;
31
32 /**
33  * MongoDB cache provider for ext-mongodb
34  *
35  * @internal Do not use - will be removed in 2.0. Use MongoDBCache instead
36  */
37 class ExtMongoDBCache extends CacheProvider
38 {
39     /**
40      * @var Database
41      */
42     private $database;
43
44     /**
45      * @var Collection
46      */
47     private $collection;
48
49     /**
50      * @var bool
51      */
52     private $expirationIndexCreated = false;
53
54     /**
55      * Constructor.
56      *
57      * This provider will default to the write concern and read preference
58      * options set on the Database instance (or inherited from MongoDB or
59      * Client). Using an unacknowledged write concern (< 1) may make the return
60      * values of delete() and save() unreliable. Reading from secondaries may
61      * make contain() and fetch() unreliable.
62      *
63      * @see http://www.php.net/manual/en/mongo.readpreferences.php
64      * @see http://www.php.net/manual/en/mongo.writeconcerns.php
65      * @param Collection $collection
66      */
67     public function __construct(Collection $collection)
68     {
69         // Ensure there is no typemap set - we want to use our own
70         $this->collection = $collection->withOptions(['typeMap' => null]);
71         $this->database = new Database($collection->getManager(), $collection->getDatabaseName());
72     }
73
74     /**
75      * {@inheritdoc}
76      */
77     protected function doFetch($id)
78     {
79         $document = $this->collection->findOne(['_id' => $id], [MongoDBCache::DATA_FIELD, MongoDBCache::EXPIRATION_FIELD]);
80
81         if ($document === null) {
82             return false;
83         }
84
85         if ($this->isExpired($document)) {
86             $this->createExpirationIndex();
87             $this->doDelete($id);
88             return false;
89         }
90
91         return unserialize($document[MongoDBCache::DATA_FIELD]->getData());
92     }
93
94     /**
95      * {@inheritdoc}
96      */
97     protected function doContains($id)
98     {
99         $document = $this->collection->findOne(['_id' => $id], [MongoDBCache::EXPIRATION_FIELD]);
100
101         if ($document === null) {
102             return false;
103         }
104
105         if ($this->isExpired($document)) {
106             $this->createExpirationIndex();
107             $this->doDelete($id);
108             return false;
109         }
110
111         return true;
112     }
113
114     /**
115      * {@inheritdoc}
116      */
117     protected function doSave($id, $data, $lifeTime = 0)
118     {
119         try {
120             $this->collection->updateOne(
121                 ['_id' => $id],
122                 ['$set' => [
123                     MongoDBCache::EXPIRATION_FIELD => ($lifeTime > 0 ? new UTCDateTime((time() + $lifeTime) * 1000): null),
124                     MongoDBCache::DATA_FIELD => new Binary(serialize($data), Binary::TYPE_GENERIC),
125                 ]],
126                 ['upsert' => true]
127             );
128         } catch (Exception $e) {
129             return false;
130         }
131
132         return true;
133     }
134
135     /**
136      * {@inheritdoc}
137      */
138     protected function doDelete($id)
139     {
140         try {
141             $this->collection->deleteOne(['_id' => $id]);
142         } catch (Exception $e) {
143             return false;
144         }
145
146         return true;
147     }
148
149     /**
150      * {@inheritdoc}
151      */
152     protected function doFlush()
153     {
154         try {
155             // Use remove() in lieu of drop() to maintain any collection indexes
156             $this->collection->deleteMany([]);
157         } catch (Exception $e) {
158             return false;
159         }
160
161         return true;
162     }
163
164     /**
165      * {@inheritdoc}
166      */
167     protected function doGetStats()
168     {
169         $uptime = null;
170         $memoryUsage = null;
171
172         try {
173             $serverStatus = $this->database->command([
174                 'serverStatus' => 1,
175                 'locks' => 0,
176                 'metrics' => 0,
177                 'recordStats' => 0,
178                 'repl' => 0,
179             ])->toArray()[0];
180             $uptime = $serverStatus['uptime'] ?? null;
181         } catch (Exception $e) {
182         }
183
184         try {
185             $collStats = $this->database->command(['collStats' => $this->collection->getCollectionName()])->toArray()[0];
186             $memoryUsage = $collStats['size'] ?? null;
187         } catch (Exception $e) {
188         }
189
190         return [
191             Cache::STATS_HITS => null,
192             Cache::STATS_MISSES => null,
193             Cache::STATS_UPTIME => $uptime,
194             Cache::STATS_MEMORY_USAGE => $memoryUsage,
195             Cache::STATS_MEMORY_AVAILABLE  => null,
196         ];
197     }
198
199     /**
200      * Check if the document is expired.
201      *
202      * @param BSONDocument $document
203      *
204      * @return bool
205      */
206     private function isExpired(BSONDocument $document): bool
207     {
208         return isset($document[MongoDBCache::EXPIRATION_FIELD]) &&
209             $document[MongoDBCache::EXPIRATION_FIELD] instanceof UTCDateTime &&
210             $document[MongoDBCache::EXPIRATION_FIELD]->toDateTime() < new \DateTime();
211     }
212
213     private function createExpirationIndex(): void
214     {
215         if ($this->expirationIndexCreated) {
216             return;
217         }
218
219         $this->collection->createIndex([MongoDBCache::EXPIRATION_FIELD => 1], ['background' => true, 'expireAfterSeconds' => 0]);
220     }
221 }