dolibarr 23.0.4
memory.lib.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2009-2010 Laurent Destailleur <eldy@users.sourceforge.net>
3 * Copyright (C) 2021-2024 Frédéric France <frederic.france@free.fr>
4 * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <https://www.gnu.org/licenses/>.
18 * or see https://www.gnu.org/
19 */
20
26global $shmkeys, $shmoffset;
27
28$shmkeys = array(
29 'main' => 1,
30 'admin' => 2,
31 'dict' => 3,
32 'companies' => 4,
33 'suppliers' => 5,
34 'products' => 6,
35 'commercial' => 7,
36 'compta' => 8,
37 'projects' => 9,
38 'cashdesk' => 10,
39 'agenda' => 11,
40 'bills' => 12,
41 'propal' => 13,
42 'boxes' => 14,
43 'banks' => 15,
44 'other' => 16,
45 'errors' => 17,
46 'members' => 18,
47 'ecm' => 19,
48 'orders' => 20,
49 'users' => 21,
50 'help' => 22,
51 'stocks' => 23,
52 'interventions' => 24,
53 'donations' => 25,
54 'contracts' => 26,
55);
56$shmoffset = 1000; // Max number of entries found into a language file. If too low, some entries will be overwritten.
57
58
59
71function dol_setcache($memoryid, $data, $expire = 0, $filecache = 0, $replace = 0)
72{
73 global $conf;
74
75 $result = 0;
76
77 if (strpos($memoryid, 'count_') === 0) { // The memoryid key start with 'count_...'
78 if (!getDolGlobalString('MAIN_CACHE_COUNT')) {
79 return 0;
80 }
81 }
82
83 if (isModEnabled('memcached') && class_exists('Memcached')) {
84 // Using a memcached server
85 global $dolmemcache;
86 if (empty($dolmemcache) || !is_object($dolmemcache)) {
87 $dolmemcache = new Memcached();
88 $tmparray = explode(':', getDolGlobalString('MEMCACHED_SERVER'));
89 $port = (empty($tmparray[1]) ? 0 : $tmparray[1]);
90 $result = $dolmemcache->addServer($tmparray[0], ($port || strpos($tmparray[0], '/') !== false) ? $port : 11211);
91 if (!$result) {
92 return -1;
93 }
94 }
95
96 $memoryid = session_name().'_'.$memoryid;
97 //$dolmemcache->setOption(Memcached::OPT_COMPRESSION, false);
98 $dolmemcache->add($memoryid, $data, $expire); // This fails if key already exists
99 $rescode = $dolmemcache->getResultCode();
100 if ($rescode == 0) {
101 return is_array($data) ? count($data) : (is_scalar($data) ? strlen($data) : 0);
102 } elseif (!empty($replace) && $rescode == Memcached::RES_NOTSTORED) {
103 $dolmemcache->replace($memoryid, $data, $expire); // This fails if key does not exists
104 $rescode = $dolmemcache->getResultCode();
105 if ($rescode == 0) {
106 return is_array($data) ? count($data) : (is_scalar($data) ? strlen($data) : 0);
107 } else {
108 return -$rescode;
109 }
110 } elseif ($rescode == Memcached::RES_NOTSTORED) {
111 // Key already exists and caller did not ask to replace it: nothing to do, this is not an error.
112 // Happens when several requests load the same data concurrently, only the first add() wins.
113 return 0;
114 } else {
115 return -$rescode;
116 }
117 } elseif (isModEnabled('memcached') && class_exists('Memcache')) { // This is a really not reliable cache ! Use Memcached instead.
118 // Using a memcache server
119 global $dolmemcache;
120 if (empty($dolmemcache) || !is_object($dolmemcache)) {
121 $dolmemcache = new Memcache();
122 $tmparray = explode(':', getDolGlobalString('MEMCACHED_SERVER'));
123 $port = (empty($tmparray[1]) ? 0 : $tmparray[1]);
124 $result = $dolmemcache->addServer($tmparray[0], ($port || strpos($tmparray[0], '/') !== false) ? $port : 11211);
125 if (!$result) {
126 return -1;
127 }
128 }
129
130 $memoryid = session_name().'_'.$memoryid;
131 //$dolmemcache->setOption(Memcached::OPT_COMPRESSION, false);
132 $result = $dolmemcache->add($memoryid, $data, 0, $expire); // This fails if key already exists
133 if ($result) {
134 return is_array($data) ? count($data) : (is_scalar($data) ? strlen($data) : 0);
135 } else {
136 return -1;
137 }
138 } elseif (getDolGlobalInt('MAIN_OPTIMIZE_SPEED') & 0x02) { // This is a really not reliable cache ! Use Memcached instead.
139 // Using shmop
140 $result = dol_setshmop($memoryid, $data, $expire);
141 } elseif ($filecache > 0) {
142 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
143 require_once DOL_DOCUMENT_ROOT.'/core/lib/security.lib.php';
144 require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
145 $now = dol_now();
146 $memoryid = session_name().'_'.$memoryid;
147 $dircache = 'dolcache';
148 $pathcache = DOL_DATA_ROOT.'/'.$dircache;
149 if (!dol_is_dir($pathcache)) {
150 $result = dol_mkdir($pathcache);
151 if ($result < 0) {
152 return $result;
153 }
154 }
155 if ($expire != 0) {
156 $expire = dol_time_plus_duree($now, $expire, 's');
157 }
158
159 $cachedata = array("expire" => $expire, "data" => $data);
160 $cachejson = dolEncrypt(json_encode($cachedata));
161 if (!dol_is_file($pathcache.'/'.$memoryid.'.cache') || $replace > 0) {
162 $result = file_put_contents($pathcache.'/'.$memoryid.'.cache', $cachejson);
163 dolChmod($pathcache.'/'.$memoryid.'.cache');
164 } else {
165 return 0;
166 }
167 } else {
168 // No intersession cache system available, we use at least the perpage cache
169 $conf->cache['cachememory_'.$memoryid] = $data;
170 $result = is_array($data) ? count($data) : (is_scalar($data) ? strlen($data) : 0);
171 }
172
173 return $result;
174}
175
184function dol_getcache($memoryid, $filecache = 0)
185{
186 global $conf;
187
188 if (strpos($memoryid, 'count_') === 0) { // The memoryid key start with 'count_...'
189 if (!getDolGlobalString('MAIN_CACHE_COUNT')) {
190 return null;
191 }
192 }
193
194 // Using a memcached server
195 if (isModEnabled('memcached') && class_exists('Memcached')) {
196 global $m;
197 if (empty($m) || !is_object($m)) {
198 $m = new Memcached();
199 $tmparray = explode(':', getDolGlobalString('MEMCACHED_SERVER'));
200 $port = (empty($tmparray[1]) ? 0 : $tmparray[1]);
201 $result = $m->addServer($tmparray[0], ($port || strpos($tmparray[0], '/') !== false) ? $port : 11211);
202 if (!$result) {
203 return -1;
204 }
205 }
206
207 $memoryid = session_name().'_'.$memoryid;
208 //$m->setOption(Memcached::OPT_COMPRESSION, false);
209 //print "Get memoryid=".$memoryid;
210 $data = $m->get($memoryid);
211 $rescode = $m->getResultCode();
212 //print "memoryid=".$memoryid." - rescode=".$rescode." - count(response)=".json_encode($data)."\n<br>";
213 //var_dump($data);
214 if ($rescode == 0) {
215 return $data;
216 } elseif ($rescode == 16) { // = Memcached::MEMCACHED_NOTFOUND but this constant does not exists.
217 return null;
218 } else {
219 return -$rescode;
220 }
221 } elseif (isModEnabled('memcached') && class_exists('Memcache')) { // This is a really not reliable cache ! Use Memcached instead.
222 global $m;
223 if (empty($m) || !is_object($m)) {
224 $m = new Memcache();
225 $tmparray = explode(':', getDolGlobalString('MEMCACHED_SERVER'));
226 $port = (empty($tmparray[1]) ? 0 : $tmparray[1]);
227 $result = $m->addServer($tmparray[0], ($port || strpos($tmparray[0], '/') !== false) ? $port : 11211);
228 if (!$result) {
229 return -1;
230 }
231 }
232
233 $memoryid = session_name().'_'.$memoryid;
234 //$m->setOption(Memcached::OPT_COMPRESSION, false);
235 $data = $m->get($memoryid);
236 //print "memoryid=".$memoryid." - rescode=".$rescode." - data=".count($data)."\n<br>";
237 //var_dump($data);
238 if ($data) {
239 return $data;
240 } else {
241 return null; // There is no way to make a difference between NOTFOUND and error when using Memcache. So do not use it, use Memcached instead.
242 }
243 } elseif (getDolGlobalInt('MAIN_OPTIMIZE_SPEED') & 0x02) { // This is a really not reliable cache ! Use Memcached instead.
244 // Using shmop
245 $data = dol_getshmop($memoryid);
246 return $data;
247 } elseif ($filecache > 0) {
248 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
249 require_once DOL_DOCUMENT_ROOT.'/core/lib/security.lib.php';
250 require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
251 $now = dol_now();
252 $memoryid = session_name().'_'.$memoryid;
253 $dircache = 'dolcache';
254 $pathcache = DOL_DATA_ROOT.'/'.$dircache;
255 if (!dol_is_file($pathcache.'/'.$memoryid.'.cache')) {
256 return null;
257 }
258 $data = file_get_contents($pathcache.'/'.$memoryid.'.cache');
259 if (!$data) {
260 return -1;
261 }
262 $json = json_decode(dolDecrypt($data));
263 if ($json->expire > $now) {
264 return $json->data;
265 } else {
266 $result = dol_delete_file($pathcache.'/'.$memoryid.'.cache');
267 if (!$result) {
268 return -2;
269 }
270 }
271 return null;
272 } else {
273 // No intersession cache system available, we use at least the perpage cache
274 if (isset($conf->cache['cachememory_'.$memoryid])) {
275 return $conf->cache['cachememory_'.$memoryid];
276 }
277 }
278
279 return null;
280}
281
282
283
290function dol_getshmopaddress($memoryid)
291{
292 global $shmkeys, $shmoffset;
293 if (empty($shmkeys[$memoryid])) { // No room reserved for this memoryid, no way to use cache
294 return 0;
295 }
296 return $shmkeys[$memoryid] + $shmoffset;
297}
298
305{
306 global $shmkeys;
307
308 $resarray = array();
309 foreach ($shmkeys as $key => $val) {
310 $result = dol_getshmop($key);
311 if (!is_numeric($result) || $result > 0) {
312 $resarray[$key] = $result;
313 }
314 }
315 return $resarray;
316}
317
326function dol_setshmop($memoryid, $data, $expire)
327{
328 global $shmkeys;
329
330 //print 'dol_setshmop memoryid='.$memoryid."<br>\n";
331 if (empty($shmkeys[$memoryid]) || !function_exists("shmop_write")) {
332 return 0;
333 }
334 $shmkey = dol_getshmopaddress($memoryid);
335 if (empty($shmkey)) {
336 return 0; // No key reserved for this memoryid, we can't cache this memoryid
337 }
338
339 $newdata = serialize($data);
340 $size = strlen($newdata);
341 //print 'dol_setshmop memoryid='.$memoryid." shmkey=".$shmkey." newdata=".$size."bytes<br>\n";
342 $handle = shmop_open($shmkey, 'c', 0644, 6 + $size);
343 if ($handle) {
344 $shm_bytes_written1 = shmop_write($handle, str_pad((string) $size, 6), 0);
345 $shm_bytes_written2 = shmop_write($handle, $newdata, 6);
346 if ($shm_bytes_written1 + $shm_bytes_written2 != 6 + dol_strlen($newdata)) {
347 print "Couldn't write the entire length of data\n";
348 }
349 // @phan-suppress-next-line PhanDeprecatedFunctionInternal
350 shmop_close($handle);
351 return ($shm_bytes_written1 + $shm_bytes_written2);
352 } else {
353 print 'Error in shmop_open for memoryid='.$memoryid.' shmkey='.$shmkey.' 6+size=6+'.$size;
354 return -1;
355 }
356}
357
364function dol_getshmop($memoryid)
365{
366 global $shmkeys;
367
368 $data = null;
369
370 if (empty($shmkeys[$memoryid]) || !function_exists("shmop_open")) {
371 return null;
372 }
373 $shmkey = dol_getshmopaddress($memoryid);
374 if (empty($shmkey)) {
375 return null; // No key reserved for this memoryid, we can't cache this memoryid
376 }
377
378 //print 'dol_getshmop memoryid='.$memoryid." shmkey=".$shmkey."<br>\n";
379 $handle = @shmop_open($shmkey, 'a', 0, 0);
380 if ($handle) {
381 $size = (int) trim(shmop_read($handle, 0, 6));
382 if ($size) {
383 $data = unserialize(shmop_read($handle, 6, $size));
384 } else {
385 return -1;
386 }
387 // @phan-suppress-next-line PhanDeprecatedFunctionInternal
388 shmop_close($handle);
389 } else {
390 return null; // Can't open existing block, so we suppose it was not created, so nothing were cached yet for the memoryid
391 }
392 return $data;
393}
dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth=0, $tz='')
Add a delay to a date.
Definition date.lib.php:128
dol_delete_file($file, $disableglob=0, $nophperrors=0, $nohook=0, $object=null, $allowdotdot=false, $indexdatabase=1, $nolog=0)
Remove a file or several files with a mask.
dol_is_file($pathoffile)
Return if path is a file.
dol_is_dir($folder)
Test if filename is a directory.
dol_now($mode='gmt')
Return date for now.
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
dolChmod($filepath, $newmask='')
Change mod of a file.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
dol_mkdir($dir, $dataroot='', $newmask='')
Creation of a directory (this can create recursive subdir)
dol_setcache($memoryid, $data, $expire=0, $filecache=0, $replace=0)
Save data into a memory area shared by all users, all sessions on server.
dol_getcache($memoryid, $filecache=0)
Read a memory area shared by all users, all sessions on server.
dol_listshmop()
Return list of contents of all memory area shared.
dol_setshmop($memoryid, $data, $expire)
Save data into a memory area shared by all users, all sessions on server.
dol_getshmopaddress($memoryid)
Return shared memory address used to store dataset with key memoryid.
dol_getshmop($memoryid)
Read a memory area shared by all users, all sessions on server.
dolEncrypt($chain, $key='', $ciphering='', $forceseed='')
Encode a string with a symmetric encryption.
dolDecrypt($chain, $key='')
Decode a string with a symmetric encryption.