dolibarr 22.0.5
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 } else {
164 return 0;
165 }
166 } else {
167 // No intersession cache system available, we use at least the perpage cache
168 $conf->cache['cachememory_'.$memoryid] = $data;
169 $result = is_array($data) ? count($data) : (is_scalar($data) ? strlen($data) : 0);
170 }
171
172 return $result;
173}
174
183function dol_getcache($memoryid, $filecache = 0)
184{
185 global $conf;
186
187 if (strpos($memoryid, 'count_') === 0) { // The memoryid key start with 'count_...'
188 if (!getDolGlobalString('MAIN_CACHE_COUNT')) {
189 return null;
190 }
191 }
192
193 // Using a memcached server
194 if (isModEnabled('memcached') && class_exists('Memcached')) {
195 global $m;
196 if (empty($m) || !is_object($m)) {
197 $m = new Memcached();
198 $tmparray = explode(':', getDolGlobalString('MEMCACHED_SERVER'));
199 $port = (empty($tmparray[1]) ? 0 : $tmparray[1]);
200 $result = $m->addServer($tmparray[0], ($port || strpos($tmparray[0], '/') !== false) ? $port : 11211);
201 if (!$result) {
202 return -1;
203 }
204 }
205
206 $memoryid = session_name().'_'.$memoryid;
207 //$m->setOption(Memcached::OPT_COMPRESSION, false);
208 //print "Get memoryid=".$memoryid;
209 $data = $m->get($memoryid);
210 $rescode = $m->getResultCode();
211 //print "memoryid=".$memoryid." - rescode=".$rescode." - count(response)=".count($data)."\n<br>";
212 //var_dump($data);
213 if ($rescode == 0) {
214 return $data;
215 } elseif ($rescode == 16) { // = Memcached::MEMCACHED_NOTFOUND but this constant doe snot exists.
216 return null;
217 } else {
218 return -$rescode;
219 }
220 } elseif (isModEnabled('memcached') && class_exists('Memcache')) { // This is a really not reliable cache ! Use Memcached instead.
221 global $m;
222 if (empty($m) || !is_object($m)) {
223 $m = new Memcache();
224 $tmparray = explode(':', getDolGlobalString('MEMCACHED_SERVER'));
225 $port = (empty($tmparray[1]) ? 0 : $tmparray[1]);
226 $result = $m->addServer($tmparray[0], ($port || strpos($tmparray[0], '/') !== false) ? $port : 11211);
227 if (!$result) {
228 return -1;
229 }
230 }
231
232 $memoryid = session_name().'_'.$memoryid;
233 //$m->setOption(Memcached::OPT_COMPRESSION, false);
234 $data = $m->get($memoryid);
235 //print "memoryid=".$memoryid." - rescode=".$rescode." - data=".count($data)."\n<br>";
236 //var_dump($data);
237 if ($data) {
238 return $data;
239 } else {
240 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.
241 }
242 } elseif (getDolGlobalInt('MAIN_OPTIMIZE_SPEED') & 0x02) { // This is a really not reliable cache ! Use Memcached instead.
243 // Using shmop
244 $data = dol_getshmop($memoryid);
245 return $data;
246 } elseif ($filecache > 0) {
247 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
248 require_once DOL_DOCUMENT_ROOT.'/core/lib/security.lib.php';
249 require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
250 $now = dol_now();
251 $memoryid = session_name().'_'.$memoryid;
252 $dircache = 'dolcache';
253 $pathcache = DOL_DATA_ROOT.'/'.$dircache;
254 if (!dol_is_file($pathcache.'/'.$memoryid.'.cache')) {
255 return null;
256 }
257 $data = file_get_contents($pathcache.'/'.$memoryid.'.cache');
258 if (!$data) {
259 return -1;
260 }
261 $json = json_decode(dolDecrypt($data));
262 if ($json->expire > $now) {
263 return $json->data;
264 } else {
265 $result = dol_delete_file($pathcache.'/'.$memoryid.'.cache');
266 if (!$result) {
267 return -2;
268 }
269 }
270 return null;
271 } else {
272 // No intersession cache system available, we use at least the perpage cache
273 if (isset($conf->cache['cachememory_'.$memoryid])) {
274 return $conf->cache['cachememory_'.$memoryid];
275 }
276 }
277
278 return null;
279}
280
281
282
289function dol_getshmopaddress($memoryid)
290{
291 global $shmkeys, $shmoffset;
292 if (empty($shmkeys[$memoryid])) { // No room reserved for this memoryid, no way to use cache
293 return 0;
294 }
295 return $shmkeys[$memoryid] + $shmoffset;
296}
297
304{
305 global $shmkeys;
306
307 $resarray = array();
308 foreach ($shmkeys as $key => $val) {
309 $result = dol_getshmop($key);
310 if (!is_numeric($result) || $result > 0) {
311 $resarray[$key] = $result;
312 }
313 }
314 return $resarray;
315}
316
325function dol_setshmop($memoryid, $data, $expire)
326{
327 global $shmkeys;
328
329 //print 'dol_setshmop memoryid='.$memoryid."<br>\n";
330 if (empty($shmkeys[$memoryid]) || !function_exists("shmop_write")) {
331 return 0;
332 }
333 $shmkey = dol_getshmopaddress($memoryid);
334 if (empty($shmkey)) {
335 return 0; // No key reserved for this memoryid, we can't cache this memoryid
336 }
337
338 $newdata = serialize($data);
339 $size = strlen($newdata);
340 //print 'dol_setshmop memoryid='.$memoryid." shmkey=".$shmkey." newdata=".$size."bytes<br>\n";
341 $handle = shmop_open($shmkey, 'c', 0644, 6 + $size);
342 if ($handle) {
343 $shm_bytes_written1 = shmop_write($handle, str_pad((string) $size, 6), 0);
344 $shm_bytes_written2 = shmop_write($handle, $newdata, 6);
345 if ($shm_bytes_written1 + $shm_bytes_written2 != 6 + dol_strlen($newdata)) {
346 print "Couldn't write the entire length of data\n";
347 }
348 // @phan-suppress-next-line PhanDeprecatedFunctionInternal
349 shmop_close($handle);
350 return ($shm_bytes_written1 + $shm_bytes_written2);
351 } else {
352 print 'Error in shmop_open for memoryid='.$memoryid.' shmkey='.$shmkey.' 6+size=6+'.$size;
353 return -1;
354 }
355}
356
363function dol_getshmop($memoryid)
364{
365 global $shmkeys;
366
367 $data = null;
368
369 if (empty($shmkeys[$memoryid]) || !function_exists("shmop_open")) {
370 return null;
371 }
372 $shmkey = dol_getshmopaddress($memoryid);
373 if (empty($shmkey)) {
374 return null; // No key reserved for this memoryid, we can't cache this memoryid
375 }
376
377 //print 'dol_getshmop memoryid='.$memoryid." shmkey=".$shmkey."<br>\n";
378 $handle = @shmop_open($shmkey, 'a', 0, 0);
379 if ($handle) {
380 $size = (int) trim(shmop_read($handle, 0, 6));
381 if ($size) {
382 $data = unserialize(shmop_read($handle, 6, $size));
383 } else {
384 return -1;
385 }
386 // @phan-suppress-next-line PhanDeprecatedFunctionInternal
387 shmop_close($handle);
388 } else {
389 return null; // Can't open existing block, so we suppose it was not created, so nothing were cached yet for the memoryid
390 }
391 return $data;
392}
dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth=0)
Add a delay to a date.
Definition date.lib.php:125
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_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
dol_now($mode='auto')
Return date for now.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
dol_mkdir($dir, $dataroot='', $newmask='')
Creation of a directory (this can create recursive subdir)
global $conf
The following vars must be defined: $type2label $form $conf, $lang, The following vars may also be de...
Definition member.php:79
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.