Passed
Push — main ( 4b1ce6...7d2b49 )
by Rafael
80:06
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 DoliDB;
28
use stdClass;
29
30
/**
31
 *  Class to manage Blocked Log
32
 */
33
class BlockedLog
34
{
35
    /**
36
     * @var DoliDB  Database handler
37
     */
38
    public $db;
39
40
    /**
41
     * Id of the log
42
     * @var int
43
     */
44
    public $id;
45
46
    /**
47
     * Entity
48
     * @var int
49
     */
50
    public $entity;
51
52
    /**
53
     * @var string Error message
54
     */
55
    public $error = '';
56
57
    /**
58
     * @var string[] Error codes (or messages)
59
     */
60
    public $errors = array();
61
62
    /**
63
     * Unique fingerprint of the log
64
     * @var string
65
     */
66
    public $signature = '';
67
68
    /**
69
     * Unique fingerprint of the line log content
70
     * @var string
71
     */
72
    public $signature_line = '';
73
74
    public $amounts = null;
75
76
    /**
77
     * trigger action
78
     * @var string
79
     */
80
    public $action = '';
81
82
    /**
83
     * Object element
84
     * @var string
85
     */
86
    public $element = '';
87
88
    /**
89
     * Object id
90
     * @var int
91
     */
92
    public $fk_object = 0;
93
94
    /**
95
     * Log certified by remote authority or not
96
     * @var boolean
97
     */
98
    public $certified = false;
99
100
    /**
101
     * Author
102
     * @var int
103
     */
104
    public $fk_user = 0;
105
106
    /**
107
     * @var integer|string date_creation
108
     */
109
    public $date_creation;
110
111
    /**
112
     * @var integer|string $date_modification;
113
     */
114
    public $date_modification;
115
116
    public $date_object = 0;
117
118
    public $ref_object = '';
119
120
    public $object_data = null;
121
    public $object_version = '';
122
123
    public $user_fullname = '';
124
125
    /**
126
     * Array of tracked event codes
127
     * @var string[]
128
     */
129
    public $trackedevents = array();
130
131
132
133
    /**
134
     *      Constructor
135
     *
136
     *      @param      DoliDB      $db      Database handler
137
     */
138
    public function __construct(DoliDB $db)
139
    {
140
        $this->db = $db;
141
    }
142
143
144
    /**
145
     * Load list of tracked events into $this->trackedevents.
146
     *
147
     * @return int          Always 1
148
     */
149
    public function loadTrackedEvents()
150
    {
151
        global $conf;
152
153
        $this->trackedevents = array();
154
155
        // Customer Invoice/Facture / Payment
156
        if (isModEnabled('invoice')) {
157
            $this->trackedevents['BILL_VALIDATE'] = 'logBILL_VALIDATE';
158
            $this->trackedevents['BILL_DELETE'] = 'logBILL_DELETE';
159
            $this->trackedevents['BILL_SENTBYMAIL'] = 'logBILL_SENTBYMAIL';
160
            $this->trackedevents['DOC_DOWNLOAD'] = 'BlockedLogBillDownload';
161
            $this->trackedevents['DOC_PREVIEW'] = 'BlockedLogBillPreview';
162
            $this->trackedevents['PAYMENT_CUSTOMER_CREATE'] = 'logPAYMENT_CUSTOMER_CREATE';
163
            $this->trackedevents['PAYMENT_CUSTOMER_DELETE'] = 'logPAYMENT_CUSTOMER_DELETE';
164
        }
165
166
        /* Supplier
167
        // Supplier Invoice / Payment
168
        if (isModEnabled("fournisseur")) {
169
            $this->trackedevents['BILL_SUPPLIER_VALIDATE']='BlockedLogSupplierBillValidate';
170
            $this->trackedevents['BILL_SUPPLIER_DELETE']='BlockedLogSupplierBillDelete';
171
            $this->trackedevents['BILL_SUPPLIER_SENTBYMAIL']='BlockedLogSupplierBillSentByEmail'; // Trigger key does not exists, we want just into array to list it as done
172
            $this->trackedevents['SUPPLIER_DOC_DOWNLOAD']='BlockedLogSupplierBillDownload';     // Trigger key does not exists, we want just into array to list it as done
173
            $this->trackedevents['SUPPLIER_DOC_PREVIEW']='BlockedLogSupplierBillPreview';       // Trigger key does not exists, we want just into array to list it as done
174
            $this->trackedevents['PAYMENT_SUPPLIER_CREATE']='BlockedLogSupplierBillPaymentCreate';
175
            $this->trackedevents['PAYMENT_SUPPLIER_DELETE']='BlockedLogsupplierBillPaymentCreate';
176
        }
177
         */
178
179
        // Donation
180
        if (isModEnabled('don')) {
181
            $this->trackedevents['DON_VALIDATE'] = 'logDON_VALIDATE';
182
            $this->trackedevents['DON_DELETE'] = 'logDON_DELETE';
183
            //$this->trackedevents['DON_SENTBYMAIL']='logDON_SENTBYMAIL';
184
            $this->trackedevents['DONATION_PAYMENT_CREATE'] = 'logDONATION_PAYMENT_CREATE';
185
            $this->trackedevents['DONATION_PAYMENT_DELETE'] = 'logDONATION_PAYMENT_DELETE';
186
        }
187
188
        /*
189
        // Salary
190
        if (!empty($conf->salary->enabled)) {
191
            $this->trackedevents['PAYMENT_SALARY_CREATE']='BlockedLogSalaryPaymentCreate';
192
            $this->trackedevents['PAYMENT_SALARY_MODIFY']='BlockedLogSalaryPaymentCreate';
193
            $this->trackedevents['PAYMENT_SALARY_DELETE']='BlockedLogSalaryPaymentCreate';
194
        }
195
         */
196
197
        // Members
198
        if (isModEnabled('member')) {
199
            $this->trackedevents['MEMBER_SUBSCRIPTION_CREATE'] = 'logMEMBER_SUBSCRIPTION_CREATE';
200
            $this->trackedevents['MEMBER_SUBSCRIPTION_MODIFY'] = 'logMEMBER_SUBSCRIPTION_MODIFY';
201
            $this->trackedevents['MEMBER_SUBSCRIPTION_DELETE'] = 'logMEMBER_SUBSCRIPTION_DELETE';
202
        }
203
204
        // Bank
205
        if (isModEnabled("bank")) {
206
            $this->trackedevents['PAYMENT_VARIOUS_CREATE'] = 'logPAYMENT_VARIOUS_CREATE';
207
            $this->trackedevents['PAYMENT_VARIOUS_MODIFY'] = 'logPAYMENT_VARIOUS_MODIFY';
208
            $this->trackedevents['PAYMENT_VARIOUS_DELETE'] = 'logPAYMENT_VARIOUS_DELETE';
209
        }
210
211
        // Cashdesk
212
        // $conf->global->BANK_ENABLE_POS_CASHCONTROL must be set to 1 by all external POS modules
213
        $moduleposenabled = (!empty($conf->cashdesk->enabled) || !empty($conf->takepos->enabled) || getDolGlobalString('BANK_ENABLE_POS_CASHCONTROL'));
214
        if ($moduleposenabled) {
215
            $this->trackedevents['CASHCONTROL_VALIDATE'] = 'logCASHCONTROL_VALIDATE';
216
        }
217
218
        // Add more action to track from a conf variable
219
        // For example: STOCK_MOVEMENT,...
220
        if (getDolGlobalString('BLOCKEDLOG_ADD_ACTIONS_SUPPORTED')) {
221
            $tmparrayofmoresupportedevents = explode(',', getDolGlobalString('BLOCKEDLOG_ADD_ACTIONS_SUPPORTED'));
222
            foreach ($tmparrayofmoresupportedevents as $val) {
223
                $this->trackedevents[$val] = 'log' . $val;
224
            }
225
        }
226
227
        return 1;
228
    }
229
230
    /**
231
     * Try to retrieve source object (it it still exists).
232
     *
233
     * @return string       URL string of source object
234
     */
235
    public function getObjectLink()
236
    {
237
        global $langs;
238
239
        if ($this->element === 'facture') {
240
            require_once constant('DOL_DOCUMENT_ROOT') . '/compta/facture/class/facture.class.php';
241
242
            $object = new Facture($this->db);
0 ignored issues
show
Bug introduced by
The type Dolibarr\Code\BloquedLog\Classes\Facture was not found. Did you mean Facture? If so, make sure to prefix the type with \.
Loading history...
243
            if ($object->fetch($this->fk_object) > 0) {
244
                return $object->getNomUrl(1);
245
            } else {
246
                $this->error++;
247
            }
248
        }
249
        if ($this->element === 'invoice_supplier') {
250
            require_once constant('DOL_DOCUMENT_ROOT') . '/fourn/class/fournisseur.facture.class.php';
251
252
            $object = new FactureFournisseur($this->db);
0 ignored issues
show
Bug introduced by
The type Dolibarr\Code\BloquedLog...sses\FactureFournisseur was not found. Did you mean FactureFournisseur? If so, make sure to prefix the type with \.
Loading history...
253
            if ($object->fetch($this->fk_object) > 0) {
254
                return $object->getNomUrl(1);
255
            } else {
256
                $this->error++;
257
            }
258
        } elseif ($this->element === 'payment') {
259
            require_once constant('DOL_DOCUMENT_ROOT') . '/compta/paiement/class/paiement.class.php';
260
261
            $object = new Paiement($this->db);
0 ignored issues
show
Bug introduced by
The type Dolibarr\Code\BloquedLog\Classes\Paiement was not found. Did you mean Paiement? If so, make sure to prefix the type with \.
Loading history...
262
            if ($object->fetch($this->fk_object) > 0) {
263
                return $object->getNomUrl(1);
264
            } else {
265
                $this->error++;
266
            }
267
        } elseif ($this->element === 'payment_supplier') {
268
            require_once constant('DOL_DOCUMENT_ROOT') . '/fourn/class/paiementfourn.class.php';
269
270
            $object = new PaiementFourn($this->db);
0 ignored issues
show
Bug introduced by
The type Dolibarr\Code\BloquedLog\Classes\PaiementFourn was not found. Did you mean PaiementFourn? If so, make sure to prefix the type with \.
Loading history...
271
            if ($object->fetch($this->fk_object) > 0) {
272
                return $object->getNomUrl(1);
273
            } else {
274
                $this->error++;
275
            }
276
        } elseif ($this->element === 'payment_donation') {
277
            require_once constant('DOL_DOCUMENT_ROOT') . '/don/class/paymentdonation.class.php';
278
279
            $object = new PaymentDonation($this->db);
0 ignored issues
show
Bug introduced by
The type Dolibarr\Code\BloquedLog\Classes\PaymentDonation was not found. Did you mean PaymentDonation? If so, make sure to prefix the type with \.
Loading history...
280
            if ($object->fetch($this->fk_object) > 0) {
281
                return $object->getNomUrl(1);
282
            } else {
283
                $this->error++;
284
            }
285
        } elseif ($this->element === 'payment_various') {
286
            require_once constant('DOL_DOCUMENT_ROOT') . '/compta/bank/class/paymentvarious.class.php';
287
288
            $object = new PaymentVarious($this->db);
0 ignored issues
show
Bug introduced by
The type Dolibarr\Code\BloquedLog\Classes\PaymentVarious was not found. Did you mean PaymentVarious? If so, make sure to prefix the type with \.
Loading history...
289
            if ($object->fetch($this->fk_object) > 0) {
290
                return $object->getNomUrl(1);
291
            } else {
292
                $this->error++;
293
            }
294
        } elseif ($this->element === 'don' || $this->element === 'donation') {
295
            require_once constant('DOL_DOCUMENT_ROOT') . '/don/class/don.class.php';
296
297
            $object = new Don($this->db);
0 ignored issues
show
Bug introduced by
The type Dolibarr\Code\BloquedLog\Classes\Don was not found. Did you mean Don? If so, make sure to prefix the type with \.
Loading history...
298
            if ($object->fetch($this->fk_object) > 0) {
299
                return $object->getNomUrl(1);
300
            } else {
301
                $this->error++;
302
            }
303
        } elseif ($this->element === 'subscription') {
304
            require_once constant('DOL_DOCUMENT_ROOT') . '/adherents/class/subscription.class.php';
305
306
            $object = new Subscription($this->db);
0 ignored issues
show
Bug introduced by
The type Dolibarr\Code\BloquedLog\Classes\Subscription was not found. Did you mean Subscription? If so, make sure to prefix the type with \.
Loading history...
307
            if ($object->fetch($this->fk_object) > 0) {
308
                return $object->getNomUrl(1);
309
            } else {
310
                $this->error++;
311
            }
312
        } elseif ($this->element === 'cashcontrol') {
313
            require_once constant('DOL_DOCUMENT_ROOT') . '/compta/cashcontrol/class/cashcontrol.class.php';
314
315
            $object = new CashControl($this->db);
316
            if ($object->fetch($this->fk_object) > 0) {
317
                return $object->getNomUrl(1);
318
            } else {
319
                $this->error++;
320
            }
321
        } elseif ($this->element === 'stockmouvement') {
322
            require_once constant('DOL_DOCUMENT_ROOT') . '/product/stock/class/mouvementstock.class.php';
323
324
            $object = new MouvementStock($this->db);
0 ignored issues
show
Bug introduced by
The type Dolibarr\Code\BloquedLog\Classes\MouvementStock was not found. Did you mean MouvementStock? If so, make sure to prefix the type with \.
Loading history...
325
            if ($object->fetch($this->fk_object) > 0) {
326
                return $object->getNomUrl(1);
327
            } else {
328
                $this->error++;
329
            }
330
        } elseif ($this->element === 'project') {
331
            require_once constant('DOL_DOCUMENT_ROOT') . '/projet/class/project.class.php';
332
333
            $object = new Project($this->db);
0 ignored issues
show
Bug introduced by
The type Dolibarr\Code\BloquedLog\Classes\Project was not found. Did you mean Project? If so, make sure to prefix the type with \.
Loading history...
334
            if ($object->fetch($this->fk_object) > 0) {
335
                return $object->getNomUrl(1);
336
            } else {
337
                $this->error++;
338
            }
339
        } elseif ($this->action == 'MODULE_SET') {
340
            return '<i class="opacitymedium">' . $langs->trans("BlockedLogEnabled") . '</i>';
341
        } elseif ($this->action == 'MODULE_RESET') {
342
            if ($this->signature == '0000000000') {
343
                return '<i class="opacitymedium">' . $langs->trans("BlockedLogDisabled") . '</i>';
344
            } else {
345
                return '<i class="opacitymedium">' . $langs->trans("BlockedLogDisabledBis") . '</i>';
346
            }
347
        }
348
349
        return '<i class="opacitymedium">' . $langs->trans('ImpossibleToReloadObject', $this->element, $this->fk_object) . '</i>';
350
    }
351
352
    /**
353
     *      try to retrieve user author
354
     * @return string
355
     */
356
    public function getUser()
357
    {
358
        global $langs, $cachedUser;
359
360
        if (empty($cachedUser)) {
361
            $cachedUser = array();
362
        }
363
364
        if (empty($cachedUser[$this->fk_user])) {
365
            $u = new User($this->db);
0 ignored issues
show
Bug introduced by
The type Dolibarr\Code\BloquedLog\Classes\User was not found. Did you mean User? If so, make sure to prefix the type with \.
Loading history...
366
            if ($u->fetch($this->fk_user) > 0) {
367
                $cachedUser[$this->fk_user] = $u;
368
            }
369
        }
370
371
        if (!empty($cachedUser[$this->fk_user])) {
372
            return $cachedUser[$this->fk_user]->getNomUrl(1);
373
        }
374
375
        return $langs->trans('ImpossibleToRetrieveUser', $this->fk_user);
376
    }
377
378
    /**
379
     *  Populate properties of log from object data
380
     *
381
     *  @param  CommonObject    $object     object to store
0 ignored issues
show
Bug introduced by
The type Dolibarr\Code\BloquedLog\Classes\CommonObject was not found. Did you mean CommonObject? If so, make sure to prefix the type with \.
Loading history...
382
     *  @param  string          $action     action
383
     *  @param  string          $amounts    amounts
384
     *  @param  ?User           $fuser      User object (forced)
385
     *  @return int                         >0 if OK, <0 if KO
386
     */
387
    public function setObjectData(&$object, $action, $amounts, $fuser = null)
388
    {
389
        global $langs, $user, $mysoc;
390
391
        if (is_object($fuser)) {
392
            $user = $fuser;
393
        }
394
395
        // Generic fields
396
397
        // action
398
        $this->action = $action;
399
        // amount
400
        $this->amounts = $amounts;
401
        // date
402
        if ($object->element == 'payment' || $object->element == 'payment_supplier') {
403
            $this->date_object = empty($object->datepaye) ? $object->date : $object->datepaye;
404
        } elseif ($object->element == 'payment_salary') {
405
            $this->date_object = $object->datev;
406
        } elseif ($object->element == 'payment_donation' || $object->element == 'payment_various') {
407
            $this->date_object = empty($object->datepaid) ? $object->datep : $object->datepaid;
408
        } elseif ($object->element == 'subscription') {
409
            $this->date_object = $object->dateh;
410
        } elseif ($object->element == 'cashcontrol') {
411
            $this->date_object = $object->date_creation;
412
        } elseif (property_exists($object, 'date')) {
413
            // Generic case
414
            $this->date_object = $object->date;
415
        } elseif (property_exists($object, 'datem')) {
416
            // Generic case (second chance, for example for stock movement)
417
            $this->date_object = $object->datem;
418
        }
419
420
        // ref
421
        $this->ref_object = ((!empty($object->newref)) ? $object->newref : $object->ref); // newref is set when validating a draft, ref is set in other cases
422
        // type of object
423
        $this->element = $object->element;
424
        // id of object
425
        $this->fk_object = $object->id;
426
427
428
        // Set object_data
429
        $this->object_data = new stdClass();
430
        // Add fields to exclude
431
        $arrayoffieldstoexclude = array(
432
            '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',
433
            'table_element_line', 'ismultientitymanaged', 'isextrafieldmanaged',
434
            'array_languages',
435
            'childtables',
436
            'contact_ids',
437
            'context',
438
            'labelStatus',
439
            'labelStatusShort',
440
            'linkedObjectsIds',
441
            'linkedObjects',
442
            'fk_delivery_address',
443
            'projet',          // There is already ->fk_project
444
            'restrictiononfksoc',
445
            'specimen',
446
        );
447
        // Add more fields to exclude depending on object type
448
        if ($this->element == 'cashcontrol') {
449
            $arrayoffieldstoexclude = array_merge($arrayoffieldstoexclude, array(
450
                'name', 'lastname', 'firstname', 'region', 'region_id', 'region_code', 'state', 'state_id', 'state_code', 'country', 'country_id', 'country_code',
451
                'total_ht', 'total_tva', 'total_ttc', 'total_localtax1', 'total_localtax2',
452
                'barcode_type', 'barcode_type_code', 'barcode_type_label', 'barcode_type_coder', 'mode_reglement_id', 'cond_reglement_id', 'mode_reglement', 'cond_reglement', 'shipping_method_id',
453
                'fk_incoterms', 'label_incoterms', 'location_incoterms', 'lines'));
454
        }
455
456
        // Add thirdparty info
457
        if (empty($object->thirdparty) && method_exists($object, 'fetch_thirdparty')) {
458
            $object->fetch_thirdparty();
459
        }
460
        if (!empty($object->thirdparty)) {
461
            $this->object_data->thirdparty = new stdClass();
462
463
            foreach ($object->thirdparty as $key => $value) {
464
                if (in_array($key, $arrayoffieldstoexclude)) {
465
                    continue; // Discard some properties
466
                }
467
                if (
468
                    !in_array($key, array(
469
                    'name', 'name_alias', 'ref_ext', 'address', 'zip', 'town', 'state_code', 'country_code', 'idprof1', 'idprof2', 'idprof3', 'idprof4', 'idprof5', 'idprof6', 'phone', 'fax', 'email', 'barcode',
470
                    'tva_intra', 'localtax1_assuj', 'localtax1_value', 'localtax2_assuj', 'localtax2_value', 'managers', 'capital', 'typent_code', 'forme_juridique_code', 'code_client', 'code_fournisseur'
471
                    ))
472
                ) {
473
                    continue; // Discard if not into a dedicated list
474
                }
475
                if (!is_object($value) && !is_null($value) && $value !== '') {
476
                    $this->object_data->thirdparty->$key = $value;
477
                }
478
            }
479
        }
480
481
        // Add company info
482
        if (!empty($mysoc)) {
483
            $this->object_data->mycompany = new stdClass();
484
485
            foreach ($mysoc as $key => $value) {
486
                if (in_array($key, $arrayoffieldstoexclude)) {
487
                    continue; // Discard some properties
488
                }
489
                if (
490
                    !in_array($key, array(
491
                    'name', 'name_alias', 'ref_ext', 'address', 'zip', 'town', 'state_code', 'country_code', 'idprof1', 'idprof2', 'idprof3', 'idprof4', 'idprof5', 'idprof6', 'phone', 'fax', 'email', 'barcode',
492
                    'tva_intra', 'localtax1_assuj', 'localtax1_value', 'localtax2_assuj', 'localtax2_value', 'managers', 'capital', 'typent_code', 'forme_juridique_code', 'code_client', 'code_fournisseur'
493
                    ))
494
                ) {
495
                    continue; // Discard if not into a dedicated list
496
                }
497
                if (!is_object($value) && !is_null($value) && $value !== '') {
498
                    $this->object_data->mycompany->$key = $value;
499
                }
500
            }
501
        }
502
503
        // Add user info
504
        if (!empty($user)) {
505
            $this->fk_user = $user->id;
506
            $this->user_fullname = $user->getFullName($langs);
507
        }
508
509
        // Field specific to object
510
        if ($this->element == 'facture') {
511
            foreach ($object as $key => $value) {
512
                if (in_array($key, $arrayoffieldstoexclude)) {
513
                    continue; // Discard some properties
514
                }
515
                if (
516
                    !in_array($key, array(
517
                    'ref', 'ref_client', 'ref_supplier', 'date', 'datef', 'datev', 'type', 'total_ht', 'total_tva', 'total_ttc', 'localtax1', 'localtax2', 'revenuestamp', 'datepointoftax', 'note_public', 'lines'
518
                    ))
519
                ) {
520
                    continue; // Discard if not into a dedicated list
521
                }
522
                if ($key == 'lines') {
523
                    $lineid = 0;
524
                    foreach ($value as $tmpline) {  // $tmpline is object FactureLine
525
                        $lineid++;
526
                        foreach ($tmpline as $keyline => $valueline) {
527
                            if (
528
                                !in_array($keyline, array(
529
                                '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'
530
                                ))
531
                            ) {
532
                                continue; // Discard if not into a dedicated list
533
                            }
534
535
                            if (empty($this->object_data->invoiceline[$lineid]) || !is_object($this->object_data->invoiceline[$lineid])) {      // To avoid warning
536
                                $this->object_data->invoiceline[$lineid] = new stdClass();
537
                            }
538
539
                            if (!is_object($valueline) && !is_null($valueline) && $valueline !== '') {
540
                                $this->object_data->invoiceline[$lineid]->$keyline = $valueline;
541
                            }
542
                        }
543
                    }
544
                } elseif (!is_object($value) && !is_null($value) && $value !== '') {
545
                    $this->object_data->$key = $value;
546
                }
547
            }
548
549
            if (!empty($object->newref)) {
550
                $this->object_data->ref = $object->newref;
551
            }
552
        } elseif ($this->element == 'invoice_supplier') {
553
            foreach ($object as $key => $value) {
554
                if (in_array($key, $arrayoffieldstoexclude)) {
555
                    continue; // Discard some properties
556
                }
557
                if (
558
                    !in_array($key, array(
559
                    'ref', 'ref_client', 'ref_supplier', 'date', 'datef', 'type', 'total_ht', 'total_tva', 'total_ttc', 'localtax1', 'localtax2', 'revenuestamp', 'datepointoftax', 'note_public'
560
                    ))
561
                ) {
562
                    continue; // Discard if not into a dedicated list
563
                }
564
                if (!is_object($value) && !is_null($value) && $value !== '') {
565
                    $this->object_data->$key = $value;
566
                }
567
            }
568
569
            if (!empty($object->newref)) {
570
                $this->object_data->ref = $object->newref;
571
            }
572
        } elseif ($this->element == 'payment' || $this->element == 'payment_supplier' || $this->element == 'payment_donation' || $this->element == 'payment_various') {
573
            $datepayment = $object->datepaye ? $object->datepaye : ($object->datepaid ? $object->datepaid : $object->datep);
574
            $paymenttypeid = $object->paiementid ? $object->paiementid : ($object->paymenttype ? $object->paymenttype : $object->type_payment);
575
576
            $this->object_data->ref = $object->ref;
577
            $this->object_data->date = $datepayment;
578
            $this->object_data->type_code = dol_getIdFromCode($this->db, $paymenttypeid, 'c_paiement', 'id', 'code');
579
580
            if (!empty($object->num_payment)) {
581
                $this->object_data->payment_num = $object->num_payment;
582
            }
583
            if (!empty($object->note_private)) {
584
                $this->object_data->note_private = $object->note_private;
585
            }
586
            //$this->object_data->fk_account = $object->fk_account;
587
            //var_dump($this->object_data);exit;
588
589
            $totalamount = 0;
590
591
            // Loop on each invoice payment amount (payment_part)
592
            if (is_array($object->amounts) && !empty($object->amounts)) {
593
                $paymentpartnumber = 0;
594
                foreach ($object->amounts as $objid => $amount) {
595
                    if (empty($amount)) {
596
                        continue;
597
                    }
598
599
                    $totalamount += $amount;
600
601
                    $tmpobject = null;
602
                    if ($this->element == 'payment_supplier') {
603
                        include_once DOL_DOCUMENT_ROOT . '/fourn/class/fournisseur.facture.class.php';
604
                        $tmpobject = new FactureFournisseur($this->db);
605
                    } elseif ($this->element == 'payment') {
606
                        include_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php';
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)) {
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