Passed
Push — main ( d8f8f2...7eb3b3 )
by Rafael
47:22
created

BlockedLog::getLog()   F

Complexity

Conditions 15
Paths 2048

Size

Total Lines 75
Code Lines 42

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 15
eloc 42
nc 2048
nop 11
dl 0
loc 75
rs 1.7499
c 0
b 0
f 0

How to fix   Long Method    Complexity    Many Parameters   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

1
<?php
2
3
/* Copyright (C) 2017       ATM Consulting      <[email protected]>
4
 * Copyright (C) 2017-2020  Laurent Destailleur <[email protected]>
5
 * Copyright (C) 2022 		charlene benke		<[email protected]>
6
 * Copyright (C) 2024		MDW						<[email protected]>
7
 * Copyright (C) 2024       Rafael San José         <[email protected]>
8
 *
9
 * This program is free software; you can redistribute it and/or modify
10
 * it under the terms of the GNU General Public License as published by
11
 * the Free Software Foundation; either version 3 of the License, or
12
 * (at your option) any later version.
13
 *
14
 * This program is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
 * GNU General Public License for more details.
18
 *
19
 * You should have received a copy of the GNU General Public License
20
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
21
 *
22
 * See https://medium.com/@lhartikk/a-blockchain-in-200-lines-of-code-963cc1cc0e54
23
 */
24
25
26
namespace DoliModules\BlockedLog\Model;
27
28
use CashControl;
29
use DoliDB;
30
use Don;
31
use Facture;
32
use FactureFournisseur;
33
use MouvementStock;
34
use Paiement;
35
use PaiementFourn;
36
use PaymentDonation;
37
use PaymentVarious;
38
use Project;
39
use Subscription;
40
use User;
41
42
/**
43
 *  Class to manage Blocked Log
44
 */
45
class BlockedLog
46
{
47
    /**
48
     * @var DoliDB  Database handler
49
     */
50
    public $db;
51
52
    /**
53
     * Id of the log
54
     * @var int
55
     */
56
    public $id;
57
58
    /**
59
     * Entity
60
     * @var int
61
     */
62
    public $entity;
63
64
    /**
65
     * @var string Error message
66
     */
67
    public $error = '';
68
69
    /**
70
     * @var string[] Error codes (or messages)
71
     */
72
    public $errors = [];
73
74
    /**
75
     * Unique fingerprint of the log
76
     * @var string
77
     */
78
    public $signature = '';
79
80
    /**
81
     * Unique fingerprint of the line log content
82
     * @var string
83
     */
84
    public $signature_line = '';
85
86
    public $amounts = null;
87
88
    /**
89
     * trigger action
90
     * @var string
91
     */
92
    public $action = '';
93
94
    /**
95
     * Object element
96
     * @var string
97
     */
98
    public $element = '';
99
100
    /**
101
     * Object id
102
     * @var int
103
     */
104
    public $fk_object = 0;
105
106
    /**
107
     * Log certified by remote authority or not
108
     * @var boolean
109
     */
110
    public $certified = false;
111
112
    /**
113
     * Author
114
     * @var int
115
     */
116
    public $fk_user = 0;
117
118
    /**
119
     * @var integer|string date_creation
120
     */
121
    public $date_creation;
122
123
    /**
124
     * @var integer|string $date_modification ;
125
     */
126
    public $date_modification;
127
128
    public $date_object = 0;
129
130
    public $ref_object = '';
131
132
    public $object_data = null;
133
    public $object_version = '';
134
135
    public $user_fullname = '';
136
137
    /**
138
     * Array of tracked event codes
139
     * @var string[]
140
     */
141
    public $trackedevents = [];
142
143
144
    /**
145
     *      Constructor
146
     *
147
     * @param DoliDB $db Database handler
148
     */
149
    public function __construct(DoliDB $db)
150
    {
151
        $this->db = $db;
152
    }
153
154
155
    /**
156
     * Load list of tracked events into $this->trackedevents.
157
     *
158
     * @return int          Always 1
159
     */
160
    public function loadTrackedEvents()
161
    {
162
        global $conf;
163
164
        $this->trackedevents = [];
165
166
        // Customer Invoice/Facture / Payment
167
        if (isModEnabled('invoice')) {
168
            $this->trackedevents['BILL_VALIDATE'] = 'logBILL_VALIDATE';
169
            $this->trackedevents['BILL_DELETE'] = 'logBILL_DELETE';
170
            $this->trackedevents['BILL_SENTBYMAIL'] = 'logBILL_SENTBYMAIL';
171
            $this->trackedevents['DOC_DOWNLOAD'] = 'BlockedLogBillDownload';
172
            $this->trackedevents['DOC_PREVIEW'] = 'BlockedLogBillPreview';
173
            $this->trackedevents['PAYMENT_CUSTOMER_CREATE'] = 'logPAYMENT_CUSTOMER_CREATE';
174
            $this->trackedevents['PAYMENT_CUSTOMER_DELETE'] = 'logPAYMENT_CUSTOMER_DELETE';
175
        }
176
177
        /* Supplier
178
        // Supplier Invoice / Payment
179
        if (isModEnabled("fournisseur")) {
180
            $this->trackedevents['BILL_SUPPLIER_VALIDATE']='BlockedLogSupplierBillValidate';
181
            $this->trackedevents['BILL_SUPPLIER_DELETE']='BlockedLogSupplierBillDelete';
182
            $this->trackedevents['BILL_SUPPLIER_SENTBYMAIL']='BlockedLogSupplierBillSentByEmail'; // Trigger key does not exists, we want just into array to list it as done
183
            $this->trackedevents['SUPPLIER_DOC_DOWNLOAD']='BlockedLogSupplierBillDownload';     // Trigger key does not exists, we want just into array to list it as done
184
            $this->trackedevents['SUPPLIER_DOC_PREVIEW']='BlockedLogSupplierBillPreview';       // Trigger key does not exists, we want just into array to list it as done
185
            $this->trackedevents['PAYMENT_SUPPLIER_CREATE']='BlockedLogSupplierBillPaymentCreate';
186
            $this->trackedevents['PAYMENT_SUPPLIER_DELETE']='BlockedLogsupplierBillPaymentCreate';
187
        }
188
         */
189
190
        // Donation
191
        if (isModEnabled('don')) {
192
            $this->trackedevents['DON_VALIDATE'] = 'logDON_VALIDATE';
193
            $this->trackedevents['DON_DELETE'] = 'logDON_DELETE';
194
            //$this->trackedevents['DON_SENTBYMAIL']='logDON_SENTBYMAIL';
195
            $this->trackedevents['DONATION_PAYMENT_CREATE'] = 'logDONATION_PAYMENT_CREATE';
196
            $this->trackedevents['DONATION_PAYMENT_DELETE'] = 'logDONATION_PAYMENT_DELETE';
197
        }
198
199
        /*
200
        // Salary
201
        if (!empty($conf->salary->enabled)) {
202
            $this->trackedevents['PAYMENT_SALARY_CREATE']='BlockedLogSalaryPaymentCreate';
203
            $this->trackedevents['PAYMENT_SALARY_MODIFY']='BlockedLogSalaryPaymentCreate';
204
            $this->trackedevents['PAYMENT_SALARY_DELETE']='BlockedLogSalaryPaymentCreate';
205
        }
206
         */
207
208
        // Members
209
        if (isModEnabled('member')) {
210
            $this->trackedevents['MEMBER_SUBSCRIPTION_CREATE'] = 'logMEMBER_SUBSCRIPTION_CREATE';
211
            $this->trackedevents['MEMBER_SUBSCRIPTION_MODIFY'] = 'logMEMBER_SUBSCRIPTION_MODIFY';
212
            $this->trackedevents['MEMBER_SUBSCRIPTION_DELETE'] = 'logMEMBER_SUBSCRIPTION_DELETE';
213
        }
214
215
        // Bank
216
        if (isModEnabled("bank")) {
217
            $this->trackedevents['PAYMENT_VARIOUS_CREATE'] = 'logPAYMENT_VARIOUS_CREATE';
218
            $this->trackedevents['PAYMENT_VARIOUS_MODIFY'] = 'logPAYMENT_VARIOUS_MODIFY';
219
            $this->trackedevents['PAYMENT_VARIOUS_DELETE'] = 'logPAYMENT_VARIOUS_DELETE';
220
        }
221
222
        // Cashdesk
223
        // $conf->global->BANK_ENABLE_POS_CASHCONTROL must be set to 1 by all external POS modules
224
        $moduleposenabled = (!empty($conf->cashdesk->enabled) || !empty($conf->takepos->enabled) || getDolGlobalString('BANK_ENABLE_POS_CASHCONTROL'));
225
        if ($moduleposenabled) {
226
            $this->trackedevents['CASHCONTROL_VALIDATE'] = 'logCASHCONTROL_VALIDATE';
227
        }
228
229
        // Add more action to track from a conf variable
230
        // For example: STOCK_MOVEMENT,...
231
        if (getDolGlobalString('BLOCKEDLOG_ADD_ACTIONS_SUPPORTED')) {
232
            $tmparrayofmoresupportedevents = explode(',', getDolGlobalString('BLOCKEDLOG_ADD_ACTIONS_SUPPORTED'));
233
            foreach ($tmparrayofmoresupportedevents as $val) {
234
                $this->trackedevents[$val] = 'log' . $val;
235
            }
236
        }
237
238
        return 1;
239
    }
240
241
    /**
242
     * Try to retrieve source object (it it still exists).
243
     *
244
     * @return string       URL string of source object
245
     */
246
    public function getObjectLink()
247
    {
248
        global $langs;
249
250
        if ($this->element === 'facture') {
251
            $object = new Facture($this->db);
252
            if ($object->fetch($this->fk_object) > 0) {
253
                return $object->getNomUrl(1);
254
            } else {
255
                $this->error++;
256
            }
257
        }
258
        if ($this->element === 'invoice_supplier') {
259
            $object = new FactureFournisseur($this->db);
260
            if ($object->fetch($this->fk_object) > 0) {
261
                return $object->getNomUrl(1);
262
            } else {
263
                $this->error++;
264
            }
265
        } elseif ($this->element === 'payment') {
266
            require_once DOL_DOCUMENT_ROOT . '/compta/paiement/class/paiement.class.php';
267
268
            $object = new Paiement($this->db);
269
            if ($object->fetch($this->fk_object) > 0) {
270
                return $object->getNomUrl(1);
271
            } else {
272
                $this->error++;
273
            }
274
        } elseif ($this->element === 'payment_supplier') {
275
            $object = new PaiementFourn($this->db);
276
            if ($object->fetch($this->fk_object) > 0) {
277
                return $object->getNomUrl(1);
278
            } else {
279
                $this->error++;
280
            }
281
        } elseif ($this->element === 'payment_donation') {
282
            $object = new PaymentDonation($this->db);
283
            if ($object->fetch($this->fk_object) > 0) {
284
                return $object->getNomUrl(1);
285
            } else {
286
                $this->error++;
287
            }
288
        } elseif ($this->element === 'payment_various') {
289
            $object = new PaymentVarious($this->db);
290
            if ($object->fetch($this->fk_object) > 0) {
291
                return $object->getNomUrl(1);
292
            } else {
293
                $this->error++;
294
            }
295
        } elseif ($this->element === 'don' || $this->element === 'donation') {
296
            $object = new Don($this->db);
297
            if ($object->fetch($this->fk_object) > 0) {
298
                return $object->getNomUrl(1);
299
            } else {
300
                $this->error++;
301
            }
302
        } elseif ($this->element === 'subscription') {
303
            $object = new Subscription($this->db);
304
            if ($object->fetch($this->fk_object) > 0) {
305
                return $object->getNomUrl(1);
306
            } else {
307
                $this->error++;
308
            }
309
        } elseif ($this->element === 'cashcontrol') {
310
            require_once DOL_DOCUMENT_ROOT . '/compta/cashcontrol/class/cashcontrol.class.php';
311
312
            $object = new CashControl($this->db);
313
            if ($object->fetch($this->fk_object) > 0) {
314
                return $object->getNomUrl(1);
315
            } else {
316
                $this->error++;
317
            }
318
        } elseif ($this->element === 'stockmouvement') {
319
            require_once DOL_DOCUMENT_ROOT . '/product/stock/class/mouvementstock.class.php';
320
321
            $object = new MouvementStock($this->db);
322
            if ($object->fetch($this->fk_object) > 0) {
323
                return $object->getNomUrl(1);
324
            } else {
325
                $this->error++;
326
            }
327
        } elseif ($this->element === 'project') {
328
            $object = new Project($this->db);
329
            if ($object->fetch($this->fk_object) > 0) {
330
                return $object->getNomUrl(1);
331
            } else {
332
                $this->error++;
333
            }
334
        } elseif ($this->action == 'MODULE_SET') {
335
            return '<i class="opacitymedium">' . $langs->trans("BlockedLogEnabled") . '</i>';
336
        } elseif ($this->action == 'MODULE_RESET') {
337
            if ($this->signature == '0000000000') {
338
                return '<i class="opacitymedium">' . $langs->trans("BlockedLogDisabled") . '</i>';
339
            } else {
340
                return '<i class="opacitymedium">' . $langs->trans("BlockedLogDisabledBis") . '</i>';
341
            }
342
        }
343
344
        return '<i class="opacitymedium">' . $langs->trans('ImpossibleToReloadObject', $this->element, $this->fk_object) . '</i>';
345
    }
346
347
    /**
348
     *      try to retrieve user author
349
     * @return string
350
     */
351
    public function getUser()
352
    {
353
        global $langs, $cachedUser;
354
355
        if (empty($cachedUser)) {
356
            // @phan-suppress-next-line PhanPluginRedundantAssignment
357
            $cachedUser = [];
358
        }
359
360
        if (empty($cachedUser[$this->fk_user])) {
361
            $u = new User($this->db);
362
            if ($u->fetch($this->fk_user) > 0) {
363
                $cachedUser[$this->fk_user] = $u;
364
            }
365
        }
366
367
        if (!empty($cachedUser[$this->fk_user])) {
368
            return $cachedUser[$this->fk_user]->getNomUrl(1);
369
        }
370
371
        return $langs->trans('ImpossibleToRetrieveUser', $this->fk_user);
372
    }
373
374
    /**
375
     *      Populate properties of log from object data
376
     *
377
     * @param Object $object  object to store
378
     * @param string $action  action
379
     * @param string $amounts amounts
380
     * @param User   $fuser   User object (forced)
381
     *
382
     * @return     int                     >0 if OK, <0 if KO
383
     */
384
    public function setObjectData(&$object, $action, $amounts, $fuser = null)
385
    {
386
        global $langs, $user, $mysoc;
387
388
        if (is_object($fuser)) {
389
            $user = $fuser;
390
        }
391
392
        // Generic fields
393
394
        // action
395
        $this->action = $action;
396
        // amount
397
        $this->amounts = $amounts;
398
        // date
399
        if ($object->element == 'payment' || $object->element == 'payment_supplier') {
400
            $this->date_object = empty($object->datepaye) ? $object->date : $object->datepaye;
401
        } elseif ($object->element == 'payment_salary') {
402
            $this->date_object = $object->datev;
403
        } elseif ($object->element == 'payment_donation' || $object->element == 'payment_various') {
404
            $this->date_object = empty($object->datepaid) ? $object->datep : $object->datepaid;
405
        } elseif ($object->element == 'subscription') {
406
            $this->date_object = $object->dateh;
407
        } elseif ($object->element == 'cashcontrol') {
408
            $this->date_object = $object->date_creation;
409
        } elseif (property_exists($object, 'date')) {
410
            // Generic case
411
            $this->date_object = $object->date;
412
        } elseif (property_exists($object, 'datem')) {
413
            // Generic case (second chance, for example for stock movement)
414
            $this->date_object = $object->datem;
415
        }
416
417
        // ref
418
        $this->ref_object = ((!empty($object->newref)) ? $object->newref : $object->ref); // newref is set when validating a draft, ref is set in other cases
419
        // type of object
420
        $this->element = $object->element;
421
        // id of object
422
        $this->fk_object = $object->id;
423
424
425
        // Set object_data
426
        $this->object_data = new stdClass();
0 ignored issues
show
Bug introduced by
The type DoliModules\BlockedLog\Model\stdClass was not found. Did you mean stdClass? If so, make sure to prefix the type with \.
Loading history...
427
        // Add fields to exclude
428
        $arrayoffieldstoexclude = [
429
            'table_element', 'fields', 'ref_previous', 'ref_next', 'origin', 'origin_id', 'oldcopy', 'picto', 'error', 'errors', 'model_pdf', 'modelpdf', 'last_main_doc', 'civility_id', 'contact', 'contact_id',
430
            'table_element_line', 'ismultientitymanaged', 'isextrafieldmanaged',
431
            'array_languages',
432
            'childtables',
433
            'contact_ids',
434
            'context',
435
            'labelStatus',
436
            'labelStatusShort',
437
            'linkedObjectsIds',
438
            'linkedObjects',
439
            'fk_delivery_address',
440
            'projet',          // There is already ->fk_project
441
            'restrictiononfksoc',
442
            'specimen',
443
        ];
444
        // Add more fields to exclude depending on object type
445
        if ($this->element == 'cashcontrol') {
446
            $arrayoffieldstoexclude = array_merge($arrayoffieldstoexclude, [
447
                'name', 'lastname', 'firstname', 'region', 'region_id', 'region_code', 'state', 'state_id', 'state_code', 'country', 'country_id', 'country_code',
448
                'total_ht', 'total_tva', 'total_ttc', 'total_localtax1', 'total_localtax2',
449
                'barcode_type', 'barcode_type_code', 'barcode_type_label', 'barcode_type_coder', 'mode_reglement_id', 'cond_reglement_id', 'mode_reglement', 'cond_reglement', 'shipping_method_id',
450
                'fk_incoterms', 'label_incoterms', 'location_incoterms', 'lines',
451
            ]);
452
        }
453
454
        // Add thirdparty info
455
        if (empty($object->thirdparty) && method_exists($object, 'fetch_thirdparty')) {
456
            $object->fetch_thirdparty();
457
        }
458
        if (!empty($object->thirdparty)) {
459
            $this->object_data->thirdparty = new stdClass();
460
461
            foreach ($object->thirdparty as $key => $value) {
462
                if (in_array($key, $arrayoffieldstoexclude)) {
463
                    continue; // Discard some properties
464
                }
465
                if (
466
                    !in_array($key, [
467
                        'name', 'name_alias', 'ref_ext', 'address', 'zip', 'town', 'state_code', 'country_code', 'idprof1', 'idprof2', 'idprof3', 'idprof4', 'idprof5', 'idprof6', 'phone', 'fax', 'email', 'barcode',
468
                        'tva_intra', 'localtax1_assuj', 'localtax1_value', 'localtax2_assuj', 'localtax2_value', 'managers', 'capital', 'typent_code', 'forme_juridique_code', 'code_client', 'code_fournisseur',
469
                    ])
470
                ) {
471
                    continue; // Discard if not into a dedicated list
472
                }
473
                if (!is_object($value) && !is_null($value) && $value !== '') {
474
                    $this->object_data->thirdparty->$key = $value;
475
                }
476
            }
477
        }
478
479
        // Add company info
480
        if (!empty($mysoc)) {
481
            $this->object_data->mycompany = new stdClass();
482
483
            foreach ($mysoc as $key => $value) {
484
                if (in_array($key, $arrayoffieldstoexclude)) {
485
                    continue; // Discard some properties
486
                }
487
                if (
488
                    !in_array($key, [
489
                        'name', 'name_alias', 'ref_ext', 'address', 'zip', 'town', 'state_code', 'country_code', 'idprof1', 'idprof2', 'idprof3', 'idprof4', 'idprof5', 'idprof6', 'phone', 'fax', 'email', 'barcode',
490
                        'tva_intra', 'localtax1_assuj', 'localtax1_value', 'localtax2_assuj', 'localtax2_value', 'managers', 'capital', 'typent_code', 'forme_juridique_code', 'code_client', 'code_fournisseur',
491
                    ])
492
                ) {
493
                    continue; // Discard if not into a dedicated list
494
                }
495
                if (!is_object($value) && !is_null($value) && $value !== '') {
496
                    $this->object_data->mycompany->$key = $value;
497
                }
498
            }
499
        }
500
501
        // Add user info
502
        if (!empty($user)) {
503
            $this->fk_user = $user->id;
504
            $this->user_fullname = $user->getFullName($langs);
505
        }
506
507
        // Field specific to object
508
        if ($this->element == 'facture') {
509
            foreach ($object as $key => $value) {
510
                if (in_array($key, $arrayoffieldstoexclude)) {
511
                    continue; // Discard some properties
512
                }
513
                if (
514
                    !in_array($key, [
515
                        'ref', 'ref_client', 'ref_supplier', 'date', 'datef', 'datev', 'type', 'total_ht', 'total_tva', 'total_ttc', 'localtax1', 'localtax2', 'revenuestamp', 'datepointoftax', 'note_public', 'lines',
516
                    ])
517
                ) {
518
                    continue; // Discard if not into a dedicated list
519
                }
520
                if ($key == 'lines') {
521
                    $lineid = 0;
522
                    foreach ($value as $tmpline) {  // $tmpline is object FactureLine
523
                        $lineid++;
524
                        foreach ($tmpline as $keyline => $valueline) {
525
                            if (
526
                                !in_array($keyline, [
527
                                    'ref', 'multicurrency_code', 'multicurrency_total_ht', 'multicurrency_total_tva', 'multicurrency_total_ttc', 'qty', 'product_type', 'vat_src_code', 'tva_tx', 'info_bits', 'localtax1_tx', 'localtax2_tx', 'total_ht', 'total_tva', 'total_ttc', 'total_localtax1', 'total_localtax2',
528
                                ])
529
                            ) {
530
                                continue; // Discard if not into a dedicated list
531
                            }
532
533
                            if (empty($this->object_data->invoiceline[$lineid]) || !is_object($this->object_data->invoiceline[$lineid])) {      // To avoid warning
534
                                $this->object_data->invoiceline[$lineid] = new stdClass();
535
                            }
536
537
                            if (!is_object($valueline) && !is_null($valueline) && $valueline !== '') {
538
                                $this->object_data->invoiceline[$lineid]->$keyline = $valueline;
539
                            }
540
                        }
541
                    }
542
                } elseif (!is_object($value) && !is_null($value) && $value !== '') {
543
                    $this->object_data->$key = $value;
544
                }
545
            }
546
547
            if (!empty($object->newref)) {
548
                $this->object_data->ref = $object->newref;
549
            }
550
        } elseif ($this->element == 'invoice_supplier') {
551
            foreach ($object as $key => $value) {
552
                if (in_array($key, $arrayoffieldstoexclude)) {
553
                    continue; // Discard some properties
554
                }
555
                if (
556
                    !in_array($key, [
557
                        'ref', 'ref_client', 'ref_supplier', 'date', 'datef', 'type', 'total_ht', 'total_tva', 'total_ttc', 'localtax1', 'localtax2', 'revenuestamp', 'datepointoftax', 'note_public',
558
                    ])
559
                ) {
560
                    continue; // Discard if not into a dedicated list
561
                }
562
                if (!is_object($value) && !is_null($value) && $value !== '') {
563
                    $this->object_data->$key = $value;
564
                }
565
            }
566
567
            if (!empty($object->newref)) {
568
                $this->object_data->ref = $object->newref;
569
            }
570
        } elseif ($this->element == 'payment' || $this->element == 'payment_supplier' || $this->element == 'payment_donation' || $this->element == 'payment_various') {
571
            $datepayment = $object->datepaye ? $object->datepaye : ($object->datepaid ? $object->datepaid : $object->datep);
572
            $paymenttypeid = $object->paiementid ? $object->paiementid : ($object->paymenttype ? $object->paymenttype : $object->type_payment);
573
574
            $this->object_data->ref = $object->ref;
575
            $this->object_data->date = $datepayment;
576
            $this->object_data->type_code = dol_getIdFromCode($this->db, $paymenttypeid, 'c_paiement', 'id', 'code');
577
578
            if (!empty($object->num_payment)) {
579
                $this->object_data->payment_num = $object->num_payment;
580
            }
581
            if (!empty($object->note_private)) {
582
                $this->object_data->note_private = $object->note_private;
583
            }
584
            //$this->object_data->fk_account = $object->fk_account;
585
            //var_dump($this->object_data);exit;
586
587
            $totalamount = 0;
588
589
            // Loop on each invoice payment amount (payment_part)
590
            if (is_array($object->amounts) && !empty($object->amounts)) {
591
                $paymentpartnumber = 0;
592
                foreach ($object->amounts as $objid => $amount) {
593
                    if (empty($amount)) {
594
                        continue;
595
                    }
596
597
                    $totalamount += $amount;
598
599
                    $tmpobject = null;
600
                    if ($this->element == 'payment_supplier') {
601
                        $tmpobject = new FactureFournisseur($this->db);
602
                    } elseif ($this->element == 'payment') {
603
                        $tmpobject = new Facture($this->db);
604
                    } elseif ($this->element == 'payment_donation') {
605
                        include_once DOL_DOCUMENT_ROOT . '/don/class/don.class.php';
606
                        $tmpobject = new Don($this->db);
607
                    } elseif ($this->element == 'payment_various') {
608
                        include_once DOL_DOCUMENT_ROOT . '/compta/bank/class/paymentvarious.class.php';
609
                        $tmpobject = new PaymentVarious($this->db);
610
                    }
611
612
                    if (!is_object($tmpobject)) {
613
                        continue;
614
                    }
615
616
                    $result = $tmpobject->fetch($objid);
617
618
                    if ($result <= 0) {
619
                        $this->error = $tmpobject->error;
620
                        $this->errors = $tmpobject->errors;
621
                        dol_syslog("Failed to fetch object with id " . $objid, LOG_ERR);
622
                        return -1;
623
                    }
624
625
                    $paymentpart = new stdClass();
626
                    $paymentpart->amount = $amount;
627
628
                    if (!in_array($this->element, ['payment_donation', 'payment_various'])) {
629
                        $result = $tmpobject->fetch_thirdparty();
630
                        if ($result == 0) {
631
                            $this->error = 'Failed to fetch thirdparty for object with id ' . $tmpobject->id;
632
                            $this->errors[] = $this->error;
633
                            dol_syslog("Failed to fetch thirdparty for object with id " . $tmpobject->id, LOG_ERR);
634
                            return -1;
635
                        } elseif ($result < 0) {
636
                            $this->error = $tmpobject->error;
637
                            $this->errors = $tmpobject->errors;
638
                            return -1;
639
                        }
640
641
                        $paymentpart->thirdparty = new stdClass();
642
                        foreach ($tmpobject->thirdparty as $key => $value) {
643
                            if (in_array($key, $arrayoffieldstoexclude)) {
644
                                continue; // Discard some properties
645
                            }
646
                            if (
647
                                !in_array($key, [
648
                                    'name', 'name_alias', 'ref_ext', 'address', 'zip', 'town', 'state_code', 'country_code', 'idprof1', 'idprof2', 'idprof3', 'idprof4', 'idprof5', 'idprof6', 'phone', 'fax', 'email', 'barcode',
649
                                    'tva_intra', 'localtax1_assuj', 'localtax1_value', 'localtax2_assuj', 'localtax2_value', 'managers', 'capital', 'typent_code', 'forme_juridique_code', 'code_client', 'code_fournisseur',
650
                                ])
651
                            ) {
652
                                continue; // Discard if not into a dedicated list
653
                            }
654
                            if (!is_object($value) && !is_null($value) && $value !== '') {
655
                                $paymentpart->thirdparty->$key = $value;
656
                            }
657
                        }
658
                    }
659
660
                    // Init object to avoid warnings
661
                    if ($this->element == 'payment_donation') {
662
                        $paymentpart->donation = new stdClass();
663
                    } else {
664
                        $paymentpart->invoice = new stdClass();
665
                    }
666
667
                    if ($this->element != 'payment_various') {
668
                        foreach ($tmpobject as $key => $value) {
669
                            if (in_array($key, $arrayoffieldstoexclude)) {
670
                                continue; // Discard some properties
671
                            }
672
                            if (
673
                                !in_array($key, [
674
                                    'ref', 'ref_client', 'ref_supplier', 'date', 'datef', 'type', 'total_ht', 'total_tva', 'total_ttc', 'localtax1', 'localtax2', 'revenuestamp', 'datepointoftax', 'note_public',
675
                                ])
676
                            ) {
677
                                continue; // Discard if not into a dedicated list
678
                            }
679
                            if (!is_object($value) && !is_null($value) && $value !== '') {
680
                                if ($this->element == 'payment_donation') {
681
                                    $paymentpart->donation->$key = $value;
682
                                } elseif ($this->element == 'payment_various') {
683
                                    $paymentpart->various->$key = $value;
684
                                } else {
685
                                    $paymentpart->invoice->$key = $value;
686
                                }
687
                            }
688
                        }
689
690
                        $paymentpartnumber++; // first payment will be 1
691
                        $this->object_data->payment_part[$paymentpartnumber] = $paymentpart;
692
                    }
693
                }
694
            } elseif (!empty($object->amount)) {
695
                $totalamount = $object->amount;
696
            }
697
698
            $this->object_data->amount = $totalamount;
699
700
            if (!empty($object->newref)) {
701
                $this->object_data->ref = $object->newref;
702
            }
703
        } elseif ($this->element == 'payment_salary') {
704
            $this->object_data->amounts = [$object->amount];
705
706
            if (!empty($object->newref)) {
707
                $this->object_data->ref = $object->newref;
708
            }
709
        } elseif ($this->element == 'subscription') {
710
            foreach ($object as $key => $value) {
711
                if (in_array($key, $arrayoffieldstoexclude)) {
712
                    continue; // Discard some properties
713
                }
714
                if (
715
                    !in_array($key, [
716
                        'id', 'datec', 'dateh', 'datef', 'fk_adherent', 'amount', 'import_key', 'statut', 'note',
717
                    ])
718
                ) {
719
                    continue; // Discard if not into a dedicated list
720
                }
721
                if (!is_object($value) && !is_null($value) && $value !== '') {
722
                    $this->object_data->$key = $value;
723
                }
724
            }
725
726
            if (!empty($object->newref)) {
727
                $this->object_data->ref = $object->newref;
728
            }
729
        } elseif ($this->element == 'stockmouvement') {
730
            foreach ($object as $key => $value) {
731
                if (in_array($key, $arrayoffieldstoexclude)) {
732
                    continue; // Discard some properties
733
                }
734
                if (!is_object($value) && !is_null($value) && $value !== '') {
735
                    $this->object_data->$key = $value;
736
                }
737
            }
738
        } else {
739
            // Generic case
740
            foreach ($object as $key => $value) {
741
                if (in_array($key, $arrayoffieldstoexclude)) {
742
                    continue; // Discard some properties
743
                }
744
                if (!is_object($value) && !is_null($value) && $value !== '') {
745
                    $this->object_data->$key = $value;
746
                }
747
            }
748
749
            if (!empty($object->newref)) {
750
                $this->object_data->ref = $object->newref;
751
            }
752
        }
753
754
        // A trick to be sure all the object_data is an associative array
755
        // json_encode and json_decode are not able to manage mixed object (with array/object, only full arrays or full objects)
756
        $this->object_data = json_decode(json_encode($this->object_data, JSON_FORCE_OBJECT), false);
757
758
        return 1;
759
    }
760
761
    /**
762
     *  Get object from database
763
     *
764
     * @param int $id Id of object to load
765
     *
766
     * @return     int                     >0 if OK, <0 if KO, 0 if not found
767
     */
768
    public function fetch($id)
769
    {
770
        global $langs;
771
772
        if (empty($id)) {
773
            $this->error = 'BadParameter';
774
            return -1;
775
        }
776
777
        $sql = "SELECT b.rowid, b.date_creation, b.signature, b.signature_line, b.amounts, b.action, b.element, b.fk_object, b.entity,";
778
        $sql .= " b.certified, b.tms, b.fk_user, b.user_fullname, b.date_object, b.ref_object, b.object_data, b.object_version";
779
        $sql .= " FROM " . MAIN_DB_PREFIX . "blockedlog as b";
780
        if ($id) {
781
            $sql .= " WHERE b.rowid = " . ((int) $id);
782
        }
783
784
        $resql = $this->db->query($sql);
785
        if ($resql) {
786
            $obj = $this->db->fetch_object($resql);
787
            if ($obj) {
788
                $this->id = $obj->rowid;
789
                $this->entity = $obj->entity;
790
791
                $this->date_creation = $this->db->jdate($obj->date_creation);
792
                $this->date_modification = $this->db->jdate($obj->tms);
793
794
                $this->amounts = (float) $obj->amounts;
795
                $this->action = $obj->action;
796
                $this->element = $obj->element;
797
798
                $this->fk_object = $obj->fk_object;
799
                $this->date_object = $this->db->jdate($obj->date_object);
800
                $this->ref_object = $obj->ref_object;
801
802
                $this->fk_user = $obj->fk_user;
803
                $this->user_fullname = $obj->user_fullname;
804
805
                $this->object_data = $this->dolDecodeBlockedData($obj->object_data);
806
                $this->object_version = $obj->object_version;
807
808
                $this->signature = $obj->signature;
809
                $this->signature_line = $obj->signature_line;
810
                $this->certified = ($obj->certified == 1);
811
812
                return 1;
813
            } else {
814
                $langs->load("blockedlog");
815
                $this->error = $langs->trans("RecordNotFound");
816
                return 0;
817
            }
818
        } else {
819
            $this->error = $this->db->error();
820
            return -1;
821
        }
822
    }
823
824
825
    /**
826
     * Encode data
827
     *
828
     * @param string $data Data to serialize
829
     * @param int    $mode 0=serialize, 1=json_encode
830
     *
831
     * @return  string          Value serialized, an object (stdClass)
832
     */
833
    public function dolEncodeBlockedData($data, $mode = 0)
834
    {
835
        try {
836
            $aaa = json_encode($data);
837
        } catch (Exception $e) {
0 ignored issues
show
Bug introduced by
The type DoliModules\BlockedLog\Model\Exception was not found. Did you mean Exception? If so, make sure to prefix the type with \.
Loading history...
838
            //print $e->getErrs);
839
        }
840
        //var_dump($aaa);
841
842
        return $aaa;
843
    }
844
845
846
    /**
847
     * Decode data
848
     *
849
     * @param string $data Data to unserialize
850
     * @param int    $mode 0=unserialize, 1=json_decode
851
     *
852
     * @return  object          Value unserialized, an object (stdClass)
853
     */
854
    public function dolDecodeBlockedData($data, $mode = 0)
855
    {
856
        try {
857
            $aaa = (object) jsonOrUnserialize($data);
858
        } catch (Exception $e) {
859
            //print $e->getErrs);
860
        }
861
        //var_dump($aaa);
862
863
        return $aaa;
864
    }
865
866
867
    /**
868
     *  Set block certified by authority
869
     *
870
     * @return boolean
871
     */
872
    public function setCertified()
873
    {
874
        $res = $this->db->query("UPDATE " . MAIN_DB_PREFIX . "blockedlog SET certified=1 WHERE rowid=" . ((int) $this->id));
875
        if (!$res) {
876
            return false;
877
        }
878
879
        return true;
880
    }
881
882
    /**
883
     *  Create blocked log in database.
884
     *
885
     * @param User   $user           Object user that create
886
     * @param string $forcesignature Force signature (for example '0000000000' when we disabled the module)
887
     *
888
     * @return int                         Return integer <0 if KO, >0 if OK
889
     */
890
    public function create($user, $forcesignature = '')
891
    {
892
        global $conf, $langs, $hookmanager;
893
894
        $langs->load('blockedlog');
895
896
        $error = 0;
897
898
        // Clean data
899
        $this->amounts = (float) $this->amounts;
900
901
        dol_syslog(get_class($this) . '::create action=' . $this->action . ' fk_user=' . $this->fk_user . ' user_fullname=' . $this->user_fullname, LOG_DEBUG);
902
903
        // Check parameters/properties
904
        if (!isset($this->amounts)) {   // amount can be 0 for some events (like when module is disabled)
905
            $this->error = $langs->trans("BlockLogNeedAmountsValue");
906
            dol_syslog($this->error, LOG_WARNING);
907
            return -1;
908
        }
909
910
        if (empty($this->element)) {
911
            $this->error = $langs->trans("BlockLogNeedElement");
912
            dol_syslog($this->error, LOG_WARNING);
913
            return -2;
914
        }
915
916
        if (empty($this->action)) {
917
            $this->error = $langs->trans("BadParameterWhenCallingCreateOfBlockedLog");
918
            dol_syslog($this->error, LOG_WARNING);
919
            return -3;
920
        }
921
        if (empty($this->fk_user)) {
922
            $this->user_fullname = '(Anonymous)';
923
        }
924
925
        $this->date_creation = dol_now();
926
927
        $this->object_version = ((float) DOL_VERSION);
0 ignored issues
show
Bug introduced by
The constant DoliModules\BlockedLog\Model\DOL_VERSION was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
928
929
930
        $this->db->begin();
931
932
        $previoushash = $this->getPreviousHash(1, 0); // This get last record and lock database until insert is done
933
934
        $keyforsignature = $this->buildKeyForSignature();
935
936
        include_once BASE_PATH . '/../Dolibarr/Lib/Security.php';
937
938
        $this->signature_line = dol_hash($keyforsignature, '5'); // Not really useful
939
        $this->signature = dol_hash($previoushash . $keyforsignature, '5');
940
        if ($forcesignature) {
941
            $this->signature = $forcesignature;
942
        }
943
        //var_dump($keyforsignature);var_dump($previoushash);var_dump($this->signature_line);var_dump($this->signature);
944
945
        $sql = "INSERT INTO " . MAIN_DB_PREFIX . "blockedlog (";
946
        $sql .= " date_creation,";
947
        $sql .= " action,";
948
        $sql .= " amounts,";
949
        $sql .= " signature,";
950
        $sql .= " signature_line,";
951
        $sql .= " element,";
952
        $sql .= " fk_object,";
953
        $sql .= " date_object,";
954
        $sql .= " ref_object,";
955
        $sql .= " object_data,";
956
        $sql .= " object_version,";
957
        $sql .= " certified,";
958
        $sql .= " fk_user,";
959
        $sql .= " user_fullname,";
960
        $sql .= " entity";
961
        $sql .= ") VALUES (";
962
        $sql .= "'" . $this->db->idate($this->date_creation) . "',";
963
        $sql .= "'" . $this->db->escape($this->action) . "',";
964
        $sql .= $this->amounts . ",";
965
        $sql .= "'" . $this->db->escape($this->signature) . "',";
966
        $sql .= "'" . $this->db->escape($this->signature_line) . "',";
967
        $sql .= "'" . $this->db->escape($this->element) . "',";
968
        $sql .= $this->fk_object . ",";
969
        $sql .= "'" . $this->db->idate($this->date_object) . "',";
970
        $sql .= "'" . $this->db->escape($this->ref_object) . "',";
971
        $sql .= "'" . $this->db->escape($this->dolEncodeBlockedData($this->object_data)) . "',";
972
        $sql .= "'" . $this->db->escape($this->object_version) . "',";
973
        $sql .= "0,";
974
        $sql .= $this->fk_user . ",";
975
        $sql .= "'" . $this->db->escape($this->user_fullname) . "',";
976
        $sql .= ($this->entity ? $this->entity : $conf->entity);
977
        $sql .= ")";
978
979
        /*
980
        $a = serialize($this->object_data); $a2 = unserialize($a); $a4 = print_r($a2, true);
981
        $b = json_encode($this->object_data); $b2 = json_decode($b); $b4 = print_r($b2, true);
982
        var_dump($a4 == print_r($this->object_data, true) ? 'a=a' : 'a not = a');
983
        var_dump($b4 == print_r($this->object_data, true) ? 'b=b' : 'b not = b');
984
        exit;
985
        */
986
987
        $res = $this->db->query($sql);
988
        if ($res) {
989
            $id = $this->db->last_insert_id(MAIN_DB_PREFIX . "blockedlog");
990
991
            if ($id > 0) {
992
                $this->id = $id;
993
994
                $this->db->commit();
995
996
                return $this->id;
997
            } else {
998
                $this->db->rollback();
999
                return -2;
1000
            }
1001
        } else {
1002
            $this->error = $this->db->error();
1003
            $this->db->rollback();
1004
            return -1;
1005
        }
1006
1007
        // The commit will release the lock so we can insert nex record
1008
    }
1009
1010
    /**
1011
     *  Check if current signature still correct compared to the value in chain
1012
     *
1013
     * @param string $previoushash If previous signature hash is known, we can provide it to avoid to make a search of
1014
     *                             it in database.
1015
     * @param int    $returnarray  1=Return array of details, 2=Return array of details including keyforsignature,
1016
     *                             0=Boolean
1017
     *
1018
     * @return boolean|array                       True if OK, False if KO
1019
     */
1020
    public function checkSignature($previoushash = '', $returnarray = 0)
1021
    {
1022
        if (empty($previoushash)) {
1023
            $previoushash = $this->getPreviousHash(0, $this->id);
1024
        }
1025
        // Recalculate hash
1026
        $keyforsignature = $this->buildKeyForSignature();
1027
1028
        //$signature_line = dol_hash($keyforsignature, '5'); // Not really useful
1029
        $signature = dol_hash($previoushash . $keyforsignature, 'sha256');
1030
        //var_dump($previoushash); var_dump($keyforsignature); var_dump($signature_line); var_dump($signature);
1031
1032
        $res = ($signature === $this->signature);
1033
1034
        if (!$res) {
1035
            $this->error = 'Signature KO';
1036
        }
1037
1038
        if ($returnarray) {
1039
            if ($returnarray == 1) {
1040
                unset($keyforsignature);
1041
                return ['checkresult' => $res, 'calculatedsignature' => $signature, 'previoushash' => $previoushash];
1042
            } else {    // Consume much memory ($keyforsignature is a large var)
1043
                return ['checkresult' => $res, 'calculatedsignature' => $signature, 'previoushash' => $previoushash, 'keyforsignature' => $keyforsignature];
1044
            }
1045
        } else {
1046
            unset($keyforsignature);
1047
            return $res;
1048
        }
1049
    }
1050
1051
    /**
1052
     * Return a string for signature.
1053
     * Note: rowid of line not included as it is not a business data and this allow to make backup of a year
1054
     * and restore it into another database with different id without comprimising checksums
1055
     *
1056
     * @return string       Key for signature
1057
     */
1058
    private function buildKeyForSignature()
1059
    {
1060
        //print_r($this->object_data);
1061
        if (((int) $this->object_version) >= 18) {
1062
            return $this->date_creation . '|' . $this->action . '|' . $this->amounts . '|' . $this->ref_object . '|' . $this->date_object . '|' . $this->user_fullname . '|' . json_encode($this->object_data, JSON_FORCE_OBJECT);
1063
        } else {
1064
            return $this->date_creation . '|' . $this->action . '|' . $this->amounts . '|' . $this->ref_object . '|' . $this->date_object . '|' . $this->user_fullname . '|' . print_r($this->object_data, true);
1065
        }
1066
    }
1067
1068
1069
    /**
1070
     *  Get previous signature/hash in chain
1071
     *
1072
     * @param int $withlock 1=With a lock
1073
     * @param int $beforeid ID of a record
1074
     *
1075
     * @return string              Hash of previous record (if beforeid is defined) or hash of last record (if beforeid
1076
     *                             is 0)
1077
     */
1078
    public function getPreviousHash($withlock = 0, $beforeid = 0)
1079
    {
1080
        global $conf;
1081
1082
        $previoussignature = '';
1083
1084
        $sql = "SELECT rowid, signature FROM " . MAIN_DB_PREFIX . "blockedlog";
1085
        $sql .= " WHERE entity = " . ((int) $conf->entity);
1086
        if ($beforeid) {
1087
            $sql .= " AND rowid < " . (int) $beforeid;
1088
        }
1089
        $sql .= " ORDER BY rowid DESC LIMIT 1";
1090
        $sql .= ($withlock ? " FOR UPDATE " : "");
1091
1092
        $resql = $this->db->query($sql);
1093
        if ($resql) {
1094
            $obj = $this->db->fetch_object($resql);
1095
            if ($obj) {
1096
                $previoussignature = $obj->signature;
1097
            }
1098
        } else {
1099
            dol_print_error($this->db);
1100
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
1101
        }
1102
1103
        if (empty($previoussignature)) {
1104
            // First signature line (line 0)
1105
            $previoussignature = $this->getSignature();
1106
        }
1107
1108
        return $previoussignature;
1109
    }
1110
1111
    /**
1112
     *  Return array of log objects (with criteria)
1113
     *
1114
     * @param string $element        element to search
1115
     * @param int    $fk_object      id of object to search
1116
     * @param int    $limit          max number of element, 0 for all
1117
     * @param string $sortfield      sort field
1118
     * @param string $sortorder      sort order
1119
     * @param int    $search_fk_user id of user(s)
1120
     * @param int    $search_start   start time limit
1121
     * @param int    $search_end     end time limit
1122
     * @param string $search_ref     search ref
1123
     * @param string $search_amount  search amount
1124
     * @param string $search_code    search code
1125
     *
1126
     * @return array|int               Array of object log or <0 if error
1127
     */
1128
    public function getLog($element, $fk_object, $limit = 0, $sortfield = '', $sortorder = '', $search_fk_user = -1, $search_start = -1, $search_end = -1, $search_ref = '', $search_amount = '', $search_code = '')
1129
    {
1130
        global $conf;
1131
        //global $cachedlogs;
1132
1133
        /* $cachedlogs allow fastest search */
1134
        //if (empty($cachedlogs)) $cachedlogs = array();
1135
1136
        if ($element == 'all') {
1137
            $sql = "SELECT rowid FROM " . MAIN_DB_PREFIX . "blockedlog
1138
			 WHERE entity=" . $conf->entity;
1139
        } elseif ($element == 'not_certified') {
1140
            $sql = "SELECT rowid FROM " . MAIN_DB_PREFIX . "blockedlog
1141
			 WHERE entity=" . $conf->entity . " AND certified = 0";
1142
        } elseif ($element == 'just_certified') {
1143
            $sql = "SELECT rowid FROM " . MAIN_DB_PREFIX . "blockedlog
1144
			 WHERE entity=" . $conf->entity . " AND certified = 1";
1145
        } else {
1146
            $sql = "SELECT rowid FROM " . MAIN_DB_PREFIX . "blockedlog
1147
			 WHERE entity=" . $conf->entity . " AND element = '" . $this->db->escape($element) . "'";
1148
        }
1149
1150
        if ($fk_object) {
1151
            $sql .= natural_search("rowid", $fk_object, 1);
1152
        }
1153
        if ($search_fk_user > 0) {
1154
            $sql .= natural_search("fk_user", $search_fk_user, 2);
1155
        }
1156
        if ($search_start > 0) {
1157
            $sql .= " AND date_creation >= '" . $this->db->idate($search_start) . "'";
1158
        }
1159
        if ($search_end > 0) {
1160
            $sql .= " AND date_creation <= '" . $this->db->idate($search_end) . "'";
1161
        }
1162
        if ($search_ref != '') {
1163
            $sql .= natural_search("ref_object", $search_ref);
1164
        }
1165
        if ($search_amount != '') {
1166
            $sql .= natural_search("amounts", $search_amount, 1);
1167
        }
1168
        if ($search_code != '' && $search_code != '-1') {
1169
            $sql .= natural_search("action", $search_code, 3);
1170
        }
1171
1172
        $sql .= $this->db->order($sortfield, $sortorder);
1173
        $sql .= $this->db->plimit($limit + 1); // We want more, because we will stop into loop later with error if we reach max
1174
1175
        $res = $this->db->query($sql);
1176
        if ($res) {
1177
            $results = [];
1178
1179
            $i = 0;
1180
            while ($obj = $this->db->fetch_object($res)) {
1181
                $i++;
1182
                if ($i > $limit) {
1183
                    // Too many record, we will consume too much memory
1184
                    return -2;
1185
                }
1186
1187
                //if (!isset($cachedlogs[$obj->rowid]))
1188
                //{
1189
                $b = new BlockedLog($this->db);
1190
                $b->fetch($obj->rowid);
1191
                //$b->loadTrackedEvents();
1192
                //$cachedlogs[$obj->rowid] = $b;
1193
                //}
1194
1195
                //$results[] = $cachedlogs[$obj->rowid];
1196
                $results[] = $b;
1197
            }
1198
1199
            return $results;
1200
        }
1201
1202
        return -1;
1203
    }
1204
1205
    /**
1206
     *  Return the signature (hash) of the "genesis-block" (Block 0).
1207
     *
1208
     * @return string                  Signature of genesis-block for current conf->entity
1209
     */
1210
    public function getSignature()
1211
    {
1212
        global $db, $conf, $mysoc;
1213
1214
        if (!getDolGlobalString('BLOCKEDLOG_ENTITY_FINGERPRINT')) { // creation of a unique fingerprint
1215
            require_once BASE_PATH . '/../Dolibarr/Lib/Admin.php';
1216
            require_once BASE_PATH . '/../Dolibarr/Lib/Security.php';
1217
            require_once BASE_PATH . '/../Dolibarr/Lib/Security2.php';
1218
1219
            $fingerprint = dol_hash(print_r($mysoc, true) . getRandomPassword(1), '5');
1220
1221
            dolibarr_set_const($db, 'BLOCKEDLOG_ENTITY_FINGERPRINT', $fingerprint, 'chaine', 0, 'Numeric Unique Fingerprint', $conf->entity);
1222
1223
            $conf->global->BLOCKEDLOG_ENTITY_FINGERPRINT = $fingerprint;
1224
        }
1225
1226
        return $conf->global->BLOCKEDLOG_ENTITY_FINGERPRINT;
1227
    }
1228
1229
1230
    /**
1231
     * Check if module was already used or not for at least one recording.
1232
     *
1233
     * @param int $ignoresystem Ignore system events for the test
1234
     *
1235
     * @return  bool
1236
     */
1237
    public function alreadyUsed($ignoresystem = 0)
1238
    {
1239
        global $conf;
1240
1241
        $result = false;
1242
1243
        $sql = "SELECT rowid FROM " . MAIN_DB_PREFIX . "blockedlog";
1244
        $sql .= " WHERE entity = " . $conf->entity;
1245
        if ($ignoresystem) {
1246
            $sql .= " AND action not in ('MODULE_SET','MODULE_RESET')";
1247
        }
1248
        $sql .= $this->db->plimit(1);
1249
1250
        $res = $this->db->query($sql);
1251
        if ($res !== false) {
1252
            $obj = $this->db->fetch_object($res);
1253
            if ($obj) {
1254
                $result = true;
1255
            }
1256
        } else {
1257
            dol_print_error($this->db);
1258
        }
1259
1260
        dol_syslog("Module Blockedlog alreadyUsed with ignoresystem=" . $ignoresystem . " is " . json_encode($result));
1261
1262
        return $result;
1263
    }
1264
}
1265