Passed
Push — master ( 043752...2a5ce0 )
by Alxarafe
27:58
created

htdocs/core/modules/DolibarrModules.class.php (2 issues)

1
<?php
2
/* Copyright (C) 2003-2007  Rodolphe Quiedeville    <[email protected]>
3
 * Copyright (C) 2004       Sebastien Di Cintio     <[email protected]>
4
 * Copyright (C) 2004       Benoit Mortier          <[email protected]>
5
 * Copyright (C) 2004       Eric Seigne             <[email protected]>
6
 * Copyright (C) 2005-2013  Laurent Destailleur     <[email protected]>
7
 * Copyright (C) 2005-2012  Regis Houssin           <[email protected]>
8
 * Copyright (C) 2014       Raphaël Doursenaud      <[email protected]>
9
 * Copyright (C) 2018       Josep Lluís Amador      <[email protected]>
10
 *
11
 * This program is free software; you can redistribute it and/or modify
12
 * it under the terms of the GNU General Public License as published by
13
 * the Free Software Foundation; either version 3 of the License, or
14
 * (at your option) any later version.
15
 *
16
 * This program is distributed in the hope that it will be useful,
17
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19
 * GNU General Public License for more details.
20
 *
21
 * You should have received a copy of the GNU General Public License
22
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
23
 */
24
25
/**
26
 * \file           htdocs/core/modules/DolibarrModules.class.php
27
 * \brief          File of parent class of module descriptor class files
28
 */
29
30
31
/**
32
 * Class DolibarrModules
33
 *
34
 * Parent class for module descriptor class files
35
 */
36
class DolibarrModules // Can not be abstract, because we need to instantiate it into unActivateModule to be able to disable a module whose files were removed.
37
{
38
    /**
39
     * @var DoliDb Database handler
40
     */
41
    public $db;
42
43
    /**
44
     * @var int Module unique ID
45
     * @see https://wiki.dolibarr.org/index.php/List_of_modules_id
46
     */
47
    public $numero;
48
49
    /**
50
     * @var   string Publisher name
51
     * @since 4.0.0
52
     */
53
    public $editor_name;
54
55
    /**
56
     * @var   string URL of module at publisher site
57
     * @since 4.0.0
58
     */
59
    public $editor_url;
60
61
    /**
62
     * @var string Family
63
     * @see familyinfo
64
     *
65
     * Native values: 'crm', 'financial', 'hr', 'projects', 'products', 'ecm', 'technic', 'other'.
66
     * Use familyinfo to declare a custom value.
67
     */
68
    public $family;
69
70
    /**
71
     * @var array Custom family informations
72
     * @see family
73
     *
74
     * e.g.:
75
     * array(
76
     *     'myownfamily' => array(
77
     *         'position' => '001',
78
     *         'label' => $langs->trans("MyOwnFamily")
79
     *     )
80
     * );
81
     */
82
    public $familyinfo;
83
84
    /**
85
     * @var string    Module position on 2 digits
86
     */
87
    public $module_position='50';
88
89
    /**
90
     * @var string Module name
91
     *
92
     * Only used if Module[ID]Name translation string is not found.
93
     *
94
     * You can use the following code to automatically derive it from your module's class name:
95
     * preg_replace('/^mod/i', '', get_class($this))
96
     */
97
    public $name;
98
99
    /**
100
     * @var string[] Paths to create when module is activated
101
     *
102
     * e.g.: array('/mymodule/temp')
103
     */
104
    public $dirs = array();
105
106
    /**
107
     * @var array Module boxes
108
     */
109
    public $boxes = array();
110
111
    /**
112
     * @var array Module constants
113
     */
114
    public $const = array();
115
116
    /**
117
     * @var array Module cron jobs entries
118
     */
119
    public $cronjobs = array();
120
121
    /**
122
     * @var array Module access rights
123
     */
124
    public $rights;
125
126
    /**
127
     * @var string Module access rights family
128
     */
129
    public $rights_class;
130
131
    /**
132
     * @var array Module menu entries
133
     */
134
    public $menu = array();
135
136
    /**
137
     * @var array Module parts
138
     *  array(
139
     *      // Set this to 1 if module has its own trigger directory (/mymodule/core/triggers)
140
     *      'triggers' => 0,
141
     *      // Set this to 1 if module has its own login method directory (/mymodule/core/login)
142
     *      'login' => 0,
143
     *      // Set this to 1 if module has its own substitution function file (/mymodule/core/substitutions)
144
     *      'substitutions' => 0,
145
     *      // Set this to 1 if module has its own menus handler directory (/mymodule/core/menus)
146
     *      'menus' => 0,
147
     *      // Set this to 1 if module has its own theme directory (/mymodule/theme)
148
     *      'theme' => 0,
149
     *      // Set this to 1 if module overwrite template dir (/mymodule/core/tpl)
150
     *      'tpl' => 0,
151
     *      // Set this to 1 if module has its own barcode directory (/mymodule/core/modules/barcode)
152
     *      'barcode' => 0,
153
     *      // Set this to 1 if module has its own models directory (/mymodule/core/modules/xxx)
154
     *      'models' => 0,
155
     *      // Set this to relative path of css file if module has its own css file
156
     *      'css' => '/mymodule/css/mymodule.css.php',
157
     *      // Set this to relative path of js file if module must load a js on all pages
158
     *      'js' => '/mymodule/js/mymodule.js',
159
     *      // Set here all hooks context managed by module
160
     *      'hooks' => array('hookcontext1','hookcontext2')
161
     *  )
162
     */
163
    public $module_parts = array();
164
165
    /**
166
     * @var        string Module documents ?
167
     * @deprecated Seems unused anywhere
168
     */
169
    public $docs;
170
171
    /**
172
     * @var        string ?
173
     * @deprecated Seems unused anywhere
174
     */
175
    public $dbversion = "-";
176
177
    /**
178
     * @var string Error message
179
     */
180
    public $error;
181
182
    /**
183
     * @var string Module version
184
     * @see http://semver.org
185
     *
186
     * The following keywords can also be used:
187
     * 'development'
188
     * 'experimental'
189
     * 'dolibarr': only for core modules that share its version
190
     * 'dolibarr_deprecated': only for deprecated core modules
191
     */
192
    public $version;
193
194
    /**
195
     * @var string Module description (short text)
196
     *
197
     * Only used if Module[ID]Desc translation string is not found.
198
     */
199
    public $description;
200
201
    /**
202
     * @var   string Module description (long text)
203
     * @since 4.0.0
204
     *
205
     * HTML content supported.
206
     */
207
    public $descriptionlong;
208
209
210
    // For exports
211
212
    /**
213
     * @var string Module export code
214
     */
215
    public $export_code;
216
217
    /**
218
     * @var string Module export label
219
     */
220
    public $export_label;
221
222
    public $export_permission;
223
    public $export_fields_array;
224
    public $export_TypeFields_array;
225
    public $export_entities_array;
226
    public $export_special_array;           // special or computed field
227
    public $export_dependencies_array;
228
    public $export_sql_start;
229
    public $export_sql_end;
230
    public $export_sql_order;
231
232
233
    // For import
234
235
    /**
236
     * @var string Module import code
237
     */
238
    public $import_code;
239
240
    /**
241
     * @var string Module import label
242
     */
243
    public $import_label;
244
245
246
    /**
247
     * @var string Module constant name
248
     */
249
    public $const_name;
250
251
    /**
252
     * @var bool Module can't be disabled
253
     */
254
    public $always_enabled;
255
256
    /**
257
     * @var int Module is enabled globally (Multicompany support)
258
     */
259
    public $core_enabled;
260
261
    /**
262
     * @var        string Relative path to module style sheet
263
     * @deprecated
264
     * @see        module_parts
265
     */
266
    public $style_sheet = '';
267
268
    /**
269
     * @var        0|1|2|3 Where to display the module in setup page
270
     * @deprecated @since 4.0.0
271
     * @see        family
272
     * @see        familyinfo
273
     *
274
     * 0: common
275
     * 1: interface
276
     * 2: others
277
     * 3: very specific
278
     */
279
    public $special;
280
281
    /**
282
     * @var string Name of image file used for this module
283
     *
284
     * If file is in theme/yourtheme/img directory under name object_pictoname.png use 'pictoname'
285
     * If file is in module/img directory under name object_pictoname.png use 'pictoname@module'
286
     */
287
    public $picto;
288
289
    /**
290
     * @var string[] List of config pages
291
     *
292
     * Name of php pages stored into module/admin directory, used to setup module.
293
     * e.g.: "admin.php@module"
294
     */
295
    public $config_page_url;
296
297
298
    /**
299
     * @var string[] List of module class names that must be enabled if this module is enabled.
300
     *
301
     * e.g.: array('modAnotherModule', 'FR'=>'modYetAnotherModule')
302
     */
303
    public $depends;
304
305
    /**
306
     * @var int[] List of module ids to disable if this one is disabled.
307
     */
308
    public $requiredby;
309
310
    /**
311
     * @var string[] List of module class names as string this module is in conflict with.
312
     * @see depends
313
     */
314
    public $conflictwith;
315
316
    /**
317
     * @var string[] Module language files
318
     */
319
    public $langfiles;
320
321
    /**
322
     * @var array<string,string> Array of warnings to show when we activate the module
323
     *
324
     * array('always'='text') or array('FR'='text')
325
     */
326
    public $warnings_activation;
327
328
    /**
329
     * @var array<string,string> Array of warnings to show when we activate an external module
330
     *
331
     * array('always'='text') or array('FR'='text')
332
     */
333
    public $warnings_activation_ext;
334
335
336
    /**
337
     * @var array() Minimum version of PHP required by module.
338
     * e.g.: PHP ≥ 5.4 = array(5, 4)
339
     */
340
    public $phpmin;
341
342
    /**
343
     * @var array Minimum version of Dolibarr required by module.
344
     * e.g.: Dolibarr ≥ 3.6 = array(3, 6)
345
     */
346
    public $need_dolibarr_version;
347
348
    /**
349
     * @var bool Whether to hide the module.
350
     */
351
    public $hidden = false;
352
353
354
355
356
357
    /**
358
     * Constructor. Define names, constants, directories, boxes, permissions
359
     *
360
     * @param DoliDB $db Database handler
361
     */
362
    public function __construct($db)
363
    {
364
        $this->db = $db;
365
    }
366
    // We should but can't set this as abstract because this will make dolibarr hang
367
    // after migration due to old module not implementing. We must wait PHP is able to make
368
    // a try catch on Fatal error to manage this correctly.
369
    // We need constructor into function unActivateModule into admin.lib.php
370
371
372
    /**
373
     * Enables a module.
374
     * Inserts all informations into database
375
     *
376
     * @param array  $array_sql SQL requests to be executed when enabling module
377
     * @param string $options   String with options when disabling module:
378
     *                          - 'noboxes' = Do not insert boxes -
379
     *                          'newboxdefonly' = For boxes, insert def of
380
     *                          boxes only and not boxes activation
381
     *
382
     * @return int                         1 if OK, 0 if KO
383
     */
384
    function _init($array_sql, $options='')
385
    {
386
        global $conf;
387
        $err=0;
388
389
        $this->db->begin();
390
391
        // Insert activation module constant
392
        if (! $err) { $err+=$this->_active();
393
        }
394
395
        // Insert new pages for tabs (into llx_const)
396
        if (! $err) { $err+=$this->insert_tabs();
397
        }
398
399
        // Insert activation of module's parts
400
        if (! $err) { $err+=$this->insert_module_parts();
401
        }
402
403
        // Insert constant defined by modules (into llx_const)
404
        if (! $err && ! preg_match('/newboxdefonly/', $options)) { $err+=$this->insert_const();    // Test on newboxdefonly to avoid to erase value during upgrade
405
        }
406
407
        // Insert boxes def into llx_boxes_def and boxes setup (into llx_boxes)
408
        if (! $err && ! preg_match('/noboxes/', $options)) { $err+=$this->insert_boxes($options);
409
        }
410
411
        // Insert cron job entries (entry in llx_cronjobs)
412
        if (! $err) { $err+=$this->insert_cronjobs();
413
        }
414
415
        // Insert permission definitions of module into llx_rights_def. If user is admin, grant this permission to user.
416
        if (! $err) { $err+=$this->insert_permissions(1, null, 1);
417
        }
418
419
        // Insert specific menus entries into database
420
        if (! $err) { $err+=$this->insert_menus();
421
        }
422
423
        // Create module's directories
424
        if (! $err) { $err+=$this->create_dirs();
425
        }
426
427
        // Execute addons requests
428
        $num=count($array_sql);
429
        for ($i = 0; $i < $num; $i++)
430
        {
431
            if (! $err) {
432
                $val=$array_sql[$i];
433
                $sql=$val;
434
                $ignoreerror=0;
435
                if (is_array($val)) {
436
                    $sql=$val['sql'];
437
                    $ignoreerror=$val['ignoreerror'];
438
                }
439
                // Add current entity id
440
                $sql=str_replace('__ENTITY__', $conf->entity, $sql);
441
442
                dol_syslog(get_class($this)."::_init ignoreerror=".$ignoreerror."", LOG_DEBUG);
443
                $result=$this->db->query($sql, $ignoreerror);
444
                if (! $result) {
445
                    if (! $ignoreerror) {
446
                         $this->error=$this->db->lasterror();
447
                         $err++;
448
                    }
449
                    else
450
                    {
451
                         dol_syslog(get_class($this)."::_init Warning ".$this->db->lasterror(), LOG_WARNING);
452
                    }
453
                }
454
            }
455
        }
456
457
        // Return code
458
        if (! $err) {
459
            $this->db->commit();
460
            return 1;
461
        }
462
        else
463
        {
464
            $this->db->rollback();
465
            return 0;
466
        }
467
    }
468
469
    /**
470
     * Disable function. Deletes the module constants and boxes from the database.
471
     *
472
     * @param string[] $array_sql SQL requests to be executed when module is disabled
473
     * @param string   $options   Options when disabling module:
474
     *
475
     * @return int                     1 if OK, 0 if KO
476
     */
477
    function _remove($array_sql, $options='')
478
    {
479
        $err=0;
480
481
        $this->db->begin();
482
483
        // Remove activation module line (constant MAIN_MODULE_MYMODULE in llx_const)
484
        if (! $err) { $err+=$this->_unactive();
485
        }
486
487
        // Remove activation of module's new tabs (MAIN_MODULE_MYMODULE_TABS_XXX in llx_const)
488
        if (! $err) { $err+=$this->delete_tabs();
489
        }
490
491
        // Remove activation of module's parts (MAIN_MODULE_MYMODULE_XXX in llx_const)
492
        if (! $err) { $err+=$this->delete_module_parts();
493
        }
494
495
        // Remove constants defined by modules
496
        if (! $err) { $err+=$this->delete_const();
497
        }
498
499
        // Remove list of module's available boxes (entry in llx_boxes)
500
        if (! $err && ! preg_match('/(newboxdefonly|noboxes)/', $options)) { $err+=$this->delete_boxes();    // We don't have to delete if option ask to keep boxes safe or ask to add new box def only
501
        }
502
503
        // Remove list of module's cron job entries (entry in llx_cronjobs)
504
        if (! $err) { $err+=$this->delete_cronjobs();
505
        }
506
507
        // Remove module's permissions from list of available permissions (entries in llx_rights_def)
508
        if (! $err) { $err+=$this->delete_permissions();
509
        }
510
511
        // Remove module's menus (entries in llx_menu)
512
        if (! $err) { $err+=$this->delete_menus();
513
        }
514
515
        // Remove module's directories
516
        if (! $err) { $err+=$this->delete_dirs();
517
        }
518
519
        // Run complementary sql requests
520
        $num=count($array_sql);
521
        for ($i = 0; $i < $num; $i++)
522
        {
523
            if (! $err) {
524
                dol_syslog(get_class($this)."::_remove", LOG_DEBUG);
525
                $result=$this->db->query($array_sql[$i]);
526
                if (! $result) {
527
                    $this->error=$this->db->error();
528
                    $err++;
529
                }
530
            }
531
        }
532
533
        // Return code
534
        if (! $err) {
535
            $this->db->commit();
536
            return 1;
537
        }
538
        else
539
        {
540
            $this->db->rollback();
541
            return 0;
542
        }
543
    }
544
545
546
    /**
547
     * Gives the translated module name if translation exists in admin.lang or into language files of module.
548
     * Otherwise return the module key name.
549
     *
550
     * @return string  Translated module name
551
     */
552
    function getName()
553
    {
554
        global $langs;
555
        $langs->load("admin");
556
557
        if ($langs->transnoentitiesnoconv("Module".$this->numero."Name") != ("Module".$this->numero."Name")) {
558
            // If module name translation exists
559
            return $langs->transnoentitiesnoconv("Module".$this->numero."Name");
560
        }
561
        else
562
        {
563
            // If module name translation using it's unique id does not exist, we try to use its name to find translation
564
            if (is_array($this->langfiles)) {
565
                foreach($this->langfiles as $val)
566
                {
567
                    if ($val) { $langs->load($val);
568
                    }
569
                }
570
            }
571
572
            if ($langs->trans("Module".$this->name."Name") != ("Module".$this->name."Name")) {
573
                // If module name translation exists
574
                return $langs->transnoentitiesnoconv("Module".$this->name."Name");
575
            }
576
577
            // Last chance with simple label
578
            return $langs->transnoentitiesnoconv($this->name);
579
        }
580
    }
581
582
583
    /**
584
     * Gives the translated module description if translation exists in admin.lang or the default module description
585
     *
586
     * @return string  Translated module description
587
     */
588
    function getDesc()
589
    {
590
        global $langs;
591
        $langs->load("admin");
592
593
        if ($langs->transnoentitiesnoconv("Module".$this->numero."Desc") != ("Module".$this->numero."Desc")) {
594
            // If module description translation exists
595
            return $langs->transnoentitiesnoconv("Module".$this->numero."Desc");
596
        }
597
        else
598
        {
599
            // If module description translation does not exist using its unique id, we can use its name to find translation
600
            if (is_array($this->langfiles)) {
601
                foreach($this->langfiles as $val)
602
                {
603
                    if ($val) { $langs->load($val);
604
                    }
605
                }
606
            }
607
608
            if ($langs->transnoentitiesnoconv("Module".$this->name."Desc") != ("Module".$this->name."Desc")) {
609
                // If module name translation exists
610
                return $langs->trans("Module".$this->name."Desc");
611
            }
612
613
            // Last chance with simple label
614
            return $langs->trans($this->description);
615
        }
616
    }
617
618
    /**
619
     * Gives the long description of a module. First check README-la_LA.md then README.md
620
     * If no markdown files found, it returns translated value of the key ->descriptionlong.
621
     *
622
     * @return string     Long description of a module from README.md of from property.
623
     */
624
    function getDescLong()
625
    {
626
        global $langs;
627
        $langs->load("admin");
628
629
        include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
630
        include_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php';
631
632
        $pathoffile = $this->getDescLongReadmeFound();
633
634
        if ($pathoffile)     // Mostly for external modules
635
        {
636
            $content = file_get_contents($pathoffile);
637
638
            if ((float) DOL_VERSION >= 6.0) {
639
                @include_once DOL_DOCUMENT_ROOT.'/core/lib/parsemd.lib.php';
640
641
                $content = dolMd2Html(
642
                    $content, 'parsedown',
643
                    array(
644
                    'doc/'=>dol_buildpath(strtolower($this->name).'/doc/', 1),
645
                    'img/'=>dol_buildpath(strtolower($this->name).'/img/', 1),
646
                    'images/'=>dol_buildpath(strtolower($this->name).'/imgages/', 1),
647
                    )
648
                );
649
            }
650
            else
651
            {
652
                $content = nl2br($content);
653
            }
654
        }
655
        else                // Mostly for internal modules
656
        {
657
            if (! empty($this->descriptionlong)) {
658
                if (is_array($this->langfiles)) {
659
                    foreach($this->langfiles as $val)
660
                    {
661
                        if ($val) { $langs->load($val);
662
                        }
663
                    }
664
                }
665
666
                $content = $langs->transnoentitiesnoconv($this->descriptionlong);
667
            }
668
        }
669
670
        return $content;
671
    }
672
673
    /**
674
     * Return path of file if a README file was found.
675
     *
676
     * @return string      Path of file if a README file was found.
677
     */
678
    function getDescLongReadmeFound()
679
    {
680
        global $langs;
681
682
        $filefound= false;
683
684
        // Define path to file README.md.
685
        // First check README-la_LA.md then README-la.md then README.md
686
        $pathoffile = dol_buildpath(strtolower($this->name).'/README-'.$langs->defaultlang.'.md', 0);
687
        if (dol_is_file($pathoffile)) {
688
            $filefound = true;
689
        }
690
        if (! $filefound) {
691
            $tmp=explode('_', $langs->defaultlang);
692
            $pathoffile = dol_buildpath(strtolower($this->name).'/README-'.$tmp[0].'.md', 0);
693
            if (dol_is_file($pathoffile)) {
694
                $filefound = true;
695
            }
696
        }
697
        if (! $filefound) {
698
            $pathoffile = dol_buildpath(strtolower($this->name).'/README.md', 0);
699
            if (dol_is_file($pathoffile)) {
700
                $filefound = true;
701
            }
702
        }
703
704
        return ($filefound?$pathoffile:'');
705
    }
706
707
708
    /**
709
     * Gives the changelog. First check ChangeLog-la_LA.md then ChangeLog.md
710
     *
711
     * @return string  Content of ChangeLog
712
     */
713
    function getChangeLog()
714
    {
715
        global $langs;
716
        $langs->load("admin");
717
718
        include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
719
        include_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php';
720
721
        $filefound= false;
722
723
        // Define path to file README.md.
724
        // First check README-la_LA.md then README.md
725
        $pathoffile = dol_buildpath(strtolower($this->name).'/ChangeLog-'.$langs->defaultlang.'.md', 0);
726
        if (dol_is_file($pathoffile)) {
727
            $filefound = true;
728
        }
729
        if (! $filefound) {
730
            $pathoffile = dol_buildpath(strtolower($this->name).'/ChangeLog.md', 0);
731
            if (dol_is_file($pathoffile)) {
732
                $filefound = true;
733
            }
734
        }
735
736
        if ($filefound)     // Mostly for external modules
737
        {
738
            $content = file_get_contents($pathoffile);
739
740
            if ((float) DOL_VERSION >= 6.0) {
741
                @include_once DOL_DOCUMENT_ROOT.'/core/lib/parsemd.lib.php';
742
                $content = dolMd2Html($content, 'parsedown', array('doc/'=>dol_buildpath(strtolower($this->name).'/doc/', 1)));
743
            }
744
            else
745
            {
746
                $content = nl2br($content);
747
            }
748
        }
749
750
        return $content;
751
    }
752
753
    /**
754
     * Gives the publisher name
755
     *
756
     * @return string  Publisher name
757
     */
758
    function getPublisher()
759
    {
760
        return $this->editor_name;
761
    }
762
763
    /**
764
     * Gives the publisher url
765
     *
766
     * @return string  Publisher url
767
     */
768
    function getPublisherUrl()
769
    {
770
        return $this->editor_url;
771
    }
772
773
    /**
774
     * Gives module version (translated if param $translated is on)
775
     * For 'experimental' modules, gives 'experimental' translation
776
     * For 'dolibarr' modules, gives Dolibarr version
777
     *
778
     * @param  int $translated 1=Special version keys are translated, 0=Special version keys are not translated
779
     * @return string                  Module version
780
     */
781
    function getVersion($translated=1)
782
    {
783
        global $langs;
784
        $langs->load("admin");
785
786
        $ret='';
787
788
        $newversion=preg_replace('/_deprecated/', '', $this->version);
789
        if ($newversion == 'experimental') { $ret=($translated?$langs->transnoentitiesnoconv("VersionExperimental"):$newversion);
790
        } elseif ($newversion == 'development') { $ret=($translated?$langs->transnoentitiesnoconv("VersionDevelopment"):$newversion);
791
        } elseif ($newversion == 'dolibarr') { $ret=DOL_VERSION;
792
        } elseif ($newversion) { $ret=$newversion;
793
        } else { $ret=($translated?$langs->transnoentitiesnoconv("VersionUnknown"):'unknown');
794
        }
795
796
        if (preg_match('/_deprecated/', $this->version)) { $ret.=($translated?' ('.$langs->transnoentitiesnoconv("Deprecated").')':$this->version);
797
        }
798
        return $ret;
799
    }
800
801
802
    /**
803
     * Tells if module is core or external
804
     *
805
     * @return string  'core', 'external' or 'unknown'
806
     */
807
    function isCoreOrExternalModule()
808
    {
809
        if ($this->version == 'dolibarr' || $this->version == 'dolibarr_deprecated') { return 'core';
810
        }
811
        if (! empty($this->version) && ! in_array($this->version, array('experimental','development'))) { return 'external';
812
        }
813
        if (! empty($this->editor_name) || ! empty($this->editor_url)) { return 'external';
814
        }
815
        if ($this->numero >= 100000) { return 'external';
816
        }
817
        return 'unknown';
818
    }
819
820
821
    /**
822
     * Gives module related language files list
823
     *
824
     * @return string[]    Language files list
825
     */
826
    function getLangFilesArray()
827
    {
828
        return $this->langfiles;
829
    }
830
831
    /**
832
     * Gives translated label of an export dataset
833
     *
834
     * @param int $r Dataset index
835
     *
836
     * @return string       Translated databaset label
837
     */
838
    function getExportDatasetLabel($r)
839
    {
840
        global $langs;
841
842
        $langstring="ExportDataset_".$this->export_code[$r];
843
        if ($langs->trans($langstring) == $langstring) {
844
            // Translation not found
845
            return $langs->trans($this->export_label[$r]);
846
        }
847
        else
848
        {
849
            // Translation found
850
            return $langs->trans($langstring);
851
        }
852
    }
853
854
855
    /**
856
     * Gives translated label of an import dataset
857
     *
858
     * @param int $r Dataset index
859
     *
860
     * @return string      Translated dataset label
861
     */
862
    function getImportDatasetLabel($r)
863
    {
864
        global $langs;
865
866
        $langstring="ImportDataset_".$this->import_code[$r];
867
        //print "x".$langstring;
868
        if ($langs->trans($langstring) == $langstring) {
869
            // Translation not found
870
            return $langs->transnoentitiesnoconv($this->import_label[$r]);
871
        }
872
        else
873
        {
874
            // Translation found
875
            return $langs->transnoentitiesnoconv($langstring);
876
        }
877
    }
878
879
880
    /**
881
     * Gives the last date of activation
882
     *
883
     * @return timestamp       Date of last activation
884
     */
885
    function getLastActivationDate()
886
    {
887
        global $conf;
888
889
        $sql = "SELECT tms FROM ".MAIN_DB_PREFIX."const";
890
        $sql.= " WHERE ".$this->db->decrypt('name')." = '".$this->db->escape($this->const_name)."'";
891
        $sql.= " AND entity IN (0, ".$conf->entity.")";
892
893
        dol_syslog(get_class($this)."::getLastActiveDate", LOG_DEBUG);
894
        $resql=$this->db->query($sql);
895
        if (! $resql) { $err++;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $err seems to be never defined.
Loading history...
896
        } else
897
        {
898
            $obj=$this->db->fetch_object($resql);
899
            if ($obj) { return $this->db->jdate($obj->tms);
900
            }
901
        }
902
903
        return '';
904
    }
905
906
907
    /**
908
     * Gives the last author of activation
909
     *
910
     * @return array       Array array('authorid'=>Id of last activation user, 'lastactivationdate'=>Date of last activation)
911
     */
912
    function getLastActivationInfo()
913
    {
914
        global $conf;
915
916
        $sql = "SELECT tms, note FROM ".MAIN_DB_PREFIX."const";
917
        $sql.= " WHERE ".$this->db->decrypt('name')." = '".$this->db->escape($this->const_name)."'";
918
        $sql.= " AND entity IN (0, ".$conf->entity.")";
919
920
        dol_syslog(get_class($this)."::getLastActiveDate", LOG_DEBUG);
921
        $resql=$this->db->query($sql);
922
        if (! $resql) { $err++;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $err seems to be never defined.
Loading history...
923
        } else
924
        {
925
            $obj=$this->db->fetch_object($resql);
926
            $tmp=array();
927
            if ($obj->note) {
928
                $tmp=json_decode($obj->note, true);
929
            }
930
            if ($obj) { return array('authorid'=>$tmp['authorid'], 'ip'=>$tmp['ip'], 'lastactivationdate'=>$this->db->jdate($obj->tms));
931
            }
932
        }
933
934
        return array();
935
    }
936
937
938
    /**
939
     * Insert constants for module activation
940
     *
941
     * @return int Error count (0 if OK)
942
     */
943
    function _active()
944
    {
945
        global $conf, $user;
946
947
        $err = 0;
948
949
        // Common module
950
        $entity = ((! empty($this->always_enabled) || ! empty($this->core_enabled)) ? 0 : $conf->entity);
951
952
        $sql = "DELETE FROM ".MAIN_DB_PREFIX."const";
953
        $sql.= " WHERE ".$this->db->decrypt('name')." = '".$this->db->escape($this->const_name)."'";
954
        $sql.= " AND entity IN (0, ".$entity.")";
955
956
        dol_syslog(get_class($this)."::_active delete activation constant", LOG_DEBUG);
957
        $resql=$this->db->query($sql);
958
        if (! $resql) { $err++;
959
        }
960
961
        $note=json_encode(array('authorid'=>(is_object($user)?$user->id:0), 'ip'=>(empty($_SERVER['REMOTE_ADDR'])?'':$_SERVER['REMOTE_ADDR'])));
962
963
        $sql = "INSERT INTO ".MAIN_DB_PREFIX."const (name, value, visible, entity, note) VALUES";
964
        $sql.= " (".$this->db->encrypt($this->const_name, 1);
965
        $sql.= ", ".$this->db->encrypt('1', 1);
966
        $sql.= ", 0, ".$entity;
967
        $sql.= ", '".$this->db->escape($note)."')";
968
969
        dol_syslog(get_class($this)."::_active insert activation constant", LOG_DEBUG);
970
        $resql=$this->db->query($sql);
971
        if (! $resql) { $err++;
972
        }
973
974
        return $err;
975
    }
976
977
978
    /**
979
     * Module deactivation
980
     *
981
     * @return int Error count (0 if OK)
982
     */
983
    function _unactive()
984
    {
985
        global $conf;
986
987
        $err = 0;
988
989
        // Common module
990
        $entity = ((! empty($this->always_enabled) || ! empty($this->core_enabled)) ? 0 : $conf->entity);
991
992
        $sql = "DELETE FROM ".MAIN_DB_PREFIX."const";
993
        $sql.= " WHERE ".$this->db->decrypt('name')." = '".$this->db->escape($this->const_name)."'";
994
        $sql.= " AND entity IN (0, ".$entity.")";
995
996
        dol_syslog(get_class($this)."::_unactive", LOG_DEBUG);
997
        $this->db->query($sql);
998
999
        return $err;
1000
    }
1001
1002
1003
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1004
    /**
1005
     * Create tables and keys required by module.
1006
     * Files module.sql and module.key.sql with create table and create keys
1007
     * commands must be stored in directory reldir='/module/sql/'
1008
     * This function is called by this->init
1009
     *
1010
     * @param  string $reldir Relative directory where to scan files
1011
     * @return int             <=0 if KO, >0 if OK
1012
     */
1013
    function _load_tables($reldir)
1014
    {
1015
        // phpcs:enable
1016
        global $conf;
1017
1018
        $error=0;
1019
        $dirfound=0;
1020
1021
        if (empty($reldir)) { return 1;
1022
        }
1023
1024
        include_once DOL_DOCUMENT_ROOT . '/core/lib/admin.lib.php';
1025
1026
        $ok = 1;
1027
        foreach($conf->file->dol_document_root as $dirroot)
1028
        {
1029
            if ($ok) {
1030
                $dir = $dirroot.$reldir;
1031
                $ok = 0;
1032
1033
                $handle=@opendir($dir);         // Dir may not exists
1034
                if (is_resource($handle)) {
1035
                    $dirfound++;
1036
1037
                    // Run llx_mytable.sql files, then llx_mytable_*.sql
1038
                    $files = array();
1039
                    while (($file = readdir($handle))!==false)
1040
                    {
1041
                        $files[] = $file;
1042
                    }
1043
                    sort($files);
1044
                    foreach ($files as $file)
1045
                    {
1046
                        if (preg_match('/\.sql$/i', $file) && ! preg_match('/\.key\.sql$/i', $file) && substr($file, 0, 4) == 'llx_' && substr($file, 0, 4) != 'data') {
1047
                            $result=run_sql($dir.$file, empty($conf->global->MAIN_DISPLAY_SQL_INSTALL_LOG)?1:0, '', 1);
1048
                            if ($result <= 0) { $error++;
1049
                            }
1050
                        }
1051
                    }
1052
1053
                    rewinddir($handle);
1054
1055
                    // Run llx_mytable.key.sql files (Must be done after llx_mytable.sql) then then llx_mytable_*.key.sql
1056
                    $files = array();
1057
                    while (($file = readdir($handle))!==false)
1058
                    {
1059
                        $files[] = $file;
1060
                    }
1061
                    sort($files);
1062
                    foreach ($files as $file)
1063
                    {
1064
                        if (preg_match('/\.key\.sql$/i', $file) && substr($file, 0, 4) == 'llx_' && substr($file, 0, 4) != 'data') {
1065
                            $result=run_sql($dir.$file, empty($conf->global->MAIN_DISPLAY_SQL_INSTALL_LOG)?1:0, '', 1);
1066
                            if ($result <= 0) { $error++;
1067
                            }
1068
                        }
1069
                    }
1070
1071
                    rewinddir($handle);
1072
1073
                    // Run data_xxx.sql files (Must be done after llx_mytable.key.sql)
1074
                    $files = array();
1075
                    while (($file = readdir($handle))!==false)
1076
                    {
1077
                               $files[] = $file;
1078
                    }
1079
                    sort($files);
1080
                    foreach ($files as $file)
1081
                    {
1082
                        if (preg_match('/\.sql$/i', $file) && ! preg_match('/\.key\.sql$/i', $file) && substr($file, 0, 4) == 'data') {
1083
                            $result=run_sql($dir.$file, empty($conf->global->MAIN_DISPLAY_SQL_INSTALL_LOG)?1:0, '', 1);
1084
                            if ($result <= 0) { $error++;
1085
                            }
1086
                        }
1087
                    }
1088
1089
                    rewinddir($handle);
1090
1091
                    // Run update_xxx.sql files
1092
                    $files = array();
1093
                    while (($file = readdir($handle))!==false)
1094
                    {
1095
                               $files[] = $file;
1096
                    }
1097
                    sort($files);
1098
                    foreach ($files as $file)
1099
                    {
1100
                        if (preg_match('/\.sql$/i', $file) && ! preg_match('/\.key\.sql$/i', $file) && substr($file, 0, 6) == 'update') {
1101
                            $result=run_sql($dir.$file, empty($conf->global->MAIN_DISPLAY_SQL_INSTALL_LOG)?1:0, '', 1);
1102
                            if ($result <= 0) { $error++;
1103
                            }
1104
                        }
1105
                    }
1106
1107
                    closedir($handle);
1108
                }
1109
1110
                if ($error == 0) {
1111
                    $ok = 1;
1112
                }
1113
            }
1114
        }
1115
1116
        if (! $dirfound) { dol_syslog("A module ask to load sql files into ".$reldir." but this directory was not found.", LOG_WARNING);
1117
        }
1118
        return $ok;
1119
    }
1120
1121
1122
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1123
    /**
1124
     * Adds boxes
1125
     *
1126
     * @param string $option Options when disabling module ('newboxdefonly'=insert only boxes definition)
1127
     *
1128
     * @return int             Error count (0 if OK)
1129
     */
1130
    function insert_boxes($option='')
1131
    {
1132
        // phpcs:enable
1133
        include_once DOL_DOCUMENT_ROOT . '/core/class/infobox.class.php';
1134
1135
        global $conf;
1136
1137
        $err=0;
1138
1139
        if (is_array($this->boxes)) {
1140
            dol_syslog(get_class($this)."::insert_boxes", LOG_DEBUG);
1141
1142
            $pos_name = InfoBox::getListOfPagesForBoxes();
1143
1144
            foreach ($this->boxes as $key => $value)
1145
            {
1146
                $file  = isset($this->boxes[$key]['file'])?$this->boxes[$key]['file']:'';
1147
                $note  = isset($this->boxes[$key]['note'])?$this->boxes[$key]['note']:'';
1148
                $enabledbydefaulton = isset($this->boxes[$key]['enabledbydefaulton'])?$this->boxes[$key]['enabledbydefaulton']:'Home';
1149
1150
                if (empty($file)) { $file  = isset($this->boxes[$key][1])?$this->boxes[$key][1]:'';    // For backward compatibility
1151
                }
1152
                if (empty($note)) { $note  = isset($this->boxes[$key][2])?$this->boxes[$key][2]:'';    // For backward compatibility
1153
                }
1154
1155
                // Search if boxes def already present
1156
                $sql = "SELECT count(*) as nb FROM ".MAIN_DB_PREFIX."boxes_def";
1157
                $sql.= " WHERE file = '".$this->db->escape($file)."'";
1158
                $sql.= " AND entity = ".$conf->entity;
1159
                if ($note) { $sql.=" AND note ='".$this->db->escape($note)."'";
1160
                }
1161
1162
                $result=$this->db->query($sql);
1163
                if ($result) {
1164
                    $obj = $this->db->fetch_object($result);
1165
                    if ($obj->nb == 0) {
1166
                        $this->db->begin();
1167
1168
                        if (! $err) {
1169
                            $sql = "INSERT INTO ".MAIN_DB_PREFIX."boxes_def (file, entity, note)";
1170
                            $sql.= " VALUES ('".$this->db->escape($file)."', ";
1171
                            $sql.= $conf->entity.", ";
1172
                            $sql.= $note?"'".$this->db->escape($note)."'":"null";
1173
                            $sql.= ")";
1174
1175
                            dol_syslog(get_class($this)."::insert_boxes", LOG_DEBUG);
1176
                            $resql=$this->db->query($sql);
1177
                            if (! $resql) { $err++;
1178
                            }
1179
                        }
1180
                        if (! $err && ! preg_match('/newboxdefonly/', $option)) {
1181
                            $lastid=$this->db->last_insert_id(MAIN_DB_PREFIX."boxes_def", "rowid");
1182
1183
                            foreach ($pos_name as $key2 => $val2)
1184
                            {
1185
                                    //print 'key2='.$key2.'-val2='.$val2."<br>\n";
1186
                                if ($enabledbydefaulton && $val2 != $enabledbydefaulton) { continue;        // Not enabled by default onto this page.
1187
                                }
1188
1189
                                $sql = "INSERT INTO ".MAIN_DB_PREFIX."boxes (box_id,position,box_order,fk_user,entity)";
1190
                                $sql.= " VALUES (".$lastid.", ".$key2.", '0', 0, ".$conf->entity.")";
1191
1192
                                dol_syslog(get_class($this)."::insert_boxes onto page ".$key2."=".$val2."", LOG_DEBUG);
1193
                                $resql=$this->db->query($sql);
1194
                                if (! $resql) { $err++;
1195
                                }
1196
                            }
1197
                        }
1198
1199
                        if (! $err) {
1200
                            $this->db->commit();
1201
                        }
1202
                        else
1203
                        {
1204
                                  $this->error=$this->db->lasterror();
1205
                                  $this->db->rollback();
1206
                        }
1207
                    }
1208
                    // else box already registered into database
1209
                }
1210
                else
1211
                {
1212
                    $this->error=$this->db->lasterror();
1213
                    $err++;
1214
                }
1215
            }
1216
        }
1217
1218
        return $err;
1219
    }
1220
1221
1222
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1223
    /**
1224
     * Removes boxes
1225
     *
1226
     * @return int Error count (0 if OK)
1227
     */
1228
    function delete_boxes()
1229
    {
1230
        // phpcs:enable
1231
        global $conf;
1232
1233
        $err=0;
1234
1235
        if (is_array($this->boxes)) {
1236
            foreach ($this->boxes as $key => $value)
1237
            {
1238
                //$titre = $this->boxes[$key][0];
1239
                $file  = $this->boxes[$key]['file'];
1240
                //$note  = $this->boxes[$key][2];
1241
1242
                // TODO If the box is also included by another module and the other module is still on, we should not remove it.
1243
                // For the moment, we manage this with hard coded exception
1244
                //print "Remove box ".$file.'<br>';
1245
                if ($file == 'box_graph_product_distribution.php') {
1246
                    if (! empty($conf->produit->enabled) || ! empty($conf->service->enabled)) {
1247
                        dol_syslog("We discard disabling of module ".$file." because another module still active require it.");
1248
                        continue;
1249
                    }
1250
                }
1251
1252
                if (empty($file)) { $file  = isset($this->boxes[$key][1])?$this->boxes[$key][1]:'';    // For backward compatibility
1253
                }
1254
1255
                if ($this->db->type == 'sqlite3') {
1256
                    // sqlite doesn't support "USING" syntax.
1257
                    // TODO: remove this dependency.
1258
                    $sql = "DELETE FROM ".MAIN_DB_PREFIX."boxes ";
1259
                    $sql .= "WHERE ".MAIN_DB_PREFIX."boxes.box_id IN (";
1260
                    $sql .= "SELECT ".MAIN_DB_PREFIX."boxes_def.rowid ";
1261
                    $sql .= "FROM ".MAIN_DB_PREFIX."boxes_def ";
1262
                    $sql .= "WHERE ".MAIN_DB_PREFIX."boxes_def.file = '".$this->db->escape($file)."') ";
1263
                    $sql .= "AND ".MAIN_DB_PREFIX."boxes.entity = ".$conf->entity;
1264
                } else {
1265
                    $sql = "DELETE FROM ".MAIN_DB_PREFIX."boxes";
1266
                    $sql.= " USING ".MAIN_DB_PREFIX."boxes, ".MAIN_DB_PREFIX."boxes_def";
1267
                    $sql.= " WHERE ".MAIN_DB_PREFIX."boxes.box_id = ".MAIN_DB_PREFIX."boxes_def.rowid";
1268
                    $sql.= " AND ".MAIN_DB_PREFIX."boxes_def.file = '".$this->db->escape($file)."'";
1269
                    $sql.= " AND ".MAIN_DB_PREFIX."boxes.entity = ".$conf->entity;
1270
                }
1271
1272
                dol_syslog(get_class($this)."::delete_boxes", LOG_DEBUG);
1273
                $resql=$this->db->query($sql);
1274
                if (! $resql) {
1275
                    $this->error=$this->db->lasterror();
1276
                    $err++;
1277
                }
1278
1279
                $sql = "DELETE FROM ".MAIN_DB_PREFIX."boxes_def";
1280
                $sql.= " WHERE file = '".$this->db->escape($file)."'";
1281
                $sql.= " AND entity = ".$conf->entity;
1282
1283
                dol_syslog(get_class($this)."::delete_boxes", LOG_DEBUG);
1284
                $resql=$this->db->query($sql);
1285
                if (! $resql) {
1286
                    $this->error=$this->db->lasterror();
1287
                    $err++;
1288
                }
1289
            }
1290
        }
1291
1292
        return $err;
1293
    }
1294
1295
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1296
    /**
1297
     * Adds cronjobs
1298
     *
1299
     * @return int             Error count (0 if OK)
1300
     */
1301
    function insert_cronjobs()
1302
    {
1303
        // phpcs:enable
1304
        include_once DOL_DOCUMENT_ROOT . '/core/class/infobox.class.php';
1305
1306
        global $conf;
1307
1308
        $err=0;
1309
1310
        if (is_array($this->cronjobs)) {
1311
            dol_syslog(get_class($this)."::insert_cronjobs", LOG_DEBUG);
1312
1313
            foreach ($this->cronjobs as $key => $value)
1314
            {
1315
                $entity  = isset($this->cronjobs[$key]['entity'])?$this->cronjobs[$key]['entity']:$conf->entity;
1316
                $label  = isset($this->cronjobs[$key]['label'])?$this->cronjobs[$key]['label']:'';
1317
                $jobtype  = isset($this->cronjobs[$key]['jobtype'])?$this->cronjobs[$key]['jobtype']:'';
1318
                $class  = isset($this->cronjobs[$key]['class'])?$this->cronjobs[$key]['class']:'';
1319
                $objectname  = isset($this->cronjobs[$key]['objectname'])?$this->cronjobs[$key]['objectname']:'';
1320
                $method = isset($this->cronjobs[$key]['method'])?$this->cronjobs[$key]['method']:'';
1321
                $command  = isset($this->cronjobs[$key]['command'])?$this->cronjobs[$key]['command']:'';
1322
                $parameters  = isset($this->cronjobs[$key]['parameters'])?$this->cronjobs[$key]['parameters']:'';
1323
                $comment = isset($this->cronjobs[$key]['comment'])?$this->cronjobs[$key]['comment']:'';
1324
                $frequency = isset($this->cronjobs[$key]['frequency'])?$this->cronjobs[$key]['frequency']:'';
1325
                $unitfrequency = isset($this->cronjobs[$key]['unitfrequency'])?$this->cronjobs[$key]['unitfrequency']:'';
1326
                $priority = isset($this->cronjobs[$key]['priority'])?$this->cronjobs[$key]['priority']:'';
1327
                $datestart = isset($this->cronjobs[$key]['datestart'])?$this->cronjobs[$key]['datestart']:'';
1328
                $dateend = isset($this->cronjobs[$key]['dateend'])?$this->cronjobs[$key]['dateend']:'';
1329
                $status = isset($this->cronjobs[$key]['status'])?$this->cronjobs[$key]['status']:'';
1330
                $test = isset($this->cronjobs[$key]['test'])?$this->cronjobs[$key]['test']:'';                    // Line must be enabled or not (so visible or not)
1331
1332
                // Search if cron entry already present
1333
                $sql = "SELECT count(*) as nb FROM ".MAIN_DB_PREFIX."cronjob";
1334
                $sql.= " WHERE module_name = '".$this->db->escape(empty($this->rights_class)?strtolower($this->name):$this->rights_class)."'";
1335
                if ($class) { $sql.= " AND classesname = '".$this->db->escape($class)."'";
1336
                }
1337
                if ($objectname) { $sql.= " AND objectname = '".$this->db->escape($objectname)."'";
1338
                }
1339
                if ($method) { $sql.= " AND methodename = '".$this->db->escape($method)."'";
1340
                }
1341
                if ($command) { $sql.= " AND command = '".$this->db->escape($command)."'";
1342
                }
1343
                $sql.= " AND entity = ".$entity;    // Must be exact entity
1344
1345
                $now=dol_now();
1346
1347
                $result=$this->db->query($sql);
1348
                if ($result) {
1349
                    $obj = $this->db->fetch_object($result);
1350
                    if ($obj->nb == 0) {
1351
                        $this->db->begin();
1352
1353
                        if (! $err) {
1354
                            $sql = "INSERT INTO ".MAIN_DB_PREFIX."cronjob (module_name, datec, datestart, dateend, label, jobtype, classesname, objectname, methodename, command, params, note,";
1355
                            if (is_int($frequency)) { $sql.= ' frequency,'; }
1356
                            if (is_int($unitfrequency)) { $sql.= ' unitfrequency,'; }
1357
                            if (is_int($priority)) { $sql.= ' priority,'; }
1358
                            if (is_int($status)) { $sql.= ' status,'; }
1359
                            $sql.= " entity, test)";
1360
                            $sql.= " VALUES (";
1361
                            $sql.= "'".$this->db->escape(empty($this->rights_class)?strtolower($this->name):$this->rights_class)."', ";
1362
                            $sql.= "'".$this->db->idate($now)."', ";
1363
                            $sql.= ($datestart ? "'".$this->db->idate($datestart)."'" : "'".$this->db->idate($now)."'").", ";
1364
                            $sql.= ($dateend   ? "'".$this->db->idate($dateend)."'"   : "NULL").", ";
1365
                            $sql.= "'".$this->db->escape($label)."', ";
1366
                            $sql.= "'".$this->db->escape($jobtype)."', ";
1367
                            $sql.= ($class?"'".$this->db->escape($class)."'":"null").",";
1368
                            $sql.= ($objectname?"'".$this->db->escape($objectname)."'":"null").",";
1369
                            $sql.= ($method?"'".$this->db->escape($method)."'":"null").",";
1370
                            $sql.= ($command?"'".$this->db->escape($command)."'":"null").",";
1371
                            $sql.= ($parameters?"'".$this->db->escape($parameters)."'":"null").",";
1372
                            $sql.= ($comment?"'".$this->db->escape($comment)."'":"null").",";
1373
                            if(is_int($frequency)) { $sql.= "'".$this->db->escape($frequency)."', ";
1374
                            }
1375
                            if(is_int($unitfrequency)) { $sql.= "'".$this->db->escape($unitfrequency)."', ";
1376
                            }
1377
                            if(is_int($priority)) {$sql.= "'".$this->db->escape($priority)."', ";
1378
                            }
1379
                            if(is_int($status)) { $sql.= "'".$this->db->escape($status)."', ";
1380
                            }
1381
                            $sql.= $entity.",";
1382
                            $sql.= "'".$this->db->escape($test)."'";
1383
                            $sql.= ")";
1384
1385
                            $resql=$this->db->query($sql);
1386
                            if (! $resql) { $err++;
1387
                            }
1388
                        }
1389
1390
                        if (! $err) {
1391
                            $this->db->commit();
1392
                        }
1393
                        else
1394
                        {
1395
                            $this->error=$this->db->lasterror();
1396
                            $this->db->rollback();
1397
                        }
1398
                    }
1399
                    // else box already registered into database
1400
                }
1401
                else
1402
                {
1403
                    $this->error=$this->db->lasterror();
1404
                    $err++;
1405
                }
1406
            }
1407
        }
1408
1409
        return $err;
1410
    }
1411
1412
1413
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1414
    /**
1415
     * Removes boxes
1416
     *
1417
     * @return int Error count (0 if OK)
1418
     */
1419
    function delete_cronjobs()
1420
    {
1421
        // phpcs:enable
1422
        global $conf;
1423
1424
        $err=0;
1425
1426
        if (is_array($this->cronjobs)) {
1427
            $sql = "DELETE FROM ".MAIN_DB_PREFIX."cronjob";
1428
            $sql.= " WHERE module_name = '".$this->db->escape(empty($this->rights_class)?strtolower($this->name):$this->rights_class)."'";
1429
            $sql.= " AND entity = ".$conf->entity;
1430
            $sql.= " AND test = '1'";        // We delete on lines that are not set with a complete test that is '$conf->module->enabled' so when module is disabled, the cron is also removed.
1431
              // For crons declared with a '$conf->module->enabled', there is no need to delete the line, so we don't loose setup if we reenable module.
1432
1433
            dol_syslog(get_class($this)."::delete_cronjobs", LOG_DEBUG);
1434
            $resql=$this->db->query($sql);
1435
            if (! $resql) {
1436
                $this->error=$this->db->lasterror();
1437
                $err++;
1438
            }
1439
        }
1440
1441
        return $err;
1442
    }
1443
1444
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1445
    /**
1446
     * Removes tabs
1447
     *
1448
     * @return int Error count (0 if OK)
1449
     */
1450
    function delete_tabs()
1451
    {
1452
        // phpcs:enable
1453
        global $conf;
1454
1455
        $err=0;
1456
1457
        $sql = "DELETE FROM ".MAIN_DB_PREFIX."const";
1458
        $sql.= " WHERE ".$this->db->decrypt('name')." like '".$this->db->escape($this->const_name)."_TABS_%'";
1459
        $sql.= " AND entity = ".$conf->entity;
1460
1461
        dol_syslog(get_class($this)."::delete_tabs", LOG_DEBUG);
1462
        if (! $this->db->query($sql)) {
1463
            $this->error=$this->db->lasterror();
1464
            $err++;
1465
        }
1466
1467
        return $err;
1468
    }
1469
1470
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1471
    /**
1472
     * Adds tabs
1473
     *
1474
     * @return int  Error count (0 if ok)
1475
     */
1476
    function insert_tabs()
1477
    {
1478
        // phpcs:enable
1479
        global $conf;
1480
1481
        $err=0;
1482
1483
        if (! empty($this->tabs)) {
1484
            dol_syslog(get_class($this)."::insert_tabs", LOG_DEBUG);
1485
1486
            $i=0;
1487
            foreach ($this->tabs as $key => $value)
1488
            {
1489
                if (is_array($value) && count($value) == 0) { continue;    // Discard empty arrays
1490
                }
1491
1492
                $entity=$conf->entity;
1493
                $newvalue = $value;
1494
1495
                if (is_array($value)) {
1496
                    $newvalue = $value['data'];
1497
                    if (isset($value['entity'])) { $entity = $value['entity'];
1498
                    }
1499
                }
1500
1501
                if ($newvalue) {
1502
                    $sql = "INSERT INTO ".MAIN_DB_PREFIX."const (";
1503
                    $sql.= "name";
1504
                    $sql.= ", type";
1505
                    $sql.= ", value";
1506
                    $sql.= ", note";
1507
                    $sql.= ", visible";
1508
                    $sql.= ", entity";
1509
                    $sql.= ")";
1510
                    $sql.= " VALUES (";
1511
                    $sql.= $this->db->encrypt($this->const_name."_TABS_".$i, 1);
1512
                    $sql.= ", 'chaine'";
1513
                    $sql.= ", ".$this->db->encrypt($newvalue, 1);
1514
                    $sql.= ", null";
1515
                    $sql.= ", '0'";
1516
                    $sql.= ", ".$entity;
1517
                    $sql.= ")";
1518
1519
                    $resql = $this->db->query($sql);
1520
                    if (! $resql) {
1521
                         dol_syslog($this->db->lasterror(), LOG_ERR);
1522
                        if ($this->db->lasterrno() != 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1523
                            $this->error = $this->db->lasterror();
1524
                            $this->errors[] = $this->db->lasterror();
1525
                            $err++;
1526
                            break;
1527
                        }
1528
                    }
1529
                }
1530
                $i++;
1531
            }
1532
        }
1533
        return $err;
1534
    }
1535
1536
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1537
    /**
1538
     * Adds constants
1539
     *
1540
     * @return int Error count (0 if OK)
1541
     */
1542
    function insert_const()
1543
    {
1544
        // phpcs:enable
1545
        global $conf;
1546
1547
        $err=0;
1548
1549
        if (empty($this->const)) { return 0;
1550
        }
1551
1552
        dol_syslog(get_class($this)."::insert_const", LOG_DEBUG);
1553
1554
        foreach ($this->const as $key => $value)
1555
        {
1556
            $name      = $this->const[$key][0];
1557
            $type      = $this->const[$key][1];
1558
            $val       = $this->const[$key][2];
1559
            $note      = isset($this->const[$key][3])?$this->const[$key][3]:'';
1560
            $visible   = isset($this->const[$key][4])?$this->const[$key][4]:0;
1561
            $entity    = (! empty($this->const[$key][5]) && $this->const[$key][5]!='current')?0:$conf->entity;
1562
1563
            // Clean
1564
            if (empty($visible)) { $visible='0';
1565
            }
1566
            if (empty($val) && $val != '0') { $val='';
1567
            }
1568
1569
            $sql = "SELECT count(*)";
1570
            $sql.= " FROM ".MAIN_DB_PREFIX."const";
1571
            $sql.= " WHERE ".$this->db->decrypt('name')." = '".$this->db->escape($name)."'";
1572
            $sql.= " AND entity = ".$entity;
1573
1574
            $result=$this->db->query($sql);
1575
            if ($result) {
1576
                $row = $this->db->fetch_row($result);
1577
1578
                if ($row[0] == 0)   // If not found
1579
                {
1580
                    $sql = "INSERT INTO ".MAIN_DB_PREFIX."const (name,type,value,note,visible,entity)";
1581
                    $sql.= " VALUES (";
1582
                    $sql.= $this->db->encrypt($name, 1);
1583
                    $sql.= ",'".$type."'";
1584
                    $sql.= ",".(($val != '')?$this->db->encrypt($val, 1):"''");
1585
                    $sql.= ",".($note?"'".$this->db->escape($note)."'":"null");
1586
                    $sql.= ",'".$visible."'";
1587
                    $sql.= ",".$entity;
1588
                    $sql.= ")";
1589
1590
                    if (! $this->db->query($sql) ) {
1591
                        $err++;
1592
                    }
1593
                }
1594
                else
1595
                {
1596
                    dol_syslog(get_class($this)."::insert_const constant '".$name."' already exists", LOG_WARNING);
1597
                }
1598
            }
1599
            else
1600
            {
1601
                $err++;
1602
            }
1603
        }
1604
1605
        return $err;
1606
    }
1607
1608
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1609
    /**
1610
     * Removes constants tagged 'deleteonunactive'
1611
     *
1612
     * @return int <0 if KO, 0 if OK
1613
     */
1614
    function delete_const()
1615
    {
1616
        // phpcs:enable
1617
        global $conf;
1618
1619
        $err=0;
1620
1621
        if (empty($this->const)) { return 0;
1622
        }
1623
1624
        foreach ($this->const as $key => $value)
1625
        {
1626
            $name      = $this->const[$key][0];
1627
            $deleteonunactive = (! empty($this->const[$key][6]))?1:0;
1628
1629
            if ($deleteonunactive) {
1630
                $sql = "DELETE FROM ".MAIN_DB_PREFIX."const";
1631
                $sql.= " WHERE ".$this->db->decrypt('name')." = '".$name."'";
1632
                $sql.= " AND entity in (0, ".$conf->entity.")";
1633
                dol_syslog(get_class($this)."::delete_const", LOG_DEBUG);
1634
                if (! $this->db->query($sql)) {
1635
                    $this->error=$this->db->lasterror();
1636
                    $err++;
1637
                }
1638
            }
1639
        }
1640
1641
        return $err;
1642
    }
1643
1644
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1645
    /**
1646
     * Adds access rights
1647
     *
1648
     * @param  int $reinitadminperms If 1, we also grant them to all admin users
1649
     * @param  int $force_entity     Force current entity
1650
     * @param  int $notrigger        1=Does not execute triggers, 0= execute triggers
1651
     * @return int                     Error count (0 if OK)
1652
     */
1653
    function insert_permissions($reinitadminperms=0, $force_entity=null, $notrigger=0)
1654
    {
1655
        // phpcs:enable
1656
        global $conf,$user;
1657
1658
        $err=0;
1659
        $entity=(! empty($force_entity) ? $force_entity : $conf->entity);
1660
1661
        dol_syslog(get_class($this)."::insert_permissions", LOG_DEBUG);
1662
1663
        // Test if module is activated
1664
        $sql_del = "SELECT ".$this->db->decrypt('value')." as value";
1665
        $sql_del.= " FROM ".MAIN_DB_PREFIX."const";
1666
        $sql_del.= " WHERE ".$this->db->decrypt('name')." = '".$this->db->escape($this->const_name)."'";
1667
        $sql_del.= " AND entity IN (0,".$entity.")";
1668
1669
        $resql=$this->db->query($sql_del);
1670
1671
        if ($resql) {
1672
            $obj=$this->db->fetch_object($resql);
1673
            if ($obj !== null && ! empty($obj->value) && ! empty($this->rights)) {
1674
                // If the module is active
1675
                foreach ($this->rights as $key => $value)
1676
                {
1677
                    $r_id       = $this->rights[$key][0];
1678
                    $r_desc     = $this->rights[$key][1];
1679
                    $r_type     = isset($this->rights[$key][2])?$this->rights[$key][2]:'';
1680
                    $r_def      = $this->rights[$key][3];
1681
                    $r_perms    = $this->rights[$key][4];
1682
                    $r_subperms = isset($this->rights[$key][5])?$this->rights[$key][5]:'';
1683
                    $r_modul    = empty($this->rights_class)?strtolower($this->name):$this->rights_class;
1684
1685
                    if (empty($r_type)) { $r_type='w';
1686
                    }
1687
1688
                    // Search if perm already present
1689
                    $sql = "SELECT count(*) as nb FROM ".MAIN_DB_PREFIX."rights_def";
1690
                    $sql.= " WHERE id = ".$r_id." AND entity = ".$entity;
1691
1692
                    $resqlselect=$this->db->query($sql);
1693
                    if ($resqlselect) {
1694
                        $objcount = $this->db->fetch_object($resqlselect);
1695
                        if ($objcount && $objcount->nb == 0) {
1696
                            if (dol_strlen($r_perms) ) {
1697
                                if (dol_strlen($r_subperms) ) {
1698
                                    $sql = "INSERT INTO ".MAIN_DB_PREFIX."rights_def";
1699
                                    $sql.= " (id, entity, libelle, module, type, bydefault, perms, subperms)";
1700
                                    $sql.= " VALUES ";
1701
                                    $sql.= "(".$r_id.",".$entity.",'".$this->db->escape($r_desc)."','".$r_modul."','".$r_type."',".$r_def.",'".$r_perms."','".$r_subperms."')";
1702
                                }
1703
                                else
1704
                                   {
1705
                                    $sql = "INSERT INTO ".MAIN_DB_PREFIX."rights_def";
1706
                                    $sql.= " (id, entity, libelle, module, type, bydefault, perms)";
1707
                                    $sql.= " VALUES ";
1708
                                    $sql.= "(".$r_id.",".$entity.",'".$this->db->escape($r_desc)."','".$r_modul."','".$r_type."',".$r_def.",'".$r_perms."')";
1709
                                }
1710
                            }
1711
                            else
1712
                            {
1713
                                 $sql = "INSERT INTO ".MAIN_DB_PREFIX."rights_def ";
1714
                                 $sql .= " (id, entity, libelle, module, type, bydefault)";
1715
                                 $sql .= " VALUES ";
1716
                                 $sql .= "(".$r_id.",".$entity.",'".$this->db->escape($r_desc)."','".$r_modul."','".$r_type."',".$r_def.")";
1717
                            }
1718
1719
                            $resqlinsert=$this->db->query($sql, 1);
1720
1721
                            if (! $resqlinsert) {
1722
                                if ($this->db->errno() != "DB_ERROR_RECORD_ALREADY_EXISTS") {
1723
                                    $this->error=$this->db->lasterror();
1724
                                    $err++;
1725
                                    break;
1726
                                }
1727
                                else { dol_syslog(get_class($this)."::insert_permissions record already exists", LOG_INFO);
1728
                                }
1729
                            }
1730
1731
                            $this->db->free($resqlinsert);
1732
                        }
1733
1734
                        $this->db->free($resqlselect);
1735
                    }
1736
1737
                    // If we want to init permissions on admin users
1738
                    if ($reinitadminperms) {
1739
                        if (! class_exists('User')) {
1740
                            include_once DOL_DOCUMENT_ROOT . '/user/class/user.class.php';
1741
                        }
1742
                        $sql="SELECT rowid FROM ".MAIN_DB_PREFIX."user WHERE admin = 1";
1743
                        dol_syslog(get_class($this)."::insert_permissions Search all admin users", LOG_DEBUG);
1744
                        $resqlseladmin=$this->db->query($sql, 1);
1745
                        if ($resqlseladmin) {
1746
                            $num=$this->db->num_rows($resqlseladmin);
1747
                            $i=0;
1748
                            while ($i < $num)
1749
                            {
1750
                                  $obj2=$this->db->fetch_object($resqlseladmin);
1751
                                  dol_syslog(get_class($this)."::insert_permissions Add permission to user id=".$obj2->rowid);
1752
1753
                                  $tmpuser=new User($this->db);
1754
                                  $result = $tmpuser->fetch($obj2->rowid);
1755
                                if ($result > 0) {
1756
                                    $tmpuser->addrights($r_id, '', '', 0, 1);
1757
                                }
1758
                                else
1759
                                 {
1760
                                    dol_syslog(get_class($this)."::insert_permissions Failed to add the permission to user because fetch return an error", LOG_ERR);
1761
                                }
1762
                                 $i++;
1763
                            }
1764
                        }
1765
                        else
1766
                        {
1767
                            dol_print_error($this->db);
1768
                        }
1769
                    }
1770
                }
1771
1772
                if ($reinitadminperms && ! empty($user->admin))  // Reload permission for current user if defined
1773
                {
1774
                    // We reload permissions
1775
                    $user->clearrights();
1776
                    $user->getrights();
1777
                }
1778
            }
1779
            $this->db->free($resql);
1780
        }
1781
        else
1782
        {
1783
            $this->error=$this->db->lasterror();
1784
            $err++;
1785
        }
1786
1787
        return $err;
1788
    }
1789
1790
1791
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1792
    /**
1793
     * Removes access rights
1794
     *
1795
     * @return int                     Error count (0 if OK)
1796
     */
1797
    function delete_permissions()
1798
    {
1799
        // phpcs:enable
1800
        global $conf;
1801
1802
        $err=0;
1803
1804
        $sql = "DELETE FROM ".MAIN_DB_PREFIX."rights_def";
1805
        $sql.= " WHERE module = '".$this->db->escape(empty($this->rights_class)?strtolower($this->name):$this->rights_class)."'";
1806
        $sql.= " AND entity = ".$conf->entity;
1807
        dol_syslog(get_class($this)."::delete_permissions", LOG_DEBUG);
1808
        if (! $this->db->query($sql)) {
1809
            $this->error=$this->db->lasterror();
1810
            $err++;
1811
        }
1812
1813
        return $err;
1814
    }
1815
1816
1817
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1818
    /**
1819
     * Adds menu entries
1820
     *
1821
     * @return int     Error count (0 if OK)
1822
     */
1823
    function insert_menus()
1824
    {
1825
        // phpcs:enable
1826
        global $user;
1827
1828
        if (! is_array($this->menu) || empty($this->menu)) { return 0;
1829
        }
1830
1831
        include_once DOL_DOCUMENT_ROOT . '/core/class/menubase.class.php';
1832
1833
        dol_syslog(get_class($this)."::insert_menus", LOG_DEBUG);
1834
1835
        $err=0;
1836
1837
        $this->db->begin();
1838
1839
        foreach ($this->menu as $key => $value)
1840
        {
1841
            $menu = new Menubase($this->db);
1842
            $menu->menu_handler='all';
1843
1844
            //$menu->module=strtolower($this->name);    TODO When right_class will be same than module name
1845
            $menu->module=empty($this->rights_class)?strtolower($this->name):$this->rights_class;
1846
1847
            if (! $this->menu[$key]['fk_menu']) {
1848
                $menu->fk_menu=0;
1849
            }
1850
            else
1851
            {
1852
                $foundparent=0;
1853
                $fk_parent=$this->menu[$key]['fk_menu'];
1854
                if (preg_match('/^r=/', $fk_parent))    // old deprecated method
1855
                {
1856
                    $fk_parent=str_replace('r=', '', $fk_parent);
1857
                    if (isset($this->menu[$fk_parent]['rowid'])) {
1858
                        $menu->fk_menu=$this->menu[$fk_parent]['rowid'];
1859
                        $foundparent=1;
1860
                    }
1861
                }
1862
                elseif (preg_match('/^fk_mainmenu=([a-zA-Z0-9_]+),fk_leftmenu=([a-zA-Z0-9_]+)$/', $fk_parent, $reg)) {
1863
                    $menu->fk_menu=-1;
1864
                    $menu->fk_mainmenu=$reg[1];
1865
                    $menu->fk_leftmenu=$reg[2];
1866
                    $foundparent=1;
1867
                }
1868
                elseif (preg_match('/^fk_mainmenu=([a-zA-Z0-9_]+)$/', $fk_parent, $reg)) {
1869
                    $menu->fk_menu=-1;
1870
                    $menu->fk_mainmenu=$reg[1];
1871
                    $menu->fk_leftmenu='';
1872
                    $foundparent=1;
1873
                }
1874
                if (! $foundparent) {
1875
                    $this->error="ErrorBadDefinitionOfMenuArrayInModuleDescriptor";
1876
                    dol_syslog(get_class($this)."::insert_menus ".$this->error." ".$this->menu[$key]['fk_menu'], LOG_ERR);
1877
                    $err++;
1878
                }
1879
            }
1880
            $menu->type=$this->menu[$key]['type'];
1881
            $menu->mainmenu=isset($this->menu[$key]['mainmenu'])?$this->menu[$key]['mainmenu']:(isset($menu->fk_mainmenu)?$menu->fk_mainmenu:'');
1882
            $menu->leftmenu=isset($this->menu[$key]['leftmenu'])?$this->menu[$key]['leftmenu']:'';
1883
            $menu->titre=$this->menu[$key]['titre'];
1884
            $menu->url=$this->menu[$key]['url'];
1885
            $menu->langs=$this->menu[$key]['langs'];
1886
            $menu->position=$this->menu[$key]['position'];
1887
            $menu->perms=$this->menu[$key]['perms'];
1888
            $menu->target=isset($this->menu[$key]['target'])?$this->menu[$key]['target']:'';
1889
            $menu->user=$this->menu[$key]['user'];
1890
            $menu->enabled=isset($this->menu[$key]['enabled'])?$this->menu[$key]['enabled']:0;
1891
            $menu->position=$this->menu[$key]['position'];
1892
1893
            if (! $err) {
1894
                $result=$menu->create($user);    // Save menu entry into table llx_menu
1895
                if ($result > 0) {
1896
                    $this->menu[$key]['rowid']=$result;
1897
                }
1898
                else
1899
                {
1900
                    $this->error=$menu->error;
1901
                    dol_syslog(get_class($this).'::insert_menus result='.$result." ".$this->error, LOG_ERR);
1902
                    $err++;
1903
                    break;
1904
                }
1905
            }
1906
        }
1907
1908
        if (! $err) {
1909
            $this->db->commit();
1910
        }
1911
        else
1912
        {
1913
            dol_syslog(get_class($this)."::insert_menus ".$this->error, LOG_ERR);
1914
            $this->db->rollback();
1915
        }
1916
1917
        return $err;
1918
    }
1919
1920
1921
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1922
    /**
1923
     * Removes menu entries
1924
     *
1925
     * @return int Error count (0 if OK)
1926
     */
1927
    function delete_menus()
1928
    {
1929
        // phpcs:enable
1930
        global $conf;
1931
1932
        $err=0;
1933
1934
        //$module=strtolower($this->name);        TODO When right_class will be same than module name
1935
        $module=empty($this->rights_class)?strtolower($this->name):$this->rights_class;
1936
1937
        $sql = "DELETE FROM ".MAIN_DB_PREFIX."menu";
1938
        $sql.= " WHERE module = '".$this->db->escape($module)."'";
1939
        $sql.= " AND entity = ".$conf->entity;
1940
1941
        dol_syslog(get_class($this)."::delete_menus", LOG_DEBUG);
1942
        $resql=$this->db->query($sql);
1943
        if (! $resql) {
1944
            $this->error=$this->db->lasterror();
1945
            $err++;
1946
        }
1947
1948
        return $err;
1949
    }
1950
1951
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1952
    /**
1953
     * Creates directories
1954
     *
1955
     * @return int Error count (0 if OK)
1956
     */
1957
    function create_dirs()
1958
    {
1959
        // phpcs:enable
1960
        global $langs, $conf;
1961
1962
        $err=0;
1963
1964
        if (isset($this->dirs) && is_array($this->dirs)) {
1965
            foreach ($this->dirs as $key => $value)
1966
            {
1967
                $addtodatabase=0;
1968
1969
                if (! is_array($value)) { $dir=$value;    // Default simple mode
1970
                } else {
1971
                    $constname = $this->const_name."_DIR_";
1972
                    $dir       = $this->dirs[$key][1];
1973
                    $addtodatabase = empty($this->dirs[$key][2])?'':$this->dirs[$key][2]; // Create constante in llx_const
1974
                    $subname   = empty($this->dirs[$key][3])?'':strtoupper($this->dirs[$key][3]); // Add submodule name (ex: $conf->module->submodule->dir_output)
1975
                    $forcename = empty($this->dirs[$key][4])?'':strtoupper($this->dirs[$key][4]); // Change the module name if different
1976
1977
                    if (! empty($forcename)) { $constname = 'MAIN_MODULE_'.$forcename."_DIR_";
1978
                    }
1979
                    if (! empty($subname)) {   $constname = $constname.$subname."_";
1980
                    }
1981
1982
                    $name = $constname.strtoupper($this->dirs[$key][0]);
1983
                }
1984
1985
                // Define directory full path ($dir must start with "/")
1986
                if (empty($conf->global->MAIN_MODULE_MULTICOMPANY) || $conf->entity == 1) { $fulldir = DOL_DATA_ROOT.$dir;
1987
                } else { $fulldir = DOL_DATA_ROOT."/".$conf->entity.$dir;
1988
                }
1989
                // Create dir if it does not exists
1990
                if (! empty($fulldir) && ! file_exists($fulldir)) {
1991
                    if (dol_mkdir($fulldir, DOL_DATA_ROOT) < 0) {
1992
                         $this->error = $langs->trans("ErrorCanNotCreateDir", $fulldir);
1993
                         dol_syslog(get_class($this)."::_init ".$this->error, LOG_ERR);
1994
                         $err++;
1995
                    }
1996
                }
1997
1998
                // Define the constant in database if requested (not the default mode)
1999
                if (! empty($addtodatabase)) {
2000
                    $result = $this->insert_dirs($name, $dir);
2001
                    if ($result) { $err++;
2002
                    }
2003
                }
2004
            }
2005
        }
2006
2007
        return $err;
2008
    }
2009
2010
2011
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2012
    /**
2013
     * Adds directories definitions
2014
     *
2015
     * @param string $name Name
2016
     * @param string $dir  Directory
2017
     *
2018
     * @return int             Error count (0 if OK)
2019
     */
2020
    function insert_dirs($name,$dir)
2021
    {
2022
        // phpcs:enable
2023
        global $conf;
2024
2025
        $err=0;
2026
2027
        $sql = "SELECT count(*)";
2028
        $sql.= " FROM ".MAIN_DB_PREFIX."const";
2029
        $sql.= " WHERE ".$this->db->decrypt('name')." = '".$name."'";
2030
        $sql.= " AND entity = ".$conf->entity;
2031
2032
        dol_syslog(get_class($this)."::insert_dirs", LOG_DEBUG);
2033
        $result=$this->db->query($sql);
2034
        if ($result) {
2035
            $row = $this->db->fetch_row($result);
2036
2037
            if ($row[0] == 0) {
2038
                $sql = "INSERT INTO ".MAIN_DB_PREFIX."const (name,type,value,note,visible,entity)";
2039
                $sql.= " VALUES (".$this->db->encrypt($name, 1).",'chaine',".$this->db->encrypt($dir, 1).",'Directory for module ".$this->name."','0',".$conf->entity.")";
2040
2041
                dol_syslog(get_class($this)."::insert_dirs", LOG_DEBUG);
2042
                $this->db->query($sql);
2043
            }
2044
        }
2045
        else
2046
        {
2047
            $this->error=$this->db->lasterror();
2048
            $err++;
2049
        }
2050
2051
        return $err;
2052
    }
2053
2054
2055
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2056
    /**
2057
     * Removes directories
2058
     *
2059
     * @return int Error count (0 if OK)
2060
     */
2061
    function delete_dirs()
2062
    {
2063
        // phpcs:enable
2064
        global $conf;
2065
2066
        $err=0;
2067
2068
        $sql = "DELETE FROM ".MAIN_DB_PREFIX."const";
2069
        $sql.= " WHERE ".$this->db->decrypt('name')." LIKE '".$this->db->escape($this->const_name)."_DIR_%'";
2070
        $sql.= " AND entity = ".$conf->entity;
2071
2072
        dol_syslog(get_class($this)."::delete_dirs", LOG_DEBUG);
2073
        if (! $this->db->query($sql)) {
2074
            $this->error=$this->db->lasterror();
2075
            $err++;
2076
        }
2077
2078
        return $err;
2079
    }
2080
2081
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2082
    /**
2083
     * Adds generic parts
2084
     *
2085
     * @return int Error count (0 if OK)
2086
     */
2087
    function insert_module_parts()
2088
    {
2089
        // phpcs:enable
2090
        global $conf;
2091
2092
        $error=0;
2093
2094
        if (is_array($this->module_parts) && ! empty($this->module_parts)) {
2095
            foreach($this->module_parts as $key => $value)
2096
            {
2097
                if (is_array($value) && count($value) == 0) { continue;    // Discard empty arrays
2098
                }
2099
2100
                $entity=$conf->entity; // Reset the current entity
2101
                $newvalue = $value;
2102
2103
                // Serialize array parameters
2104
                if (is_array($value)) {
2105
                    // Can defined other parameters
2106
                    // Example when $key='hooks', then $value is an array('data'=>array('hookcontext1','hookcontext2'), 'entity'=>X)
2107
                    if (isset($value['data']) && is_array($value['data'])) {
2108
                        $newvalue = json_encode($value['data']);
2109
                        if (isset($value['entity'])) { $entity = $value['entity'];
2110
                        }
2111
                    }
2112
                    else if (isset($value['data']) && !is_array($value['data'])) {
2113
                        $newvalue = $value['data'];
2114
                        if (isset($value['entity'])) { $entity = $value['entity'];
2115
                        }
2116
                    }
2117
                    else    // when hook is declared with syntax 'hook'=>array('hookcontext1','hookcontext2',...)
2118
                    {
2119
                        $newvalue = json_encode($value);
2120
                    }
2121
                }
2122
2123
                $sql = "INSERT INTO ".MAIN_DB_PREFIX."const (";
2124
                $sql.= "name";
2125
                $sql.= ", type";
2126
                $sql.= ", value";
2127
                $sql.= ", note";
2128
                $sql.= ", visible";
2129
                $sql.= ", entity";
2130
                $sql.= ")";
2131
                $sql.= " VALUES (";
2132
                $sql.= $this->db->encrypt($this->const_name."_".strtoupper($key), 1);
2133
                $sql.= ", 'chaine'";
2134
                $sql.= ", ".$this->db->encrypt($newvalue, 1);
2135
                $sql.= ", null";
2136
                $sql.= ", '0'";
2137
                $sql.= ", ".$entity;
2138
                $sql.= ")";
2139
2140
                dol_syslog(get_class($this)."::insert_module_parts for key=".$this->const_name."_".strtoupper($key), LOG_DEBUG);
2141
2142
                $resql=$this->db->query($sql, 1);
2143
                if (! $resql) {
2144
                    if ($this->db->lasterrno() != 'DB_ERROR_RECORD_ALREADY_EXISTS') {
2145
                         $error++;
2146
                         $this->error=$this->db->lasterror();
2147
                    }
2148
                    else
2149
                    {
2150
                         dol_syslog(get_class($this)."::insert_module_parts for ".$this->const_name."_".strtoupper($key)." Record already exists.", LOG_WARNING);
2151
                    }
2152
                }
2153
            }
2154
        }
2155
        return $error;
2156
    }
2157
2158
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2159
    /**
2160
     * Removes generic parts
2161
     *
2162
     * @return int Error count (0 if OK)
2163
     */
2164
    function delete_module_parts()
2165
    {
2166
        // phpcs:enable
2167
        global $conf;
2168
2169
        $err=0;
2170
        $entity=$conf->entity;
2171
2172
        if (is_array($this->module_parts) && ! empty($this->module_parts)) {
2173
            foreach($this->module_parts as $key => $value)
2174
            {
2175
                // If entity is defined
2176
                if (is_array($value) && isset($value['entity'])) { $entity = $value['entity'];
2177
                }
2178
2179
                $sql = "DELETE FROM ".MAIN_DB_PREFIX."const";
2180
                $sql.= " WHERE ".$this->db->decrypt('name')." LIKE '".$this->db->escape($this->const_name)."_".strtoupper($key)."'";
2181
                $sql.= " AND entity = ".$entity;
2182
2183
                dol_syslog(get_class($this)."::delete_const_".$key."", LOG_DEBUG);
2184
                if (! $this->db->query($sql)) {
2185
                    $this->error=$this->db->lasterror();
2186
                    $err++;
2187
                }
2188
            }
2189
        }
2190
        return $err;
2191
    }
2192
2193
    /**
2194
     * Function called when module is enabled.
2195
     * The init function adds tabs, constants, boxes, permissions and menus (defined in constructor) into Dolibarr database.
2196
     * It also creates data directories
2197
     *
2198
     * @param  string $options Options when enabling module ('', 'newboxdefonly', 'noboxes')
2199
     *                         'noboxes' = Do not insert boxes 'newboxdefonly' = For boxes,
2200
     *                         insert def of boxes only and not boxes activation
2201
     * @return int                1 if OK, 0 if KO
2202
     */
2203
    public function init($options = '')
2204
    {
2205
        return $this->_init(array(), $options);
2206
    }
2207
2208
    /**
2209
     * Function called when module is disabled.
2210
     * The remove function removes tabs, constants, boxes, permissions and menus from Dolibarr database.
2211
     * Data directories are not deleted
2212
     *
2213
     * @param  string $options Options when enabling module ('', 'noboxes')
2214
     * @return int                     1 if OK, 0 if KO
2215
     */
2216
    public function remove($options = '')
2217
    {
2218
        return $this->_remove(array(), $options);
2219
    }
2220
}
2221