forked from Dolibarr/dolibarr
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunctions.lib.php
More file actions
13612 lines (12332 loc) · 557 KB
/
functions.lib.php
File metadata and controls
13612 lines (12332 loc) · 557 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/* Copyright (C) 2000-2007 Rodolphe Quiedeville <rodolphe@quiedeville.org>
* Copyright (C) 2003 Jean-Louis Bergamo <jlb@j1b.org>
* Copyright (C) 2004-2022 Laurent Destailleur <eldy@users.sourceforge.net>
* Copyright (C) 2004 Sebastien Di Cintio <sdicintio@ressource-toi.org>
* Copyright (C) 2004 Benoit Mortier <benoit.mortier@opensides.be>
* Copyright (C) 2004 Christophe Combelles <ccomb@free.fr>
* Copyright (C) 2005-2019 Regis Houssin <regis.houssin@inodbox.com>
* Copyright (C) 2008 Raphael Bertrand (Resultic) <raphael.bertrand@resultic.fr>
* Copyright (C) 2010-2018 Juanjo Menent <jmenent@2byte.es>
* Copyright (C) 2013 Cédric Salvador <csalvador@gpcsolutions.fr>
* Copyright (C) 2013-2021 Alexandre Spangaro <aspangaro@open-dsi.fr>
* Copyright (C) 2014 Cédric GROSS <c.gross@kreiz-it.fr>
* Copyright (C) 2014-2015 Marcos García <marcosgdf@gmail.com>
* Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
* Copyright (C) 2018-2023 Frédéric France <frederic.france@netlogic.fr>
* Copyright (C) 2019-2023 Thibault Foucart <support@ptibogxiv.net>
* Copyright (C) 2020 Open-Dsi <support@open-dsi.fr>
* Copyright (C) 2021 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
* Copyright (C) 2022 Anthony Berton <anthony.berton@bb2a.fr>
* Copyright (C) 2022 Ferran Marcet <fmarcet@2byte.es>
* Copyright (C) 2022 Charlene Benke <charlene@patas-monkey.com>
* Copyright (C) 2023 Joachim Kueter <git-jk@bloxera.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
* or see https://www.gnu.org/
*/
/**
* \file htdocs/core/lib/functions.lib.php
* \brief A set of functions for Dolibarr
* This file contains all frequently used functions.
*/
include_once DOL_DOCUMENT_ROOT.'/core/lib/json.lib.php';
// Function for better PHP x compatibility
if (!function_exists('utf8_encode')) {
/**
* Implement utf8_encode for PHP that does not support it.
*
* @param mixed $elements PHP Object to json encode
* @return string Json encoded string
*/
function utf8_encode($elements)
{
return mb_convert_encoding($elements, 'UTF-8', 'ISO-8859-1');
}
}
if (!function_exists('utf8_decode')) {
/**
* Implement utf8_decode for PHP that does not support it.
*
* @param mixed $elements PHP Object to json encode
* @return string Json encoded string
*/
function utf8_decode($elements)
{
return mb_convert_encoding($elements, 'ISO-8859-1', 'UTF-8');
}
}
if (!function_exists('str_starts_with')) {
/**
* str_starts_with
*
* @param string $haystack haystack
* @param string $needle needle
* @return boolean
*/
function str_starts_with($haystack, $needle)
{
return (string) $needle !== '' && strncmp($haystack, $needle, strlen($needle)) === 0;
}
}
if (!function_exists('str_ends_with')) {
/**
* str_ends_with
*
* @param string $haystack haystack
* @param string $needle needle
* @return boolean
*/
function str_ends_with($haystack, $needle)
{
return $needle !== '' && substr($haystack, -strlen($needle)) === (string) $needle;
}
}
if (!function_exists('str_contains')) {
/**
* str_contains
*
* @param string $haystack haystack
* @param string $needle needle
* @return boolean
*/
function str_contains($haystack, $needle)
{
return $needle !== '' && mb_strpos($haystack, $needle) !== false;
}
}
/**
* Return the full path of the directory where a module (or an object of a module) stores its files. Path may depends on the entity if a multicompany module is enabled.
*
* @param CommonObject $object Dolibarr common object
* @param string $module Override object element, for example to use 'mycompany' instead of 'societe'
* @return string|void The path of the relative directory of the module
* @since Dolibarr V18
*/
function getMultidirOutput($object, $module = '')
{
global $conf;
if (!is_object($object) && empty($module)) {
return null;
}
if (empty($module) && !empty($object->element)) {
$module = $object->element;
}
// Special case for backward compatibility
if ($module == 'fichinter') {
$module = 'ficheinter';
}
if (isset($conf->$module) && property_exists($conf->$module, 'multidir_output')) {
return $conf->$module->multidir_output[(empty($object->entity) ? $conf->entity : $object->entity)];
} else {
return 'error-diroutput-not-defined-for-this-object='.$module;
}
}
/**
* Return dolibarr global constant string value
*
* @param string $key key to return value, return '' if not set
* @param string $default value to return
* @return string
*/
function getDolGlobalString($key, $default = '')
{
global $conf;
return (string) (isset($conf->global->$key) ? $conf->global->$key : $default);
}
/**
* Return a Dolibarr global constant int value.
* The constants $conf->global->xxx are loaded by the script master.inc.php included at begin of any PHP page.
*
* @param string $key key to return value, return 0 if not set
* @param int $default value to return
* @return int
*/
function getDolGlobalInt($key, $default = 0)
{
global $conf;
return (int) (isset($conf->global->$key) ? $conf->global->$key : $default);
}
/**
* Return Dolibarr user constant string value
*
* @param string $key key to return value, return '' if not set
* @param string $default value to return
* @param User $tmpuser To get another user than current user
* @return string
*/
function getDolUserString($key, $default = '', $tmpuser = null)
{
if (empty($tmpuser)) {
global $user;
$tmpuser = $user;
}
return (string) (empty($tmpuser->conf->$key) ? $default : $tmpuser->conf->$key);
}
/**
* Return Dolibarr user constant int value
*
* @param string $key key to return value, return 0 if not set
* @param int $default value to return
* @param User $tmpuser To get another user than current user
* @return int
*/
function getDolUserInt($key, $default = 0, $tmpuser = null)
{
if (empty($tmpuser)) {
global $user;
$tmpuser = $user;
}
return (int) (empty($tmpuser->conf->$key) ? $default : $tmpuser->conf->$key);
}
/**
* Is Dolibarr module enabled
*
* @param string $module Module name to check
* @return boolean True if module is enabled
*/
function isModEnabled($module)
{
global $conf;
// Fix special cases
$arrayconv = array(
'bank' => 'banque',
'category' => 'categorie',
'contract' => 'contrat',
'project' => 'projet',
'delivery_note' => 'expedition'
);
if (!getDolGlobalString('MAIN_USE_NEW_SUPPLIERMOD')) {
$arrayconv['supplier_order'] = 'fournisseur';
$arrayconv['supplier_invoice'] = 'fournisseur';
}
if (!empty($arrayconv[$module])) {
$module = $arrayconv[$module];
}
return !empty($conf->modules[$module]);
//return !empty($conf->$module->enabled);
}
/**
* Return a DoliDB instance (database handler).
*
* @param string $type Type of database (mysql, pgsql...)
* @param string $host Address of database server
* @param string $user Authorized username
* @param string $pass Password
* @param string $name Name of database
* @param int $port Port of database server
* @return DoliDB A DoliDB instance
*/
function getDoliDBInstance($type, $host, $user, $pass, $name, $port)
{
require_once DOL_DOCUMENT_ROOT."/core/db/".$type.'.class.php';
$class = 'DoliDB'.ucfirst($type);
$dolidb = new $class($type, $host, $user, $pass, $name, $port);
return $dolidb;
}
/**
* Get list of entity id to use.
*
* @param string $element Current element
* 'societe', 'socpeople', 'actioncomm', 'agenda', 'resource',
* 'product', 'productprice', 'stock', 'bom', 'mo',
* 'propal', 'supplier_proposal', 'invoice', 'supplier_invoice', 'payment_various',
* 'categorie', 'bank_account', 'bank_account', 'adherent', 'user',
* 'commande', 'supplier_order', 'expedition', 'intervention', 'survey',
* 'contract', 'tax', 'expensereport', 'holiday', 'multicurrency', 'project',
* 'email_template', 'event', 'donation'
* 'c_paiement', 'c_payment_term', ...
* @param int $shared 0=Return id of current entity only,
* 1=Return id of current entity + shared entities (default)
* @param object $currentobject Current object if needed
* @return mixed Entity id(s) to use ( eg. entity IN ('.getEntity(elementname).')' )
*/
function getEntity($element, $shared = 1, $currentobject = null)
{
global $conf, $mc, $hookmanager, $object, $action, $db;
if (!is_object($hookmanager)) {
include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
$hookmanager = new HookManager($db);
}
// fix different element names (France to English)
switch ($element) {
case 'projet':
$element = 'project';
break;
case 'contrat':
$element = 'contract';
break; // "/contrat/class/contrat.class.php"
case 'order_supplier':
$element = 'supplier_order';
break; // "/fourn/class/fournisseur.commande.class.php"
case 'invoice_supplier':
$element = 'supplier_invoice';
break; // "/fourn/class/fournisseur.facture.class.php"
}
if (is_object($mc)) {
$out = $mc->getEntity($element, $shared, $currentobject);
} else {
$out = '';
$addzero = array('user', 'usergroup', 'cronjob', 'c_email_templates', 'email_template', 'default_values', 'overwrite_trans');
if (in_array($element, $addzero)) {
$out .= '0,';
}
$out .= ((int) $conf->entity);
}
// Manipulate entities to query on the fly
$parameters = array(
'element' => $element,
'shared' => $shared,
'object' => $object,
'currentobject' => $currentobject,
'out' => $out
);
$reshook = $hookmanager->executeHooks('hookGetEntity', $parameters, $currentobject, $action); // Note that $action and $object may have been modified by some hooks
if (is_numeric($reshook)) {
if ($reshook == 0 && !empty($hookmanager->resPrint)) {
$out .= ','.$hookmanager->resPrint; // add
} elseif ($reshook == 1) {
$out = $hookmanager->resPrint; // replace
}
}
return $out;
}
/**
* Set entity id to use when to create an object
*
* @param object $currentobject Current object
* @return mixed Entity id to use ( eg. entity = '.setEntity($object) )
*/
function setEntity($currentobject)
{
global $conf, $mc;
if (is_object($mc) && method_exists($mc, 'setEntity')) {
return $mc->setEntity($currentobject);
} else {
return ((is_object($currentobject) && $currentobject->id > 0 && $currentobject->entity > 0) ? $currentobject->entity : $conf->entity);
}
}
/**
* Return if string has a name dedicated to store a secret
*
* @param string $keyname Name of key to test
* @return boolean True if key is used to store a secret
*/
function isASecretKey($keyname)
{
return preg_match('/(_pass|password|_pw|_key|securekey|serverkey|secret\d?|p12key|exportkey|_PW_[a-z]+|token)$/i', $keyname);
}
/**
* Return a numeric value into an Excel like column number. So 0 return 'A', 1 returns 'B'..., 26 return 'AA'
*
* @param int|string $n Numeric value
* @return string Column in Excel format
*/
function num2Alpha($n)
{
for ($r = ""; $n >= 0; $n = intval($n / 26) - 1) {
$r = chr($n % 26 + 0x41) . $r;
}
return $r;
}
/**
* Return information about user browser
*
* Returns array with the following format:
* array(
* 'browsername' => Browser name (firefox|chrome|iceweasel|epiphany|safari|opera|ie|unknown)
* 'browserversion' => Browser version. Empty if unknown
* 'browseros' => Set with mobile OS (android|blackberry|ios|palm|symbian|webos|maemo|windows|unknown)
* 'layout' => (tablet|phone|classic)
* 'phone' => empty if not mobile, (android|blackberry|ios|palm|unknown) if mobile
* 'tablet' => true/false
* )
*
* @param string $user_agent Content of $_SERVER["HTTP_USER_AGENT"] variable
* @return array Check function documentation
*/
function getBrowserInfo($user_agent)
{
include_once DOL_DOCUMENT_ROOT.'/includes/mobiledetect/mobiledetectlib/Mobile_Detect.php';
$name = 'unknown';
$version = '';
$os = 'unknown';
$phone = '';
$user_agent = substr($user_agent, 0, 512); // Avoid to process too large user agent
$detectmobile = new Mobile_Detect(null, $user_agent);
$tablet = $detectmobile->isTablet();
if ($detectmobile->isMobile()) {
$phone = 'unknown';
// If phone/smartphone, we set phone os name.
if ($detectmobile->is('AndroidOS')) {
$os = $phone = 'android';
} elseif ($detectmobile->is('BlackBerryOS')) {
$os = $phone = 'blackberry';
} elseif ($detectmobile->is('iOS')) {
$os = 'ios';
$phone = 'iphone';
} elseif ($detectmobile->is('PalmOS')) {
$os = $phone = 'palm';
} elseif ($detectmobile->is('SymbianOS')) {
$os = 'symbian';
} elseif ($detectmobile->is('webOS')) {
$os = 'webos';
} elseif ($detectmobile->is('MaemoOS')) {
$os = 'maemo';
} elseif ($detectmobile->is('WindowsMobileOS') || $detectmobile->is('WindowsPhoneOS')) {
$os = 'windows';
}
}
// OS
if (preg_match('/linux/i', $user_agent)) {
$os = 'linux';
} elseif (preg_match('/macintosh/i', $user_agent)) {
$os = 'macintosh';
} elseif (preg_match('/windows/i', $user_agent)) {
$os = 'windows';
}
// Name
$reg = array();
if (preg_match('/firefox(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
$name = 'firefox';
$version = empty($reg[2]) ? '' : $reg[2];
} elseif (preg_match('/edge(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
$name = 'edge';
$version = empty($reg[2]) ? '' : $reg[2];
} elseif (preg_match('/chrome(\/|\s)([\d\.]+)/i', $user_agent, $reg)) {
$name = 'chrome';
$version = empty($reg[2]) ? '' : $reg[2];
} elseif (preg_match('/chrome/i', $user_agent, $reg)) {
// we can have 'chrome (Mozilla...) chrome x.y' in one string
$name = 'chrome';
} elseif (preg_match('/iceweasel/i', $user_agent)) {
$name = 'iceweasel';
} elseif (preg_match('/epiphany/i', $user_agent)) {
$name = 'epiphany';
} elseif (preg_match('/safari(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
$name = 'safari';
$version = empty($reg[2]) ? '' : $reg[2];
} elseif (preg_match('/opera(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
// Safari is often present in string for mobile but its not.
$name = 'opera';
$version = empty($reg[2]) ? '' : $reg[2];
} elseif (preg_match('/(MSIE\s([0-9]+\.[0-9]))|.*(Trident\/[0-9]+.[0-9];.*rv:([0-9]+\.[0-9]+))/i', $user_agent, $reg)) {
$name = 'ie';
$version = end($reg);
} elseif (preg_match('/(Windows NT\s([0-9]+\.[0-9])).*(Trident\/[0-9]+.[0-9];.*rv:([0-9]+\.[0-9]+))/i', $user_agent, $reg)) {
// MS products at end
$name = 'ie';
$version = end($reg);
} elseif (preg_match('/l[iy]n(x|ks)(\(|\/|\s)*([\d\.]+)/i', $user_agent, $reg)) {
// MS products at end
$name = 'lynxlinks';
$version = empty($reg[3]) ? '' : $reg[3];
}
if ($tablet) {
$layout = 'tablet';
} elseif ($phone) {
$layout = 'phone';
} else {
$layout = 'classic';
}
return array(
'browsername' => $name,
'browserversion' => $version,
'browseros' => $os,
'browserua' => $user_agent,
'layout' => $layout, // tablet, phone, classic
'phone' => $phone, // deprecated
'tablet' => $tablet // deprecated
);
}
/**
* Function called at end of web php process
*
* @return void
*/
function dol_shutdown()
{
global $db;
$disconnectdone = false;
$depth = 0;
if (is_object($db) && !empty($db->connected)) {
$depth = $db->transaction_opened;
$disconnectdone = $db->close();
}
dol_syslog("--- End access to ".(empty($_SERVER["PHP_SELF"]) ? 'unknown' : $_SERVER["PHP_SELF"]).(($disconnectdone && $depth) ? ' (Warn: db disconnection forced, transaction depth was '.$depth.')' : ''), (($disconnectdone && $depth) ? LOG_WARNING : LOG_INFO));
}
/**
* Return true if we are in a context of submitting the parameter $paramname from a POST of a form.
* Warning:
* For action=add, use: $var = GETPOST('var'); // No GETPOSTISSET, so GETPOST always called and default value is retreived if not a form POST, and value of form is retreived if it is a form POST.
* For action=update, use: $var = GETPOSTISSET('var') ? GETPOST('var') : $object->var;
*
* @param string $paramname Name or parameter to test
* @return boolean True if we have just submit a POST or GET request with the parameter provided (even if param is empty)
*/
function GETPOSTISSET($paramname)
{
$isset = false;
$relativepathstring = $_SERVER["PHP_SELF"];
// Clean $relativepathstring
if (constant('DOL_URL_ROOT')) {
$relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
}
$relativepathstring = preg_replace('/^\//', '', $relativepathstring);
$relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
//var_dump($relativepathstring);
//var_dump($user->default_values);
// Code for search criteria persistence.
// Retrieve values if restore_lastsearch_values
if (!empty($_GET['restore_lastsearch_values'])) { // Use $_GET here and not GETPOST
if (!empty($_SESSION['lastsearch_values_'.$relativepathstring])) { // If there is saved values
$tmp = json_decode($_SESSION['lastsearch_values_'.$relativepathstring], true);
if (is_array($tmp)) {
foreach ($tmp as $key => $val) {
if ($key == $paramname) { // We are on the requested parameter
$isset = true;
break;
}
}
}
}
// If there is saved contextpage, limit, page or mode
if ($paramname == 'contextpage' && !empty($_SESSION['lastsearch_contextpage_'.$relativepathstring])) {
$isset = true;
} elseif ($paramname == 'limit' && !empty($_SESSION['lastsearch_limit_'.$relativepathstring])) {
$isset = true;
} elseif ($paramname == 'page' && !empty($_SESSION['lastsearch_page_'.$relativepathstring])) {
$isset = true;
} elseif ($paramname == 'mode' && !empty($_SESSION['lastsearch_mode_'.$relativepathstring])) {
$isset = true;
}
} else {
$isset = (isset($_POST[$paramname]) || isset($_GET[$paramname])); // We must keep $_POST and $_GET here
}
return $isset;
}
/**
* Return true if the parameter $paramname is submit from a POST OR GET as an array.
* Can be used before GETPOST to know if the $check param of GETPOST need to check an array or a string
*
* @param string $paramname Name or parameter to test
* @param int $method Type of method (0 = get then post, 1 = only get, 2 = only post, 3 = post then get)
* @return bool True if we have just submit a POST or GET request with the parameter provided (even if param is empty)
*/
function GETPOSTISARRAY($paramname, $method = 0)
{
// for $method test need return the same $val as GETPOST
if (empty($method)) {
$val = isset($_GET[$paramname]) ? $_GET[$paramname] : (isset($_POST[$paramname]) ? $_POST[$paramname] : '');
} elseif ($method == 1) {
$val = isset($_GET[$paramname]) ? $_GET[$paramname] : '';
} elseif ($method == 2) {
$val = isset($_POST[$paramname]) ? $_POST[$paramname] : '';
} elseif ($method == 3) {
$val = isset($_POST[$paramname]) ? $_POST[$paramname] : (isset($_GET[$paramname]) ? $_GET[$paramname] : '');
} else {
$val = 'BadFirstParameterForGETPOST';
}
return is_array($val);
}
/**
* Return value of a param into GET or POST supervariable.
* Use the property $user->default_values[path]['createform'] and/or $user->default_values[path]['filters'] and/or $user->default_values[path]['sortorder']
* Note: The property $user->default_values is loaded by main.php when loading the user.
*
* @param string $paramname Name of parameter to found
* @param string $check Type of check
* ''=no check (deprecated)
* 'none'=no check (only for param that should have very rich content like passwords)
* 'array', 'array:restricthtml' or 'array:aZ09' to check it's an array
* 'int'=check it's numeric (integer or float)
* 'intcomma'=check it's integer+comma ('1,2,3,4...')
* 'alpha'=Same than alphanohtml since v13
* 'alphawithlgt'=alpha with lgt
* 'alphanohtml'=check there is no html content and no " and no ../
* 'aZ'=check it's a-z only
* 'aZ09'=check it's simple alpha string (recommended for keys)
* 'aZ09arobase'=check it's a string for an element type
* 'aZ09comma'=check it's a string for a sortfield or sortorder
* 'san_alpha'=Use filter_var with FILTER_SANITIZE_STRING (do not use this for free text string)
* 'nohtml'=check there is no html content
* 'restricthtml'=check html content is restricted to some tags only
* 'custom'= custom filter specify $filter and $options)
* @param int $method Type of method (0 = get then post, 1 = only get, 2 = only post, 3 = post then get)
* @param int $filter Filter to apply when $check is set to 'custom'. (See http://php.net/manual/en/filter.filters.php for détails)
* @param mixed $options Options to pass to filter_var when $check is set to 'custom'
* @param string $noreplace Force disable of replacement of __xxx__ strings.
* @return string|array Value found (string or array), or '' if check fails
*/
function GETPOST($paramname, $check = 'alphanohtml', $method = 0, $filter = null, $options = null, $noreplace = 0)
{
global $mysoc, $user, $conf;
if (empty($paramname)) {
return 'BadFirstParameterForGETPOST';
}
if (empty($check)) {
dol_syslog("Deprecated use of GETPOST, called with 1st param = ".$paramname." and a 2nd param that is '', when calling page ".$_SERVER["PHP_SELF"], LOG_WARNING);
// Enable this line to know who call the GETPOST with '' $check parameter.
//var_dump(debug_backtrace()[0]);
}
if (empty($method)) {
$out = isset($_GET[$paramname]) ? $_GET[$paramname] : (isset($_POST[$paramname]) ? $_POST[$paramname] : '');
} elseif ($method == 1) {
$out = isset($_GET[$paramname]) ? $_GET[$paramname] : '';
} elseif ($method == 2) {
$out = isset($_POST[$paramname]) ? $_POST[$paramname] : '';
} elseif ($method == 3) {
$out = isset($_POST[$paramname]) ? $_POST[$paramname] : (isset($_GET[$paramname]) ? $_GET[$paramname] : '');
} else {
return 'BadThirdParameterForGETPOST';
}
if (empty($method) || $method == 3 || $method == 4) {
$relativepathstring = (empty($_SERVER["PHP_SELF"]) ? '' : $_SERVER["PHP_SELF"]);
// Clean $relativepathstring
if (constant('DOL_URL_ROOT')) {
$relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
}
$relativepathstring = preg_replace('/^\//', '', $relativepathstring);
$relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
//var_dump($relativepathstring);
//var_dump($user->default_values);
// Code for search criteria persistence.
// Retrieve saved values if restore_lastsearch_values is set
if (!empty($_GET['restore_lastsearch_values'])) { // Use $_GET here and not GETPOST
if (!empty($_SESSION['lastsearch_values_'.$relativepathstring])) { // If there is saved values
$tmp = json_decode($_SESSION['lastsearch_values_'.$relativepathstring], true);
if (is_array($tmp)) {
foreach ($tmp as $key => $val) {
if ($key == $paramname) { // We are on the requested parameter
$out = $val;
break;
}
}
}
}
// If there is saved contextpage, page or limit
if ($paramname == 'contextpage' && !empty($_SESSION['lastsearch_contextpage_'.$relativepathstring])) {
$out = $_SESSION['lastsearch_contextpage_'.$relativepathstring];
} elseif ($paramname == 'limit' && !empty($_SESSION['lastsearch_limit_'.$relativepathstring])) {
$out = $_SESSION['lastsearch_limit_'.$relativepathstring];
} elseif ($paramname == 'page' && !empty($_SESSION['lastsearch_page_'.$relativepathstring])) {
$out = $_SESSION['lastsearch_page_'.$relativepathstring];
} elseif ($paramname == 'mode' && !empty($_SESSION['lastsearch_mode_'.$relativepathstring])) {
$out = $_SESSION['lastsearch_mode_'.$relativepathstring];
}
} elseif (!isset($_GET['sortfield'])) {
// Else, retrieve default values if we are not doing a sort
// If we did a click on a field to sort, we do no apply default values. Same if option MAIN_ENABLE_DEFAULT_VALUES is not set
if (!empty($_GET['action']) && $_GET['action'] == 'create' && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) {
// Search default value from $object->field
global $object;
if (is_object($object) && isset($object->fields[$paramname]['default'])) {
$out = $object->fields[$paramname]['default'];
}
}
if (getDolGlobalString('MAIN_ENABLE_DEFAULT_VALUES')) {
if (!empty($_GET['action']) && (preg_match('/^create/', $_GET['action']) || preg_match('/^presend/', $_GET['action'])) && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) {
// Now search in setup to overwrite default values
if (!empty($user->default_values)) { // $user->default_values defined from menu 'Setup - Default values'
if (isset($user->default_values[$relativepathstring]['createform'])) {
foreach ($user->default_values[$relativepathstring]['createform'] as $defkey => $defval) {
$qualified = 0;
if ($defkey != '_noquery_') {
$tmpqueryarraytohave = explode('&', $defkey);
$tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
$foundintru = 0;
foreach ($tmpqueryarraytohave as $tmpquerytohave) {
if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
$foundintru = 1;
}
}
if (!$foundintru) {
$qualified = 1;
}
//var_dump($defkey.'-'.$qualified);
} else {
$qualified = 1;
}
if ($qualified) {
if (isset($user->default_values[$relativepathstring]['createform'][$defkey][$paramname])) {
$out = $user->default_values[$relativepathstring]['createform'][$defkey][$paramname];
break;
}
}
}
}
}
} elseif (!empty($paramname) && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) {
// Management of default search_filters and sort order
if (!empty($user->default_values)) {
// $user->default_values defined from menu 'Setup - Default values'
//var_dump($user->default_values[$relativepathstring]);
if ($paramname == 'sortfield' || $paramname == 'sortorder') {
// Sorted on which fields ? ASC or DESC ?
if (isset($user->default_values[$relativepathstring]['sortorder'])) {
// Even if paramname is sortfield, data are stored into ['sortorder...']
foreach ($user->default_values[$relativepathstring]['sortorder'] as $defkey => $defval) {
$qualified = 0;
if ($defkey != '_noquery_') {
$tmpqueryarraytohave = explode('&', $defkey);
$tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
$foundintru = 0;
foreach ($tmpqueryarraytohave as $tmpquerytohave) {
if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
$foundintru = 1;
}
}
if (!$foundintru) {
$qualified = 1;
}
//var_dump($defkey.'-'.$qualified);
} else {
$qualified = 1;
}
if ($qualified) {
$forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
foreach ($user->default_values[$relativepathstring]['sortorder'][$defkey] as $key => $val) {
if ($out) {
$out .= ', ';
}
if ($paramname == 'sortfield') {
$out .= dol_string_nospecial($key, '', $forbidden_chars_to_replace);
}
if ($paramname == 'sortorder') {
$out .= dol_string_nospecial($val, '', $forbidden_chars_to_replace);
}
}
//break; // No break for sortfield and sortorder so we can cumulate fields (is it realy usefull ?)
}
}
}
} elseif (isset($user->default_values[$relativepathstring]['filters'])) {
foreach ($user->default_values[$relativepathstring]['filters'] as $defkey => $defval) { // $defkey is a querystring like 'a=b&c=d', $defval is key of user
if (!empty($_GET['disabledefaultvalues'])) { // If set of default values has been disabled by a request parameter
continue;
}
$qualified = 0;
if ($defkey != '_noquery_') {
$tmpqueryarraytohave = explode('&', $defkey);
$tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
$foundintru = 0;
foreach ($tmpqueryarraytohave as $tmpquerytohave) {
if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
$foundintru = 1;
}
}
if (!$foundintru) {
$qualified = 1;
}
//var_dump($defkey.'-'.$qualified);
} else {
$qualified = 1;
}
if ($qualified && isset($user->default_values[$relativepathstring]['filters'][$defkey][$paramname])) {
// We must keep $_POST and $_GET here
if (isset($_POST['sall']) || isset($_POST['search_all']) || isset($_GET['sall']) || isset($_GET['search_all'])) {
// We made a search from quick search menu, do we still use default filter ?
if (!getDolGlobalString('MAIN_DISABLE_DEFAULT_FILTER_FOR_QUICK_SEARCH')) {
$forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
$out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace);
}
} else {
$forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
$out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace);
}
break;
}
}
}
}
}
}
}
}
// Substitution variables for GETPOST (used to get final url with variable parameters or final default value, when using variable parameters __XXX__ in the GET URL)
// Example of variables: __DAY__, __MONTH__, __YEAR__, __MYCOMPANY_COUNTRY_ID__, __USER_ID__, ...
// We do this only if var is a GET. If it is a POST, may be we want to post the text with vars as the setup text.
if (!is_array($out) && empty($_POST[$paramname]) && empty($noreplace)) {
$reg = array();
$maxloop = 20;
$loopnb = 0; // Protection against infinite loop
while (preg_match('/__([A-Z0-9]+_?[A-Z0-9]+)__/i', $out, $reg) && ($loopnb < $maxloop)) { // Detect '__ABCDEF__' as key 'ABCDEF' and '__ABC_DEF__' as key 'ABC_DEF'. Detection is also correct when 2 vars are side by side.
$loopnb++;
$newout = '';
if ($reg[1] == 'DAY') {
$tmp = dol_getdate(dol_now(), true);
$newout = $tmp['mday'];
} elseif ($reg[1] == 'MONTH') {
$tmp = dol_getdate(dol_now(), true);
$newout = $tmp['mon'];
} elseif ($reg[1] == 'YEAR') {
$tmp = dol_getdate(dol_now(), true);
$newout = $tmp['year'];
} elseif ($reg[1] == 'PREVIOUS_DAY') {
$tmp = dol_getdate(dol_now(), true);
$tmp2 = dol_get_prev_day($tmp['mday'], $tmp['mon'], $tmp['year']);
$newout = $tmp2['day'];
} elseif ($reg[1] == 'PREVIOUS_MONTH') {
$tmp = dol_getdate(dol_now(), true);
$tmp2 = dol_get_prev_month($tmp['mon'], $tmp['year']);
$newout = $tmp2['month'];
} elseif ($reg[1] == 'PREVIOUS_YEAR') {
$tmp = dol_getdate(dol_now(), true);
$newout = ($tmp['year'] - 1);
} elseif ($reg[1] == 'NEXT_DAY') {
$tmp = dol_getdate(dol_now(), true);
$tmp2 = dol_get_next_day($tmp['mday'], $tmp['mon'], $tmp['year']);
$newout = $tmp2['day'];
} elseif ($reg[1] == 'NEXT_MONTH') {
$tmp = dol_getdate(dol_now(), true);
$tmp2 = dol_get_next_month($tmp['mon'], $tmp['year']);
$newout = $tmp2['month'];
} elseif ($reg[1] == 'NEXT_YEAR') {
$tmp = dol_getdate(dol_now(), true);
$newout = ($tmp['year'] + 1);
} elseif ($reg[1] == 'MYCOMPANY_COUNTRY_ID' || $reg[1] == 'MYCOUNTRY_ID' || $reg[1] == 'MYCOUNTRYID') {
$newout = $mysoc->country_id;
} elseif ($reg[1] == 'USER_ID' || $reg[1] == 'USERID') {
$newout = $user->id;
} elseif ($reg[1] == 'USER_SUPERVISOR_ID' || $reg[1] == 'SUPERVISOR_ID' || $reg[1] == 'SUPERVISORID') {
$newout = $user->fk_user;
} elseif ($reg[1] == 'ENTITY_ID' || $reg[1] == 'ENTITYID') {
$newout = $conf->entity;
} else {
$newout = ''; // Key not found, we replace with empty string
}
//var_dump('__'.$reg[1].'__ -> '.$newout);
$out = preg_replace('/__'.preg_quote($reg[1], '/').'__/', $newout, $out);
}
}
// Check type of variable and make sanitization according to this
if (preg_match('/^array/', $check)) { // If 'array' or 'array:restricthtml' or 'array:aZ09' or 'array:intcomma'
if (!is_array($out) || empty($out)) {
$out = array();
} else {
$tmparray = explode(':', $check);
if (!empty($tmparray[1])) {
$tmpcheck = $tmparray[1];
} else {
$tmpcheck = 'alphanohtml';
}
foreach ($out as $outkey => $outval) {
$out[$outkey] = sanitizeVal($outval, $tmpcheck, $filter, $options);
}
}
} else {
// If field name is 'search_xxx' then we force the add of space after each < and > (when following char is numeric) because it means
// we use the < or > to make a search on a numeric value to do higher or lower so we can add a space to break html tags
if (strpos($paramname, 'search_') === 0) {
$out = preg_replace('/([<>])([-+]?\d)/', '\1 \2', $out);
}
$out = sanitizeVal($out, $check, $filter, $options);
}
// Sanitizing for special parameters.
// Note: There is no reason to allow the backtopage, backtolist or backtourl parameter to contains an external URL. Only relative URLs are allowed.
if ($paramname == 'backtopage' || $paramname == 'backtolist' || $paramname == 'backtourl') {
$out = str_replace('\\', '/', $out); // Can be before the loop because only 1 char is replaced. No risk to get it after other replacements.
$out = str_replace(array(':', ';', '@', "\t", ' '), '', $out); // Can be before the loop because only 1 char is replaced. No risk to retreive it after other replacements.
do {
$oldstringtoclean = $out;
$out = str_ireplace(array('javascript', 'vbscript', '&colon', '&#'), '', $out);
$out = preg_replace(array('/^[^\?]*%/'), '', $out); // We remove any % chars before the ?. Example in url: '/product/stock/card.php?action=create&backtopage=%2Fdolibarr_dev%2Fhtdocs%2Fpro%25duct%2Fcard.php%3Fid%3Dabc'
$out = preg_replace(array('/^[a-z]*\/\s*\/+/i'), '', $out); // We remove schema*// to remove external URL
} while ($oldstringtoclean != $out);
}
// Code for search criteria persistence.
// Save data into session if key start with 'search_' or is 'smonth', 'syear', 'month', 'year'
if (empty($method) || $method == 3 || $method == 4) {
if (preg_match('/^search_/', $paramname) || in_array($paramname, array('sortorder', 'sortfield'))) {
//var_dump($paramname.' - '.$out.' '.$user->default_values[$relativepathstring]['filters'][$paramname]);
// We save search key only if $out not empty that means:
// - posted value not empty, or
// - if posted value is empty and a default value exists that is not empty (it means we did a filter to an empty value when default was not).
if ($out != '' && isset($user)) {// $out = '0' or 'abc', it is a search criteria to keep
$user->lastsearch_values_tmp[$relativepathstring][$paramname] = $out;
}
}
}
return $out;
}
/**
* Return value of a param into GET or POST supervariable.
* Use the property $user->default_values[path]['creatform'] and/or $user->default_values[path]['filters'] and/or $user->default_values[path]['sortorder']
* Note: The property $user->default_values is loaded by main.php when loading the user.
*
* @param string $paramname Name of parameter to found
* @param int $method Type of method (0 = get then post, 1 = only get, 2 = only post, 3 = post then get)
* @return int Value found (int)
*/
function GETPOSTINT($paramname, $method = 0)
{
return (int) GETPOST($paramname, 'int', $method, null, null, 0);
}
/**
* Return a sanitized or empty value after checking value against a rule.
*
* @deprecated
* @param string|array $out Value to check/clear.
* @param string $check Type of check/sanitizing
* @param int $filter Filter to apply when $check is set to 'custom'. (See http://php.net/manual/en/filter.filters.php for détails)
* @param mixed $options Options to pass to filter_var when $check is set to 'custom'
* @return string|array Value sanitized (string or array). It may be '' if format check fails.
*/
function checkVal($out = '', $check = 'alphanohtml', $filter = null, $options = null)
{
return sanitizeVal($out, $check, $filter, $options);
}
/**
* Return a sanitized or empty value after checking value against a rule.
*
* @param string|array $out Value to check/clear.
* @param string $check Type of check/sanitizing
* @param int $filter Filter to apply when $check is set to 'custom'. (See http://php.net/manual/en/filter.filters.php for détails)
* @param mixed $options Options to pass to filter_var when $check is set to 'custom'
* @return string|array Value sanitized (string or array). It may be '' if format check fails.
*/
function sanitizeVal($out = '', $check = 'alphanohtml', $filter = null, $options = null)
{
// TODO : use class "Validate" to perform tests (and add missing tests) if needed for factorize
// Check is done after replacement
switch ($check) {
case 'none':
break;
case 'int': // Check param is a numeric value (integer but also float or hexadecimal)
if (!is_numeric($out)) {
$out = '';
}
break;
case 'intcomma':
if (is_array($out)) {
$out = implode(',', $out);
}
if (preg_match('/[^0-9,-]+/i', $out)) {
$out = '';
}
break;
case 'san_alpha':
$out = filter_var($out, FILTER_SANITIZE_STRING);
break;
case 'email':
$out = filter_var($out, FILTER_SANITIZE_EMAIL);
break;
case 'aZ':
if (!is_array($out)) {
$out = trim($out);
if (preg_match('/[^a-z]+/i', $out)) {
$out = '';
}
}