Passed
Pull Request — dev (#6)
by Rafael
79:24 queued 24:08
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
namespace Dolibarr\Code\BloquedLog\Classes;
26
27
use CashControl;
28
use Dolibarr\Code\Adherents\Classes\Subscription;
29
use Dolibarr\Code\Compta\Classes\Facture;
30
use Dolibarr\Code\Don\Classes\Don;
31
use Dolibarr\Code\Don\Classes\PaymentDonation;
32
use Dolibarr\Code\Fourn\Classes\FactureFournisseur;
33
use Dolibarr\Code\Fourn\Classes\PaiementFourn;
34
use Dolibarr\Code\Product\Classes\MouvementStock;
35
use Dolibarr\Code\Projet\Classes\Project;
36
use Dolibarr\Code\User\Classes\User;
37
use Dolibarr\Core\Base\CommonObject;
38
use DoliDB;
39
use Paiement;
40
use PaymentVarious;
41
use stdClass;
42
43
/**
44
 *  Class to manage Blocked Log
45
 */
46
class BlockedLog
47
{
48
    /**
49
     * @var DoliDB  Database handler
50
     */
51
    public $db;
52
53
    /**
54
     * Id of the log
55
     * @var int
56
     */
57
    public $id;
58
59
    /**
60
     * Entity
61
     * @var int
62
     */
63
    public $entity;
64
65
    /**
66
     * @var string Error message
67
     */
68
    public $error = '';
69
70
    /**
71
     * @var string[] Error codes (or messages)
72
     */
73
    public $errors = array();
74
75
    /**
76
     * Unique fingerprint of the log
77
     * @var string
78
     */
79
    public $signature = '';
80
81
    /**
82
     * Unique fingerprint of the line log content
83
     * @var string
84
     */
85
    public $signature_line = '';
86
87
    public $amounts = null;
88
89
    /**
90
     * trigger action
91
     * @var string
92
     */
93
    public $action = '';
94
95
    /**
96
     * Object element
97
     * @var string
98
     */
99
    public $element = '';
100
101
    /**
102
     * Object id
103
     * @var int
104
     */
105
    public $fk_object = 0;
106
107
    /**
108
     * Log certified by remote authority or not
109
     * @var boolean
110
     */
111
    public $certified = false;
112
113
    /**
114
     * Author
115
     * @var int
116
     */
117
    public $fk_user = 0;
118
119
    /**
120
     * @var integer|string date_creation
121
     */
122
    public $date_creation;
123
124
    /**
125
     * @var integer|string $date_modification;
126
     */
127
    public $date_modification;
128
129
    public $date_object = 0;
130
131
    public $ref_object = '';
132
133
    public $object_data = null;
134
    public $object_version = '';
135
136
    public $user_fullname = '';
137
138
    /**
139
     * Array of tracked event codes
140
     * @var string[]
141
     */
142
    public $trackedevents = array();
143
144
145
146
    /**
147
     *      Constructor
148
     *
149
     *      @param      DoliDB      $db      Database handler
150
     */
151
    public function __construct(DoliDB $db)
152
    {
153
        $this->db = $db;
154
    }
155
156
157
    /**
158
     * Load list of tracked events into $this->trackedevents.
159
     *
160
     * @return int          Always 1
161
     */
162
    public function loadTrackedEvents()
163
    {
164
        global $conf;
165
166
        $this->trackedevents = array();
167
168
        // Customer Invoice/Facture / Payment
169
        if (isModEnabled('invoice')) {
170
            $this->trackedevents['BILL_VALIDATE'] = 'logBILL_VALIDATE';
171
            $this->trackedevents['BILL_DELETE'] = 'logBILL_DELETE';
172
            $this->trackedevents['BILL_SENTBYMAIL'] = 'logBILL_SENTBYMAIL';
173
            $this->trackedevents['DOC_DOWNLOAD'] = 'BlockedLogBillDownload';
174
            $this->trackedevents['DOC_PREVIEW'] = 'BlockedLogBillPreview';
175
            $this->trackedevents['PAYMENT_CUSTOMER_CREATE'] = 'logPAYMENT_CUSTOMER_CREATE';
176
            $this->trackedevents['PAYMENT_CUSTOMER_DELETE'] = 'logPAYMENT_CUSTOMER_DELETE';
177
        }
178
179
        /* Supplier
180
        // Supplier Invoice / Payment
181
        if (isModEnabled("fournisseur")) {
182
            $this->trackedevents['BILL_SUPPLIER_VALIDATE']='BlockedLogSupplierBillValidate';
183
            $this->trackedevents['BILL_SUPPLIER_DELETE']='BlockedLogSupplierBillDelete';
184
            $this->trackedevents['BILL_SUPPLIER_SENTBYMAIL']='BlockedLogSupplierBillSentByEmail'; // Trigger key does not exists, we want just into array to list it as done
185
            $this->trackedevents['SUPPLIER_DOC_DOWNLOAD']='BlockedLogSupplierBillDownload';     // Trigger key does not exists, we want just into array to list it as done
186
            $this->trackedevents['SUPPLIER_DOC_PREVIEW']='BlockedLogSupplierBillPreview';       // Trigger key does not exists, we want just into array to list it as done
187
            $this->trackedevents['PAYMENT_SUPPLIER_CREATE']='BlockedLogSupplierBillPaymentCreate';
188
            $this->trackedevents['PAYMENT_SUPPLIER_DELETE']='BlockedLogsupplierBillPaymentCreate';
189
        }
190
         */
191
192
        // Donation
193
        if (isModEnabled('don')) {
194
            $this->trackedevents['DON_VALIDATE'] = 'logDON_VALIDATE';
195
            $this->trackedevents['DON_DELETE'] = 'logDON_DELETE';
196
            //$this->trackedevents['DON_SENTBYMAIL']='logDON_SENTBYMAIL';
197
            $this->trackedevents['DONATION_PAYMENT_CREATE'] = 'logDONATION_PAYMENT_CREATE';
198
            $this->trackedevents['DONATION_PAYMENT_DELETE'] = 'logDONATION_PAYMENT_DELETE';
199
        }
200
201
        /*
202
        // Salary
203
        if (!empty($conf->salary->enabled)) {
204
            $this->trackedevents['PAYMENT_SALARY_CREATE']='BlockedLogSalaryPaymentCreate';
205
            $this->trackedevents['PAYMENT_SALARY_MODIFY']='BlockedLogSalaryPaymentCreate';
206
            $this->trackedevents['PAYMENT_SALARY_DELETE']='BlockedLogSalaryPaymentCreate';
207
        }
208
         */
209
210
        // Members
211
        if (isModEnabled('member')) {
212
            $this->trackedevents['MEMBER_SUBSCRIPTION_CREATE'] = 'logMEMBER_SUBSCRIPTION_CREATE';
213
            $this->trackedevents['MEMBER_SUBSCRIPTION_MODIFY'] = 'logMEMBER_SUBSCRIPTION_MODIFY';
214
            $this->trackedevents['MEMBER_SUBSCRIPTION_DELETE'] = 'logMEMBER_SUBSCRIPTION_DELETE';
215
        }
216
217
        // Bank
218
        if (isModEnabled("bank")) {
219
            $this->trackedevents['PAYMENT_VARIOUS_CREATE'] = 'logPAYMENT_VARIOUS_CREATE';
220
            $this->trackedevents['PAYMENT_VARIOUS_MODIFY'] = 'logPAYMENT_VARIOUS_MODIFY';
221
            $this->trackedevents['PAYMENT_VARIOUS_DELETE'] = 'logPAYMENT_VARIOUS_DELETE';
222
        }
223
224
        // Cashdesk
225
        // $conf->global->BANK_ENABLE_POS_CASHCONTROL must be set to 1 by all external POS modules
226
        $moduleposenabled = (!empty($conf->cashdesk->enabled) || !empty($conf->takepos->enabled) || getDolGlobalString('BANK_ENABLE_POS_CASHCONTROL'));
227
        if ($moduleposenabled) {
228
            $this->trackedevents['CASHCONTROL_VALIDATE'] = 'logCASHCONTROL_VALIDATE';
229
        }
230
231
        // Add more action to track from a conf variable
232
        // For example: STOCK_MOVEMENT,...
233
        if (getDolGlobalString('BLOCKEDLOG_ADD_ACTIONS_SUPPORTED')) {
234
            $tmparrayofmoresupportedevents = explode(',', getDolGlobalString('BLOCKEDLOG_ADD_ACTIONS_SUPPORTED'));
235
            foreach ($tmparrayofmoresupportedevents as $val) {
236
                $this->trackedevents[$val] = 'log' . $val;
237
            }
238
        }
239
240
        return 1;
241
    }
242
243
    /**
244
     * Try to retrieve source object (it it still exists).
245
     *
246
     * @return string       URL string of source object
247
     */
248
    public function getObjectLink()
249
    {
250
        global $langs;
251
252
        if ($this->element === 'facture') {
253
254
            $object = new Facture($this->db);
255
            if ($object->fetch($this->fk_object) > 0) {
256
                return $object->getNomUrl(1);
257
            } else {
258
                $this->error++;
259
            }
260
        }
261
        if ($this->element === 'invoice_supplier') {
262
263
            $object = new FactureFournisseur($this->db);
264
            if ($object->fetch($this->fk_object) > 0) {
265
                return $object->getNomUrl(1);
266
            } else {
267
                $this->error++;
268
            }
269
        } elseif ($this->element === 'payment') {
270
271
            $object = new Paiement($this->db);
272
            if ($object->fetch($this->fk_object) > 0) {
273
                return $object->getNomUrl(1);
274
            } else {
275
                $this->error++;
276
            }
277
        } elseif ($this->element === 'payment_supplier') {
278
279
            $object = new PaiementFourn($this->db);
280
            if ($object->fetch($this->fk_object) > 0) {
281
                return $object->getNomUrl(1);
282
            } else {
283
                $this->error++;
284
            }
285
        } elseif ($this->element === 'payment_donation') {
286
287
            $object = new PaymentDonation($this->db);
288
            if ($object->fetch($this->fk_object) > 0) {
289
                return $object->getNomUrl(1);
290
            } else {
291
                $this->error++;
292
            }
293
        } elseif ($this->element === 'payment_various') {
294
295
            $object = new PaymentVarious($this->db);
296
            if ($object->fetch($this->fk_object) > 0) {
297
                return $object->getNomUrl(1);
298
            } else {
299
                $this->error++;
300
            }
301
        } elseif ($this->element === 'don' || $this->element === 'donation') {
302
303
            $object = new Don($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 === 'subscription') {
310
311
            $object = new Subscription($this->db);
312
            if ($object->fetch($this->fk_object) > 0) {
313
                return $object->getNomUrl(1);
314
            } else {
315
                $this->error++;
316
            }
317
        } elseif ($this->element === 'cashcontrol') {
318
319
            $object = new CashControl($this->db);
320
            if ($object->fetch($this->fk_object) > 0) {
321
                return $object->getNomUrl(1);
322
            } else {
323
                $this->error++;
324
            }
325
        } elseif ($this->element === 'stockmouvement') {
326
327
            $object = new MouvementStock($this->db);
328
            if ($object->fetch($this->fk_object) > 0) {
329
                return $object->getNomUrl(1);
330
            } else {
331
                $this->error++;
332
            }
333
        } elseif ($this->element === 'project') {
334
335
            $object = new Project($this->db);
336
            if ($object->fetch($this->fk_object) > 0) {
337
                return $object->getNomUrl(1);
338
            } else {
339
                $this->error++;
340
            }
341
        } elseif ($this->action == 'MODULE_SET') {
342
            return '<i class="opacitymedium">' . $langs->trans("BlockedLogEnabled") . '</i>';
343
        } elseif ($this->action == 'MODULE_RESET') {
344
            if ($this->signature == '0000000000') {
345
                return '<i class="opacitymedium">' . $langs->trans("BlockedLogDisabled") . '</i>';
346
            } else {
347
                return '<i class="opacitymedium">' . $langs->trans("BlockedLogDisabledBis") . '</i>';
348
            }
349
        }
350
351
        return '<i class="opacitymedium">' . $langs->trans('ImpossibleToReloadObject', $this->element, $this->fk_object) . '</i>';
352
    }
353
354
    /**
355
     *      try to retrieve user author
356
     * @return string
357
     */
358
    public function getUser()
359
    {
360
        global $langs, $cachedUser;
361
362
        if (empty($cachedUser)) {
363
            $cachedUser = array();
364
        }
365
366
        if (empty($cachedUser[$this->fk_user])) {
367
            $u = new User($this->db);
368
            if ($u->fetch($this->fk_user) > 0) {
369
                $cachedUser[$this->fk_user] = $u;
370
            }
371
        }
372
373
        if (!empty($cachedUser[$this->fk_user])) {
374
            return $cachedUser[$this->fk_user]->getNomUrl(1);
375
        }
376
377
        return $langs->trans('ImpossibleToRetrieveUser', $this->fk_user);
378
    }
379
380
    /**
381
     *  Populate properties of log from object data
382
     *
383
     *  @param  CommonObject    $object     object to store
384
     *  @param  string          $action     action
385
     *  @param  string          $amounts    amounts
386
     *  @param  ?User           $fuser      User object (forced)
387
     *  @return int                         >0 if OK, <0 if KO
388
     */
389
    public function setObjectData(&$object, $action, $amounts, $fuser = null)
390
    {
391
        global $langs, $user, $mysoc;
392
393
        if (is_object($fuser)) {
394
            $user = $fuser;
395
        }
396
397
        // Generic fields
398
399
        // action
400
        $this->action = $action;
401
        // amount
402
        $this->amounts = $amounts;
403
        // date
404
        if ($object->element == 'payment' || $object->element == 'payment_supplier') {
405
            $this->date_object = empty($object->datepaye) ? $object->date : $object->datepaye;
0 ignored issues
show
Bug Best Practice introduced by
The property datepaye does not exist on Dolibarr\Core\Base\CommonObject. Since you implemented __get, consider adding a @property annotation.
Loading history...
Bug Best Practice introduced by
The property date does not exist on Dolibarr\Core\Base\CommonObject. Since you implemented __get, consider adding a @property annotation.
Loading history...
406
        } elseif ($object->element == 'payment_salary') {
407
            $this->date_object = $object->datev;
0 ignored issues
show
Bug Best Practice introduced by
The property datev does not exist on Dolibarr\Core\Base\CommonObject. Since you implemented __get, consider adding a @property annotation.
Loading history...
408
        } elseif ($object->element == 'payment_donation' || $object->element == 'payment_various') {
409
            $this->date_object = empty($object->datepaid) ? $object->datep : $object->datepaid;
0 ignored issues
show
Bug Best Practice introduced by
The property datep does not exist on Dolibarr\Core\Base\CommonObject. Since you implemented __get, consider adding a @property annotation.
Loading history...
Bug Best Practice introduced by
The property datepaid does not exist on Dolibarr\Core\Base\CommonObject. Since you implemented __get, consider adding a @property annotation.
Loading history...
410
        } elseif ($object->element == 'subscription') {
411
            $this->date_object = $object->dateh;
0 ignored issues
show
Bug Best Practice introduced by
The property dateh does not exist on Dolibarr\Core\Base\CommonObject. Since you implemented __get, consider adding a @property annotation.
Loading history...
412
        } elseif ($object->element == 'cashcontrol') {
413
            $this->date_object = $object->date_creation;
414
        } elseif (property_exists($object, 'date')) {
415
            // Generic case
416
            $this->date_object = $object->date;
417
        } elseif (property_exists($object, 'datem')) {
418
            // Generic case (second chance, for example for stock movement)
419
            $this->date_object = $object->datem;
0 ignored issues
show
Bug Best Practice introduced by
The property datem does not exist on Dolibarr\Core\Base\CommonObject. Since you implemented __get, consider adding a @property annotation.
Loading history...
420
        }
421
422
        // ref
423
        $this->ref_object = ((!empty($object->newref)) ? $object->newref : $object->ref); // newref is set when validating a draft, ref is set in other cases
424
        // type of object
425
        $this->element = $object->element;
426
        // id of object
427
        $this->fk_object = $object->id;
428
429
430
        // Set object_data
431
        $this->object_data = new stdClass();
432
        // Add fields to exclude
433
        $arrayoffieldstoexclude = array(
434
            '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',
435
            'table_element_line', 'ismultientitymanaged', 'isextrafieldmanaged',
436
            'array_languages',
437
            'childtables',
438
            'contact_ids',
439
            'context',
440
            'labelStatus',
441
            'labelStatusShort',
442
            'linkedObjectsIds',
443
            'linkedObjects',
444
            'fk_delivery_address',
445
            'projet',          // There is already ->fk_project
446
            'restrictiononfksoc',
447
            'specimen',
448
        );
449
        // Add more fields to exclude depending on object type
450
        if ($this->element == 'cashcontrol') {
451
            $arrayoffieldstoexclude = array_merge($arrayoffieldstoexclude, array(
452
                'name', 'lastname', 'firstname', 'region', 'region_id', 'region_code', 'state', 'state_id', 'state_code', 'country', 'country_id', 'country_code',
453
                'total_ht', 'total_tva', 'total_ttc', 'total_localtax1', 'total_localtax2',
454
                'barcode_type', 'barcode_type_code', 'barcode_type_label', 'barcode_type_coder', 'mode_reglement_id', 'cond_reglement_id', 'mode_reglement', 'cond_reglement', 'shipping_method_id',
455
                'fk_incoterms', 'label_incoterms', 'location_incoterms', 'lines'));
456
        }
457
458
        // Add thirdparty info
459
        if (empty($object->thirdparty) && method_exists($object, 'fetch_thirdparty')) {
460
            $object->fetch_thirdparty();
461
        }
462
        if (!empty($object->thirdparty)) {
463
            $this->object_data->thirdparty = new stdClass();
464
465
            foreach ($object->thirdparty as $key => $value) {
466
                if (in_array($key, $arrayoffieldstoexclude)) {
467
                    continue; // Discard some properties
468
                }
469
                if (
470
                    !in_array($key, array(
471
                    'name', 'name_alias', 'ref_ext', 'address', 'zip', 'town', 'state_code', 'country_code', 'idprof1', 'idprof2', 'idprof3', 'idprof4', 'idprof5', 'idprof6', 'phone', 'fax', 'email', 'barcode',
472
                    'tva_intra', 'localtax1_assuj', 'localtax1_value', 'localtax2_assuj', 'localtax2_value', 'managers', 'capital', 'typent_code', 'forme_juridique_code', 'code_client', 'code_fournisseur'
473
                    ))
474
                ) {
475
                    continue; // Discard if not into a dedicated list
476
                }
477
                if (!is_object($value) && !is_null($value) && $value !== '') {
478
                    $this->object_data->thirdparty->$key = $value;
479
                }
480
            }
481
        }
482
483
        // Add company info
484
        if (!empty($mysoc)) {
485
            $this->object_data->mycompany = new stdClass();
486
487
            foreach ($mysoc as $key => $value) {
488
                if (in_array($key, $arrayoffieldstoexclude)) {
489
                    continue; // Discard some properties
490
                }
491
                if (
492
                    !in_array($key, array(
493
                    'name', 'name_alias', 'ref_ext', 'address', 'zip', 'town', 'state_code', 'country_code', 'idprof1', 'idprof2', 'idprof3', 'idprof4', 'idprof5', 'idprof6', 'phone', 'fax', 'email', 'barcode',
494
                    'tva_intra', 'localtax1_assuj', 'localtax1_value', 'localtax2_assuj', 'localtax2_value', 'managers', 'capital', 'typent_code', 'forme_juridique_code', 'code_client', 'code_fournisseur'
495
                    ))
496
                ) {
497
                    continue; // Discard if not into a dedicated list
498
                }
499
                if (!is_object($value) && !is_null($value) && $value !== '') {
500
                    $this->object_data->mycompany->$key = $value;
501
                }
502
            }
503
        }
504
505
        // Add user info
506
        if (!empty($user)) {
507
            $this->fk_user = $user->id;
508
            $this->user_fullname = $user->getFullName($langs);
509
        }
510
511
        // Field specific to object
512
        if ($this->element == 'facture') {
513
            foreach ($object as $key => $value) {
514
                if (in_array($key, $arrayoffieldstoexclude)) {
515
                    continue; // Discard some properties
516
                }
517
                if (
518
                    !in_array($key, array(
519
                    'ref', 'ref_client', 'ref_supplier', 'date', 'datef', 'datev', 'type', 'total_ht', 'total_tva', 'total_ttc', 'localtax1', 'localtax2', 'revenuestamp', 'datepointoftax', 'note_public', 'lines'
520
                    ))
521
                ) {
522
                    continue; // Discard if not into a dedicated list
523
                }
524
                if ($key == 'lines') {
525
                    $lineid = 0;
526
                    foreach ($value as $tmpline) {  // $tmpline is object FactureLine
527
                        $lineid++;
528
                        foreach ($tmpline as $keyline => $valueline) {
529
                            if (
530
                                !in_array($keyline, array(
531
                                'ref', 'multicurrency_code', 'multicurrency_total_ht', 'multicurrency_total_tva', 'multicurrency_total_ttc', 'qty', 'product_type', 'product_label', 'vat_src_code', 'tva_tx', 'info_bits', 'localtax1_tx', 'localtax2_tx', 'total_ht', 'total_tva', 'total_ttc', 'total_localtax1', 'total_localtax2'
532
                                ))
533
                            ) {
534
                                continue; // Discard if not into a dedicated list
535
                            }
536
537
                            if (empty($this->object_data->invoiceline[$lineid]) || !is_object($this->object_data->invoiceline[$lineid])) {      // To avoid warning
538
                                $this->object_data->invoiceline[$lineid] = new stdClass();
539
                            }
540
541
                            if (!is_object($valueline) && !is_null($valueline) && $valueline !== '') {
542
                                $this->object_data->invoiceline[$lineid]->$keyline = $valueline;
543
                            }
544
                        }
545
                    }
546
                } elseif (!is_object($value) && !is_null($value) && $value !== '') {
547
                    $this->object_data->$key = $value;
548
                }
549
            }
550
551
            if (!empty($object->newref)) {
552
                $this->object_data->ref = $object->newref;
553
            }
554
        } elseif ($this->element == 'invoice_supplier') {
555
            foreach ($object as $key => $value) {
556
                if (in_array($key, $arrayoffieldstoexclude)) {
557
                    continue; // Discard some properties
558
                }
559
                if (
560
                    !in_array($key, array(
561
                    'ref', 'ref_client', 'ref_supplier', 'date', 'datef', 'type', 'total_ht', 'total_tva', 'total_ttc', 'localtax1', 'localtax2', 'revenuestamp', 'datepointoftax', 'note_public'
562
                    ))
563
                ) {
564
                    continue; // Discard if not into a dedicated list
565
                }
566
                if (!is_object($value) && !is_null($value) && $value !== '') {
567
                    $this->object_data->$key = $value;
568
                }
569
            }
570
571
            if (!empty($object->newref)) {
572
                $this->object_data->ref = $object->newref;
573
            }
574
        } elseif ($this->element == 'payment' || $this->element == 'payment_supplier' || $this->element == 'payment_donation' || $this->element == 'payment_various') {
575
            $datepayment = $object->datepaye ? $object->datepaye : ($object->datepaid ? $object->datepaid : $object->datep);
576
            $paymenttypeid = $object->paiementid ? $object->paiementid : ($object->paymenttype ? $object->paymenttype : $object->type_payment);
0 ignored issues
show
Bug Best Practice introduced by
The property type_payment does not exist on Dolibarr\Core\Base\CommonObject. Since you implemented __get, consider adding a @property annotation.
Loading history...
Bug Best Practice introduced by
The property paiementid does not exist on Dolibarr\Core\Base\CommonObject. Since you implemented __get, consider adding a @property annotation.
Loading history...
Bug Best Practice introduced by
The property paymenttype does not exist on Dolibarr\Core\Base\CommonObject. Since you implemented __get, consider adding a @property annotation.
Loading history...
577
578
            $this->object_data->ref = $object->ref;
579
            $this->object_data->date = $datepayment;
580
            $this->object_data->type_code = dol_getIdFromCode($this->db, $paymenttypeid, 'c_paiement', 'id', 'code');
581
582
            if (!empty($object->num_payment)) {
0 ignored issues
show
Bug Best Practice introduced by
The property num_payment does not exist on Dolibarr\Core\Base\CommonObject. Since you implemented __get, consider adding a @property annotation.
Loading history...
583
                $this->object_data->payment_num = $object->num_payment;
584
            }
585
            if (!empty($object->note_private)) {
586
                $this->object_data->note_private = $object->note_private;
587
            }
588
            //$this->object_data->fk_account = $object->fk_account;
589
            //var_dump($this->object_data);exit;
590
591
            $totalamount = 0;
592
593
            // Loop on each invoice payment amount (payment_part)
594
            if (is_array($object->amounts) && !empty($object->amounts)) {
0 ignored issues
show
Bug Best Practice introduced by
The property amounts does not exist on Dolibarr\Core\Base\CommonObject. Since you implemented __get, consider adding a @property annotation.
Loading history...
595
                $paymentpartnumber = 0;
596
                foreach ($object->amounts as $objid => $amount) {
597
                    if (empty($amount)) {
598
                        continue;
599
                    }
600
601
                    $totalamount += $amount;
602
603
                    $tmpobject = null;
604
                    if ($this->element == 'payment_supplier') {
605
                        $tmpobject = new FactureFournisseur($this->db);
606
                    } elseif ($this->element == 'payment') {
607
                        $tmpobject = new Facture($this->db);
608
                    } elseif ($this->element == 'payment_donation') {
609
                        include_once DOL_DOCUMENT_ROOT . '/don/class/don.class.php';
610
                        $tmpobject = new Don($this->db);
611
                    } elseif ($this->element == 'payment_various') {
612
                        include_once DOL_DOCUMENT_ROOT . '/compta/bank/class/paymentvarious.class.php';
613
                        $tmpobject = new PaymentVarious($this->db);
614
                    }
615
616
                    if (!is_object($tmpobject)) {
617
                        continue;
618
                    }
619
620
                    $result = $tmpobject->fetch($objid);
621
622
                    if ($result <= 0) {
623
                        $this->error = $tmpobject->error;
624
                        $this->errors = $tmpobject->errors;
625
                        dol_syslog("Failed to fetch object with id " . $objid, LOG_ERR);
626
                        return -1;
627
                    }
628
629
                    $paymentpart = new stdClass();
630
                    $paymentpart->amount = $amount;
631
632
                    if (!in_array($this->element, array('payment_donation', 'payment_various'))) {
633
                        $result = $tmpobject->fetch_thirdparty();
634
                        if ($result == 0) {
635
                            $this->error = 'Failed to fetch thirdparty for object with id ' . $tmpobject->id;
636
                            $this->errors[] = $this->error;
637
                            dol_syslog("Failed to fetch thirdparty for object with id " . $tmpobject->id, LOG_ERR);
638
                            return -1;
639
                        } elseif ($result < 0) {
640
                            $this->error = $tmpobject->error;
641
                            $this->errors = $tmpobject->errors;
642
                            return -1;
643
                        }
644
645
                        $paymentpart->thirdparty = new stdClass();
646
                        foreach ($tmpobject->thirdparty as $key => $value) {
647
                            if (in_array($key, $arrayoffieldstoexclude)) {
648
                                continue; // Discard some properties
649
                            }
650
                            if (
651
                                !in_array($key, array(
652
                                'name', 'name_alias', 'ref_ext', 'address', 'zip', 'town', 'state_code', 'country_code', 'idprof1', 'idprof2', 'idprof3', 'idprof4', 'idprof5', 'idprof6', 'phone', 'fax', 'email', 'barcode',
653
                                'tva_intra', 'localtax1_assuj', 'localtax1_value', 'localtax2_assuj', 'localtax2_value', 'managers', 'capital', 'typent_code', 'forme_juridique_code', 'code_client', 'code_fournisseur'
654
                                ))
655
                            ) {
656
                                continue; // Discard if not into a dedicated list
657
                            }
658
                            if (!is_object($value) && !is_null($value) && $value !== '') {
659
                                $paymentpart->thirdparty->$key = $value;
660
                            }
661
                        }
662
                    }
663
664
                    // Init object to avoid warnings
665
                    if ($this->element == 'payment_donation') {
666
                        $paymentpart->donation = new stdClass();
667
                    } else {
668
                        $paymentpart->invoice = new stdClass();
669
                    }
670
671
                    if ($this->element != 'payment_various') {
672
                        foreach ($tmpobject as $key => $value) {
673
                            if (in_array($key, $arrayoffieldstoexclude)) {
674
                                continue; // Discard some properties
675
                            }
676
                            if (
677
                                !in_array($key, array(
678
                                'ref', 'ref_client', 'ref_supplier', 'date', 'datef', 'type', 'total_ht', 'total_tva', 'total_ttc', 'localtax1', 'localtax2', 'revenuestamp', 'datepointoftax', 'note_public'
679
                                ))
680
                            ) {
681
                                continue; // Discard if not into a dedicated list
682
                            }
683
                            if (!is_object($value) && !is_null($value) && $value !== '') {
684
                                if ($this->element == 'payment_donation') {
685
                                    $paymentpart->donation->$key = $value;
686
                                } elseif ($this->element == 'payment_various') {
687
                                    $paymentpart->various->$key = $value;
688
                                } else {
689
                                    $paymentpart->invoice->$key = $value;
690
                                }
691
                            }
692
                        }
693
694
                        $paymentpartnumber++; // first payment will be 1
695
                        $this->object_data->payment_part[$paymentpartnumber] = $paymentpart;
696
                    }
697
                }
698
            } elseif (!empty($object->amount)) {
0 ignored issues
show
Bug Best Practice introduced by
The property amount does not exist on Dolibarr\Core\Base\CommonObject. Since you implemented __get, consider adding a @property annotation.
Loading history...
699
                $totalamount = $object->amount;
700
            }
701
702
            $this->object_data->amount = $totalamount;
703
704
            if (!empty($object->newref)) {
705
                $this->object_data->ref = $object->newref;
706
            }
707
        } elseif ($this->element == 'payment_salary') {
708
            $this->object_data->amounts = array($object->amount);
709
710
            if (!empty($object->newref)) {
711
                $this->object_data->ref = $object->newref;
712
            }
713
        } elseif ($this->element == 'subscription') {
714
            foreach ($object as $key => $value) {
715
                if (in_array($key, $arrayoffieldstoexclude)) {
716
                    continue; // Discard some properties
717
                }
718
                if (
719
                    !in_array($key, array(
720
                    'id', 'datec', 'dateh', 'datef', 'fk_adherent', 'amount', 'import_key', 'statut', 'note'
721
                    ))
722
                ) {
723
                    continue; // Discard if not into a dedicated list
724
                }
725
                if (!is_object($value) && !is_null($value) && $value !== '') {
726
                    $this->object_data->$key = $value;
727
                }
728
            }
729
730
            if (!empty($object->newref)) {
731
                $this->object_data->ref = $object->newref;
732
            }
733
        } elseif ($this->element == 'stockmouvement') {
734
            foreach ($object as $key => $value) {
735
                if (in_array($key, $arrayoffieldstoexclude)) {
736
                    continue; // Discard some properties
737
                }
738
                if (!is_object($value) && !is_null($value) && $value !== '') {
739
                    $this->object_data->$key = $value;
740
                }
741
            }
742
        } else {
743
            // Generic case
744
            foreach ($object as $key => $value) {
745
                if (in_array($key, $arrayoffieldstoexclude)) {
746
                    continue; // Discard some properties
747
                }
748
                if (!is_object($value) && !is_null($value) && $value !== '') {
749
                    $this->object_data->$key = $value;
750
                }
751
            }
752
753
            if (!empty($object->newref)) {
754
                $this->object_data->ref = $object->newref;
755
            }
756
        }
757
758
        // A trick to be sure all the object_data is an associative array
759
        // json_encode and json_decode are not able to manage mixed object (with array/object, only full arrays or full objects)
760
        $this->object_data = json_decode(json_encode($this->object_data, JSON_FORCE_OBJECT), false);
761
762
        return 1;
763
    }
764
765
    /**
766
     *  Get object from database
767
     *
768
     *  @param      int     $id         Id of object to load
769
     *  @return     int                     >0 if OK, <0 if KO, 0 if not found
770
     */
771
    public function fetch($id)
772
    {
773
        global $langs;
774
775
        if (empty($id)) {
776
            $this->error = 'BadParameter';
777
            return -1;
778
        }
779
780
        $sql = "SELECT b.rowid, b.date_creation, b.signature, b.signature_line, b.amounts, b.action, b.element, b.fk_object, b.entity,";
781
        $sql .= " b.certified, b.tms, b.fk_user, b.user_fullname, b.date_object, b.ref_object, b.object_data, b.object_version";
782
        $sql .= " FROM " . MAIN_DB_PREFIX . "blockedlog as b";
783
        if ($id) {
784
            $sql .= " WHERE b.rowid = " . ((int) $id);
785
        }
786
787
        $resql = $this->db->query($sql);
788
        if ($resql) {
789
            $obj = $this->db->fetch_object($resql);
790
            if ($obj) {
791
                $this->id               = $obj->rowid;
792
                $this->entity           = $obj->entity;
793
794
                $this->date_creation    = $this->db->jdate($obj->date_creation);
795
                $this->date_modification = $this->db->jdate($obj->tms);
796
797
                $this->amounts          = (float) $obj->amounts;
798
                $this->action           = $obj->action;
799
                $this->element          = $obj->element;
800
801
                $this->fk_object = $obj->fk_object;
802
                $this->date_object = $this->db->jdate($obj->date_object);
803
                $this->ref_object = $obj->ref_object;
804
805
                $this->fk_user = $obj->fk_user;
806
                $this->user_fullname = $obj->user_fullname;
807
808
                $this->object_data = $this->dolDecodeBlockedData($obj->object_data);
809
                $this->object_version = $obj->object_version;
810
811
                $this->signature        = $obj->signature;
812
                $this->signature_line   = $obj->signature_line;
813
                $this->certified        = ($obj->certified == 1);
814
815
                return 1;
816
            } else {
817
                $langs->load("blockedlog");
818
                $this->error = $langs->trans("RecordNotFound");
819
                return 0;
820
            }
821
        } else {
822
            $this->error = $this->db->error();
823
            return -1;
824
        }
825
    }
826
827
828
    /**
829
     * Encode data
830
     *
831
     * @param   string  $data   Data to serialize
832
     * @param   int     $mode   0=serialize, 1=json_encode
833
     * @return  string          Value serialized, an object (stdClass)
834
     */
835
    public function dolEncodeBlockedData($data, $mode = 0)
836
    {
837
        try {
838
            $aaa = json_encode($data);
839
        } catch (Exception $e) {
0 ignored issues
show
Bug introduced by
The type Dolibarr\Code\BloquedLog\Classes\Exception was not found. Did you mean Exception? If so, make sure to prefix the type with \.
Loading history...
840
            //print $e->getErrs);
841
        }
842
        //var_dump($aaa);
843
844
        return $aaa;
845
    }
846
847
848
    /**
849
     * Decode data
850
     *
851
     * @param   string  $data   Data to unserialize
852
     * @param   int     $mode   0=unserialize, 1=json_decode
853
     * @return  object          Value unserialized, an object (stdClass)
854
     */
855
    public function dolDecodeBlockedData($data, $mode = 0)
856
    {
857
        try {
858
            $aaa = (object) jsonOrUnserialize($data);
859
        } catch (Exception $e) {
860
            //print $e->getErrs);
861
        }
862
        //var_dump($aaa);
863
864
        return $aaa;
865
    }
866
867
868
    /**
869
     *  Set block certified by authority
870
     *
871
     *  @return boolean
872
     */
873
    public function setCertified()
874
    {
875
        $res = $this->db->query("UPDATE " . MAIN_DB_PREFIX . "blockedlog SET certified=1 WHERE rowid=" . ((int) $this->id));
876
        if (!$res) {
877
            return false;
878
        }
879
880
        return true;
881
    }
882
883
    /**
884
     *  Create blocked log in database.
885
     *
886
     *  @param  User    $user               Object user that create
887
     *  @param  string      $forcesignature     Force signature (for example '0000000000' when we disabled the module)
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);
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 DOL_DOCUMENT_ROOT . '/core/lib/security.lib.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 it in database.
1014
     *  @param  int             $returnarray        1=Return array of details, 2=Return array of details including keyforsignature, 0=Boolean
1015
     *  @return boolean|array                       True if OK, False if KO
1016
     */
1017
    public function checkSignature($previoushash = '', $returnarray = 0)
1018
    {
1019
        if (empty($previoushash)) {
1020
            $previoushash = $this->getPreviousHash(0, $this->id);
1021
        }
1022
        // Recalculate hash
1023
        $keyforsignature = $this->buildKeyForSignature();
1024
1025
        //$signature_line = dol_hash($keyforsignature, '5'); // Not really useful
1026
        $signature = dol_hash($previoushash . $keyforsignature, 'sha256');
1027
        //var_dump($previoushash); var_dump($keyforsignature); var_dump($signature_line); var_dump($signature);
1028
1029
        $res = ($signature === $this->signature);
1030
1031
        if (!$res) {
1032
            $this->error = 'Signature KO';
1033
        }
1034
1035
        if ($returnarray) {
1036
            if ($returnarray == 1) {
1037
                unset($keyforsignature);
1038
                return array('checkresult' => $res, 'calculatedsignature' => $signature, 'previoushash' => $previoushash);
1039
            } else {    // Consume much memory ($keyforsignature is a large var)
1040
                return array('checkresult' => $res, 'calculatedsignature' => $signature, 'previoushash' => $previoushash, 'keyforsignature' => $keyforsignature);
1041
            }
1042
        } else {
1043
            unset($keyforsignature);
1044
            return $res;
1045
        }
1046
    }
1047
1048
    /**
1049
     * Return a string for signature.
1050
     * Note: rowid of line not included as it is not a business data and this allow to make backup of a year
1051
     * and restore it into another database with different id without comprimising checksums
1052
     *
1053
     * @return string       Key for signature
1054
     */
1055
    private function buildKeyForSignature()
1056
    {
1057
        //print_r($this->object_data);
1058
        if (((int) $this->object_version) >= 18) {
1059
            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);
1060
        } else {
1061
            return $this->date_creation . '|' . $this->action . '|' . $this->amounts . '|' . $this->ref_object . '|' . $this->date_object . '|' . $this->user_fullname . '|' . print_r($this->object_data, true);
1062
        }
1063
    }
1064
1065
1066
    /**
1067
     *  Get previous signature/hash in chain
1068
     *
1069
     *  @param int  $withlock       1=With a lock
1070
     *  @param int  $beforeid       ID of a record
1071
     *  @return string              Hash of previous record (if beforeid is defined) or hash of last record (if beforeid is 0)
1072
     */
1073
    public function getPreviousHash($withlock = 0, $beforeid = 0)
1074
    {
1075
        global $conf;
1076
1077
        $previoussignature = '';
1078
1079
        $sql = "SELECT rowid, signature FROM " . MAIN_DB_PREFIX . "blockedlog";
1080
        $sql .= " WHERE entity = " . ((int) $conf->entity);
1081
        if ($beforeid) {
1082
            $sql .= " AND rowid < " . (int) $beforeid;
1083
        }
1084
        $sql .= " ORDER BY rowid DESC LIMIT 1";
1085
        $sql .= ($withlock ? " FOR UPDATE " : "");
1086
1087
        $resql = $this->db->query($sql);
1088
        if ($resql) {
1089
            $obj = $this->db->fetch_object($resql);
1090
            if ($obj) {
1091
                $previoussignature = $obj->signature;
1092
            }
1093
        } else {
1094
            dol_print_error($this->db);
1095
            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...
1096
        }
1097
1098
        if (empty($previoussignature)) {
1099
            // First signature line (line 0)
1100
            $previoussignature = $this->getSignature();
1101
        }
1102
1103
        return $previoussignature;
1104
    }
1105
1106
    /**
1107
     *  Return array of log objects (with criteria)
1108
     *
1109
     *  @param  string  $element        element to search
1110
     *  @param  int     $fk_object      id of object to search
1111
     *  @param  int     $limit          max number of element, 0 for all
1112
     *  @param  string  $sortfield      sort field
1113
     *  @param  string  $sortorder      sort order
1114
     *  @param  int     $search_fk_user id of user(s)
1115
     *  @param  int     $search_start   start time limit
1116
     *  @param  int     $search_end     end time limit
1117
     *  @param  string  $search_ref     search ref
1118
     *  @param  string  $search_amount  search amount
1119
     *  @param  string  $search_code    search code
1120
     *  @return BlockedLog[]|int<-2,-1> Array of object log or <0 if error
1121
     */
1122
    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 = '')
1123
    {
1124
        global $conf;
1125
        //global $cachedlogs;
1126
1127
        /* $cachedlogs allow fastest search */
1128
        //if (empty($cachedlogs)) $cachedlogs = array();
1129
1130
        if ($element == 'all') {
1131
            $sql = "SELECT rowid FROM " . MAIN_DB_PREFIX . "blockedlog
1132
			 WHERE entity=" . $conf->entity;
1133
        } elseif ($element == 'not_certified') {
1134
            $sql = "SELECT rowid FROM " . MAIN_DB_PREFIX . "blockedlog
1135
			 WHERE entity=" . $conf->entity . " AND certified = 0";
1136
        } elseif ($element == 'just_certified') {
1137
            $sql = "SELECT rowid FROM " . MAIN_DB_PREFIX . "blockedlog
1138
			 WHERE entity=" . $conf->entity . " AND certified = 1";
1139
        } else {
1140
            $sql = "SELECT rowid FROM " . MAIN_DB_PREFIX . "blockedlog
1141
			 WHERE entity=" . $conf->entity . " AND element = '" . $this->db->escape($element) . "'";
1142
        }
1143
1144
        if ($fk_object) {
1145
            $sql .= natural_search("rowid", $fk_object, 1);
1146
        }
1147
        if ($search_fk_user > 0) {
1148
            $sql .= natural_search("fk_user", $search_fk_user, 2);
1149
        }
1150
        if ($search_start > 0) {
1151
            $sql .= " AND date_creation >= '" . $this->db->idate($search_start) . "'";
1152
        }
1153
        if ($search_end > 0) {
1154
            $sql .= " AND date_creation <= '" . $this->db->idate($search_end) . "'";
1155
        }
1156
        if ($search_ref != '') {
1157
            $sql .= natural_search("ref_object", $search_ref);
1158
        }
1159
        if ($search_amount != '') {
1160
            $sql .= natural_search("amounts", $search_amount, 1);
1161
        }
1162
        if ($search_code != '' && $search_code != '-1') {
1163
            $sql .= natural_search("action", $search_code, 3);
1164
        }
1165
1166
        $sql .= $this->db->order($sortfield, $sortorder);
1167
        $sql .= $this->db->plimit($limit + 1); // We want more, because we will stop into loop later with error if we reach max
1168
1169
        $res = $this->db->query($sql);
1170
        if ($res) {
1171
            $results = array();
1172
1173
            $i = 0;
1174
            while ($obj = $this->db->fetch_object($res)) {
1175
                $i++;
1176
                if ($i > $limit) {
1177
                    // Too many record, we will consume too much memory
1178
                    return -2;
1179
                }
1180
1181
                //if (!isset($cachedlogs[$obj->rowid]))
1182
                //{
1183
                $b = new BlockedLog($this->db);
1184
                $b->fetch($obj->rowid);
1185
                //$b->loadTrackedEvents();
1186
                //$cachedlogs[$obj->rowid] = $b;
1187
                //}
1188
1189
                //$results[] = $cachedlogs[$obj->rowid];
1190
                $results[] = $b;
1191
            }
1192
1193
            return $results;
1194
        }
1195
1196
        return -1;
1197
    }
1198
1199
    /**
1200
     *  Return the signature (hash) of the "genesis-block" (Block 0).
1201
     *
1202
     *  @return string                  Signature of genesis-block for current conf->entity
1203
     */
1204
    public function getSignature()
1205
    {
1206
        global $db, $conf, $mysoc;
1207
1208
        if (!getDolGlobalString('BLOCKEDLOG_ENTITY_FINGERPRINT')) { // creation of a unique fingerprint
1209
            require_once constant('DOL_DOCUMENT_ROOT') . '/core/lib/admin.lib.php';
1210
            require_once constant('DOL_DOCUMENT_ROOT') . '/core/lib/security.lib.php';
1211
            require_once constant('DOL_DOCUMENT_ROOT') . '/core/lib/security2.lib.php';
1212
1213
            $fingerprint = dol_hash(print_r($mysoc, true) . getRandomPassword(1), '5');
1214
1215
            dolibarr_set_const($db, 'BLOCKEDLOG_ENTITY_FINGERPRINT', $fingerprint, 'chaine', 0, 'Numeric Unique Fingerprint', $conf->entity);
1216
1217
            $conf->global->BLOCKEDLOG_ENTITY_FINGERPRINT = $fingerprint;
1218
        }
1219
1220
        return $conf->global->BLOCKEDLOG_ENTITY_FINGERPRINT;
1221
    }
1222
1223
1224
    /**
1225
     * Check if module was already used or not for at least one recording.
1226
     *
1227
     * @param   int     $ignoresystem       Ignore system events for the test
1228
     * @return  bool
1229
     */
1230
    public function alreadyUsed($ignoresystem = 0)
1231
    {
1232
        global $conf;
1233
1234
        $result = false;
1235
1236
        $sql = "SELECT rowid FROM " . MAIN_DB_PREFIX . "blockedlog";
1237
        $sql .= " WHERE entity = " . $conf->entity;
1238
        if ($ignoresystem) {
1239
            $sql .= " AND action not in ('MODULE_SET','MODULE_RESET')";
1240
        }
1241
        $sql .= $this->db->plimit(1);
1242
1243
        $res = $this->db->query($sql);
1244
        if ($res !== false) {
1245
            $obj = $this->db->fetch_object($res);
1246
            if ($obj) {
1247
                $result = true;
1248
            }
1249
        } else {
1250
            dol_print_error($this->db);
1251
        }
1252
1253
        dol_syslog("Module Blockedlog alreadyUsed with ignoresystem=" . $ignoresystem . " is " . json_encode($result));
1254
1255
        return $result;
1256
    }
1257
}
1258