Test Failed
Push — master ( 99a915...bca16c )
by Vítězslav
07:03
created

FlexiBeeRO::performAction()   B

Complexity

Conditions 6
Paths 7

Size

Total Lines 36
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 23
CRAP Score 6.1169

Importance

Changes 0
Metric Value
cc 6
eloc 26
nc 7
nop 2
dl 0
loc 36
ccs 23
cts 27
cp 0.8519
crap 6.1169
rs 8.439
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
A FlexiBeeRO::getVazby() 0 15 4
1
<?php
2
/**
3
 * FlexiPeeHP - Read Only Access to FlexiBee class.
4
 *
5
 * @author     Vítězslav Dvořák <[email protected]>
6
 * @copyright  (C) 2015-2017 Spoje.Net
7
 */
8
9
namespace FlexiPeeHP;
10
11
/**
12
 * Základní třída pro čtení z FlexiBee
13
 *
14
 * @url https://demo.flexibee.eu/devdoc/
15
 */
16
class FlexiBeeRO extends \Ease\Brick
17
{
18
    /**
19
     * Where to get JSON files with evidence stricture etc.
20
     * @var string
21
     */
22
    public static $infoDir = __DIR__.'/../../static';
23
24
    /**
25
     * Version of FlexiPeeHP library
26
     *
27
     * @var string
28
     */
29
    public static $libVersion = '1.8.4.3';
30
31
    /**
32
     * Základní namespace pro komunikaci s FlexiBee.
33
     * Basic namespace for communication with FlexiBee
34
     *
35
     * @var string Jmený prostor datového bloku odpovědi
36
     */
37
    public $nameSpace = 'winstrom';
38
39
    /**
40
     * URL of object data in FlexiBee
41
     * @var string url
42
     */
43
    public $apiURL = null;
44
45
    /**
46
     * Datový blok v poli odpovědi.
47
     * Data block in response field.
48
     *
49
     * @var string
50
     */
51
    public $resultField = 'results';
52
53
    /**
54
     * Verze protokolu použitého pro komunikaci.
55
     * Communication protocol version used.
56
     *
57
     * @var string Verze použitého API
58
     */
59
    public $protoVersion = '1.0';
60
61
    /**
62
     * Evidence užitá objektem.
63
     * Evidence used by object
64
     *
65
     * @link https://demo.flexibee.eu/c/demo/evidence-list Přehled evidencí
66
     * @var string
67
     */
68
    public $evidence = null;
69
70
    /**
71
     * Výchozí formát pro komunikaci.
72
     * Default communication format.
73
     *
74
     * @link https://www.flexibee.eu/api/dokumentace/ref/format-types Přehled možných formátů
75
     *
76
     * @var string json|xml|...
77
     */
78
    public $format = 'json';
79
80
    /**
81
     * formát příchozí odpovědi
82
     * response format
83
     *
84
     * @link https://www.flexibee.eu/api/dokumentace/ref/format-types Přehled možných formátů
85
     *
86
     * @var string json|xml|...
87
     */
88
    public $responseFormat = 'json';
89
90
    /**
91
     * Curl Handle.
92
     *
93
     * @var resource
94
     */
95
    public $curl = null;
96
97
    /**
98
     * @link https://demo.flexibee.eu/devdoc/company-identifier Identifikátor firmy
99
     * @var string
100
     */
101
    public $company = null;
102
103
    /**
104
     * Server[:port]
105
     * @var string
106
     */
107
    public $url = null;
108
109
    /**
110
     * REST API Username
111
     * @var string
112
     */
113
    public $user = null;
114
115
    /**
116
     * REST API Password
117
     * @var string
118
     */
119
    public $password = null;
120
121
    /**
122
     * @var array Pole HTTP hlaviček odesílaných s každým požadavkem
123
     */
124
    public $defaultHttpHeaders = ['User-Agent' => 'FlexiPeeHP'];
125
126
    /**
127
     * Default additional request url parameters after question mark
128
     *
129
     * @link https://www.flexibee.eu/api/dokumentace/ref/urls   Common params
130
     * @link https://www.flexibee.eu/api/dokumentace/ref/paging Paging params
131
     * @var array
132
     */
133
    public $defaultUrlParams = ['limit' => 0];
134
135
    /**
136
     * Identifikační řetězec.
137
     *
138
     * @var string
139
     */
140
    public $init = null;
141
142
    /**
143
     * Sloupeček s názvem.
144
     *
145
     * @var string
146
     */
147
    public $nameColumn = 'nazev';
148
149
    /**
150
     * Sloupeček obsahující datum vložení záznamu do shopu.
151
     *
152
     * @var string
153
     */
154
    public $myCreateColumn = 'false';
155
156
    /**
157
     * Slopecek obsahujici datum poslení modifikace záznamu do shopu.
158
     *
159
     * @var string
160
     */
161
    public $myLastModifiedColumn = 'lastUpdate';
162
163
    /**
164
     * Klíčový idendifikátor záznamu.
165
     *
166
     * @var string
167
     */
168
    public $fbKeyColumn = 'id';
169
170
    /**
171
     * Informace o posledním HTTP requestu.
172
     *
173
     * @var *
174
     */
175
    public $curlInfo;
176
177
    /**
178
     * Informace o poslední HTTP chybě.
179
     *
180
     * @var string
181
     */
182
    public $lastCurlError = null;
183
184
    /**
185
     * Used codes storage.
186
     *
187
     * @var array
188
     */
189
    public $codes = null;
190
191
    /**
192
     * Last Inserted ID.
193
     *
194
     * @var int
195
     */
196
    public $lastInsertedID = null;
197
198
    /**
199
     * Default Line Prefix.
200
     *
201
     * @var string
202
     */
203
    public $prefix = '/c/';
204
205
    /**
206
     * Raw Content of last curl response
207
     *
208
     * @var string
209
     */
210
    public $lastCurlResponse;
211
212
    /**
213
     * HTTP Response code of last request
214
     *
215
     * @var int
216
     */
217
    public $lastResponseCode = null;
218
219
    /**
220
     * Body data  for next curl POST operation
221
     *
222
     * @var string
223
     */
224
    protected $postFields = null;
225
226
    /**
227
     * Last operation result data or message(s)
228
     *
229
     * @var array
230
     */
231
    public $lastResult = null;
232
233
    /**
234
     * Number from  @rowCount in response
235
     * @var int
236
     */
237
    public $rowCount = null;
238
239
    /**
240
     * Number from  @globalVersion
241
     * @var int
242
     */
243
    public $globalVersion = null;
244
245
    /**
246
     * @link https://www.flexibee.eu/api/dokumentace/ref/zamykani-odemykani/
247
     * @var string filter query
248
     */
249
    public $filter;
250
251
    /**
252
     * @link https://demo.flexibee.eu/devdoc/actions Provádění akcí
253
     * @var string
254
     */
255
    protected $action;
256
257
    /**
258
     * Pole akcí které podporuje ta která evidence
259
     * @link https://demo.flexibee.eu/c/demo/faktura-vydana/actions.json Např. Akce faktury
260
     * @var array
261
     */
262
    public $actionsAvailable = null;
263
264
    /**
265
     * Parmetry pro URL
266
     * @link https://www.flexibee.eu/api/dokumentace/ref/urls/ Všechny podporované parametry
267
     * @var array
268
     */
269
    public $urlParams = [
270
        'idUcetniObdobi',
271
        'dry-run',
272
        'fail-on-warning',
273
        'report-name',
274
        'report-lang',
275
        'report-sign',
276
        'detail', //See: https://www.flexibee.eu/api/dokumentace/ref/detail-levels
277
        'mode',
278
        'limit',
279
        'start',
280
        'order',
281
        'sort',
282
        'add-row-count',
283
        'relations',
284
        'includes',
285
        'use-ext-id',
286
        'use-internal-id',
287
        'stitky-as-ids',
288
        'only-ext-ids',
289
        'no-ext-ids',
290
        'no-ids',
291
        'code-as-id',
292
        'no-http-errors',
293
        'export-settings',
294
        'as-gui',
295
        'code-in-response',
296
        'add-global-version',
297
        'encoding',
298
        'delimeter',
299
        'format',
300
        'auth',
301
        'skupina-stitku',
302
        'dir',
303
        'relations',
304
        'relations',
305
        'xpath', // See: https://www.flexibee.eu/api/dokumentace/ref/xpath/
306
        'dry-run', // See: https://www.flexibee.eu/api/dokumentace/ref/dry-run/
307
        'inDesktopApp' // Note: Undocumented function (html only)
308
    ];
309
310
    /**
311
     * Save 404 results to log ?
312
     * @var boolean
313
     */
314
    protected $ignoreNotFound = false;
315
316
    /**
317
     * Array of errors caused by last request
318
     * @var array
319
     */
320
    private $errors = [];
321
322
    /**
323
     * List of Error500 reports sent
324
     * @var array
325
     */
326
    private $reports = [];
327
328
    /**
329
     * Send Error500 Report to
330
     * @var string email address
331
     */
332
    public $reportRecipient = '[email protected]';
333
334
    /**
335
     * Class for read only interaction with FlexiBee.
336
     *
337
     * @param mixed $init default record id or initial data
338
     * @param array $options Connection settings override
339
     */
340 70
    public function __construct($init = null, $options = [])
341
    {
342 70
        $this->init = $init;
343
344 70
        parent::__construct();
345 70
        $this->setUp($options);
346 70
        $this->curlInit();
347 70
        if (!empty($init)) {
348 22
            $this->processInit($init);
349 22
        }
350 70
    }
351
352
    /**
353
     * SetUp Object to be ready for connect
354
     *
355
     * @param array $options Object Options (company,url,user,password,evidence,
356
     *                                       prefix,defaultUrlParams,debug)
357
     */
358 71
    public function setUp($options = [])
359
    {
360 71
        $this->setupProperty($options, 'company', 'FLEXIBEE_COMPANY');
361 71
        $this->setupProperty($options, 'url', 'FLEXIBEE_URL');
362 71
        $this->setupProperty($options, 'user', 'FLEXIBEE_LOGIN');
363 71
        $this->setupProperty($options, 'password', 'FLEXIBEE_PASSWORD');
364 71
        if (isset($options['evidence'])) {
365 23
            $this->setEvidence($options['evidence']);
366 23
        }
367 71
        $this->setupProperty($options, 'defaultUrlParams');
368 71
        if (isset($options['prefix'])) {
369 23
            $this->setPrefix($options['prefix']);
370 23
        }
371 71
        if (array_key_exists('detail', $options)) {
372
            $this->defaultUrlParams['detail'] = $options['detail'];
373
        }
374 71
        $this->setupProperty($options, 'debug');
375 71
        $this->updateApiURL();
376 71
    }
377
378
    /**
379
     * Set up one of properties
380
     *
381
     * @param array  $options  array of given properties
382
     * @param string $name     name of property to process
383
     * @param string $constant load default property value from constant
384
     */
385 48
    public function setupProperty($options, $name, $constant = null)
386
    {
387 48
        if (isset($options[$name])) {
388
            $this->$name = $options[$name];
389
        } else {
390 48
            if (property_exists($this, $name) && !empty($constant) && defined($constant)) {
391 48
                $this->$name = constant($constant);
392 48
            }
393
        }
394 48
    }
395
396
    /**
397
     * Inicializace CURL
398
     */
399 94
    public function curlInit()
400
    {
401 94
        $this->curl = \curl_init(); // create curl resource
402 94
        curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, true); // return content as a string from curl_exec
403 94
        curl_setopt($this->curl, CURLOPT_FOLLOWLOCATION, true); // follow redirects (compatibility for future changes in FlexiBee)
404 94
        curl_setopt($this->curl, CURLOPT_HTTPAUTH, true);       // HTTP authentication
405 94
        curl_setopt($this->curl, CURLOPT_SSL_VERIFYPEER, false); // FlexiBee by default uses Self-Signed certificates
406 94
        curl_setopt($this->curl, CURLOPT_SSL_VERIFYHOST, false);
407 94
        curl_setopt($this->curl, CURLOPT_VERBOSE, ($this->debug === true)); // For debugging
408 94
        curl_setopt($this->curl, CURLOPT_USERPWD,
409 94
            $this->user.':'.$this->password); // set username and password
410 94
    }
411
412
    /**
413
     * Zinicializuje objekt dle daných dat. Možné hodnoty:
414
     *
415
     *  * 234                              - interní číslo záznamu k načtení
416
     *  * code:LOPATA                      - kód záznamu
417
     *  * BAGR                             - kód záznamu k načtení
418
     *  * ['id'=>24,'nazev'=>'hoblík']     - pole hodnot k předvyplnění
419
     *  * 743.json?relations=adresa,vazby  - část url s parametry k načtení
420
     *
421
     * @param mixed $init číslo/"(code:)kód"/(část)URI záznamu k načtení | pole hodnot k předvyplnění
422
     */
423 13
    public function processInit($init)
424
    {
425 13
        if (is_integer($init)) {
426 11
            $this->loadFromFlexiBee($init);
427 13
        } elseif (is_array($init)) {
428 13
            $this->takeData($init);
429 13
        } elseif (preg_match('/\.(json|xml|csv)/', $init)) {
430 11
            $this->takeData($this->getFlexiData((($init[0] != '/') ? $this->getEvidenceURL($init)
0 ignored issues
show
Unused Code introduced by
The call to FlexiBeeRO::getEvidenceURL() has too many arguments starting with $init.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
431 11
                            : $init)));
432 11
        } else {
433 8
            $this->loadFromFlexiBee($init);
434
        }
435 13
    }
436
437
    /**
438
     * Set URL prefix
439
     *
440
     * @param string $prefix
441
     */
442 23
    public function setPrefix($prefix)
443
    {
444
        switch ($prefix) {
445 23
            case 'a': //Access
446 23
            case 'c': //Company
447 23
            case 'u': //User
448 23
            case 'g': //License Groups
449 23
            case 'admin':
450 23
            case 'status':
451 23
            case 'login-logout':
452 23
                $this->prefix = '/'.$prefix.'/';
453 23
                break;
454 23
            case null:
455 23
            case '':
456 23
            case '/':
457 23
                $this->prefix = '';
458 23
                break;
459 23
            default:
460 23
                throw new \Exception(sprintf('Unknown prefix %s', $prefix));
461 23
        }
462 23
    }
463
464
    /**
465
     * Set communication format.
466
     * One of html|xml|json|csv|dbf|xls|isdoc|isdocx|edi|pdf|pdf|vcf|ical
467
     *
468
     * @param string $format
469
     * @return boolen format is availble
470
     */
471 23
    public function setFormat($format)
472
    {
473 23
        $result = true;
474 23
        if (($this->debug === true) && !empty($this->evidence) && isset(Formats::$$this->evidence)) {
475
            if (array_key_exists($format, array_flip(Formats::$$this->evidence))
476
                === false) {
477
                $result = false;
478
            }
479
        }
480 23
        if ($result === true) {
481 23
            $this->format = $format;
482 23
            $this->updateApiURL();
483 23
        }
484 23
        return $result;
485
    }
486
487
    /**
488
     * Nastaví Evidenci pro Komunikaci.
489
     * Set evidence for communication
490
     *
491
     * @param string $evidence evidence pathName to use
492
     * @return boolean evidence switching status
493
     */
494 23
    public function setEvidence($evidence)
495
    {
496 23
        switch ($this->prefix) {
497 23
            case '/c/':
498 23
                if ($this->debug === true) {
499 23
                    if (array_key_exists($evidence, EvidenceList::$name)) {
500
                        $this->evidence = $evidence;
501
                        $result         = true;
502
                    } else {
503 23
                        throw new \Exception(sprintf('Try to set unsupported evidence %s',
504 23
                                $evidence));
505
                    }
506
                } else {
507 20
                    $this->evidence = $evidence;
508 20
                    $result         = true;
509
                }
510 20
                break;
511 3
            default:
512 3
                $this->evidence = $evidence;
513 3
                $result         = true;
514 3
                break;
515 23
        }
516 23
        $this->updateApiURL();
517 23
        return $result;
518
    }
519
520
    /**
521
     * Vrací právě používanou evidenci pro komunikaci
522
     * Obtain current used evidence
523
     *
524
     * @return string
525
     */
526 69
    public function getEvidence()
527
    {
528 69
        return $this->evidence;
529
    }
530
531
    /**
532
     * Set used company.
533
     * Nastaví Firmu.
534
     *
535
     * @param string $company
536
     */
537 23
    public function setCompany($company)
538
    {
539 23
        $this->company = $company;
540 23
    }
541
542
    /**
543
     * Obtain company now used
544
     * Vrací právě používanou firmu
545
     *
546
     * @return string
547
     */
548 23
    public function getCompany()
549
    {
550 23
        return $this->company;
551
    }
552
553
    /**
554
     * Vrací název evidence použité v odpovědích z FlexiBee
555
     *
556
     * @return string
557
     */
558 25
    public function getResponseEvidence()
559
    {
560 25
        switch ($this->evidence) {
561 25
            case 'c':
562
                $evidence = 'company';
563
                break;
564 25
            case 'evidence-list':
565 1
                $evidence = 'evidence';
566 1
                break;
567 24
            default:
568 24
                $evidence = $this->getEvidence();
569 24
                break;
570 25
        }
571 25
        return $evidence;
572
    }
573
574
    /**
575
     * Převede rekurzivně Objekt na pole.
576
     *
577
     * @param object|array $object
578
     *
579
     * @return array
580
     */
581 23
    public static function object2array($object)
582
    {
583 23
        $result = null;
584 23
        if (is_object($object)) {
585 23
            $objectData = get_object_vars($object);
586 23
            if (is_array($objectData) && count($objectData)) {
587 23
                $result = array_map('self::object2array', $objectData);
588 23
            }
589 23
        } else {
590 23
            if (is_array($object)) {
591 23
                foreach ($object as $item => $value) {
592 23
                    $result[$item] = self::object2array($value);
593 23
                }
594 23
            } else {
595 23
                $result = $object;
596
            }
597
        }
598
599 23
        return $result;
600
    }
601
602
    /**
603
     * Převede rekurzivně v poli všechny objekty na jejich identifikátory.
604
     *
605
     * @param object|array $object
606
     *
607
     * @return array
608
     */
609 23
    public static function objectToID($object)
610
    {
611 23
        $resultID = null;
612 23
        if (is_object($object)) {
613 22
            $resultID = $object->__toString();
614 22
        } else {
615 23
            if (is_array($object)) {
616 17
                foreach ($object as $item => $value) {
617 17
                    $resultID[$item] = self::objectToID($value);
618 17
                }
619 17
            } else { //String
620 23
                $resultID = $object;
621
            }
622
        }
623
624 23
        return $resultID;
625
    }
626
627
    /**
628
     * Return basic URL for used Evidence
629
     *
630
     * @link https://www.flexibee.eu/api/dokumentace/ref/urls/ Sestavování URL
631
     *
632
     * @return string Evidence URL
633
     */
634 68
    public function getEvidenceURL()
635
    {
636 68
        $evidenceUrl = $this->url.$this->prefix.$this->company;
637 68
        $evidence    = $this->getEvidence();
638 68
        if (!empty($evidence)) {
639 62
            $evidenceUrl .= '/'.$evidence;
640 62
        }
641 68
        return $evidenceUrl;
642
    }
643
644
    /**
645
     * Add suffix to Evidence URL
646
     *
647
     * @param string $urlSuffix
648
     *
649
     * @return string
650
     */
651 23
    public function evidenceUrlWithSuffix($urlSuffix)
652
    {
653 23
        $evidenceUrl = $this->getEvidenceUrl();
654 23
        if (!empty($urlSuffix)) {
655 23
            if (($urlSuffix[0] != '/') && ($urlSuffix[0] != ';') && ($urlSuffix[0]
656 23
                != '?')) {
657 23
                $evidenceUrl .= '/';
658 23
            }
659 23
            $evidenceUrl .= $urlSuffix;
660 23
        }
661 23
        return $evidenceUrl;
662
    }
663
664
    /**
665
     * Update $this->apiURL
666
     */
667 48
    public function updateApiURL()
668
    {
669 48
        $this->apiURL = $this->getEvidenceURL();
670 48
        $id           = $this->__toString();
671 48
        if (!empty($id)) {
672
            $this->apiURL .= '/'.urlencode($id);
673
        }
674 48
        $this->apiURL .= '.'.$this->format;
675 48
    }
676
677
    /**
678
     * Add params to url
679
     *
680
     * @param string  $url      originall url
681
     * @param array   $params   value to add
682
     * @param boolean $override replace already existing values ?
683
     *
684
     * @return string url with parameters added
685
     */
686 23
    public function addUrlParams($url, $params, $override = false)
687
    {
688 23
        $urlParts = parse_url($url);
689 23
        $urlFinal = '';
690 23
        if (array_key_exists('scheme', $urlParts)) {
691 23
            $urlFinal .= $urlParts['scheme'].'://'.$urlParts['host'];
692 23
        }
693 23
        if (array_key_exists('path', $urlParts)) {
694 23
            $urlFinal .= $urlParts['path'];
695 23
        }
696 23
        if (array_key_exists('query', $urlParts)) {
697 23
            parse_str($urlParts['query'], $queryUrlParams);
698 23
            $urlParams = $override ? array_merge($params, $queryUrlParams) : array_merge($queryUrlParams,
699 23
                    $params);
700 23
        } else {
701
            $urlParams = $params;
702
        }
703 23
        if (!empty($urlParams) && is_array($urlParams)) {
704 23
            $urlFinal .= '?'.http_build_query($urlParams);
705 23
        } else {
706
            $urlFinal .= '?'.$urlParams;
707
        }
708 23
        return $urlFinal;
709
    }
710
711
    /**
712
     * Add Default Url params to given url if not overrided
713
     *
714
     * @param string $urlRaw
715
     *
716
     * @return string url with default params added
717
     */
718 23
    public function addDefaultUrlParams($urlRaw)
719
    {
720 23
        return $this->addUrlParams($urlRaw, $this->defaultUrlParams, false);
721
    }
722
723
    /**
724
     * Funkce, která provede I/O operaci a vyhodnotí výsledek.
725
     *
726
     * @param string $urlSuffix část URL za identifikátorem firmy.
727
     * @param string $method    HTTP/REST metoda
728
     * @param string $format    Requested format
729
     * @return array|boolean Výsledek operace
730
     */
731 26
    public function performRequest($urlSuffix = null, $method = 'GET',
732
                                   $format = null)
733
    {
734 26
        $this->rowCount = null;
735
736 26
        if (preg_match('/^http/', $urlSuffix)) {
737
            $url = $urlSuffix;
738 26
        } elseif (strlen($urlSuffix) && ($urlSuffix[0] == '/')) {
739 4
            $url = $this->url.$urlSuffix;
740 4
        } else {
741 23
            $url = $this->evidenceUrlWithSuffix($urlSuffix);
742
        }
743
744 26
        $responseCode = $this->doCurlRequest($url, $method, $format);
745
746 26
        return $this->parseResponse($this->rawResponseToArray($this->lastCurlResponse,
0 ignored issues
show
Bug introduced by
It seems like $this->rawResponseToArra... $this->responseFormat) targeting FlexiPeeHP\FlexiBeeRO::rawResponseToArray() can also be of type string; however, FlexiPeeHP\FlexiBeeRO::parseResponse() does only seem to accept array, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
747 26
                    $this->responseFormat), $responseCode);
748
    }
749
750
    /**
751
     * Parse Raw FlexiBee response in several formats
752
     *
753
     * @param string $responseRaw raw response body
754
     * @param string $format      Raw Response format json|xml|etc
755
     *
756
     * @return array
757
     */
758 3
    public function rawResponseToArray($responseRaw, $format)
759
    {
760
        switch ($format) {
761 3
            case 'json':
762 3
                $responseDecoded = $this->rawJsonToArray($responseRaw);
763 3
                break;
764
            case 'xml':
765
                $responseDecoded = $this->rawXmlToArray($this->lastCurlResponse);
766
                break;
767
            case 'txt':
768
            default:
769
                $responseDecoded = $this->lastCurlResponse;
770
                break;
771
        }
772 3
        return $responseDecoded;
773
    }
774
775
    /**
776
     * Convert FlexiBee Response JSON to Array
777
     *
778
     * @param string $rawJson
779
     * 
780
     * @return array
781
     */
782 3
    public function rawJsonToArray($rawJson)
783
    {
784 3
        $responseDecoded = json_decode($rawJson, true, 10);
785 3
        $decodeError     = json_last_error_msg();
786 3
        if ($decodeError == 'No error') {
787 3
            if (array_key_exists($this->nameSpace, $responseDecoded)) {
788
                $responseDecoded = $responseDecoded[$this->nameSpace];
789
            }
790 3
        } else {
791
            $this->addStatusMessage('JSON Decoder: '.$decodeError, 'error');
792
            $this->addStatusMessage($rawJson, 'debug');
793
        }
794 3
        return $responseDecoded;
795
    }
796
797
    /**
798
     * Convert FlexiBee Response XML to Array
799
     *
800
     * @param string $rawXML
801
     *
802
     * @return array
803
     */
804
    public function rawXmlToArray($rawXML)
805
    {
806
        return self::xml2array($rawXML);
807
    }
808
809
    /**
810
     * Parse Response array
811
     *
812
     * @param array $responseDecoded
813
     * @param int $responseCode Request Response Code
814
     *
815
     * @return array main data part of response
816
     */
817 3
    public function parseResponse($responseDecoded, $responseCode)
818
    {
819 3
        $response = null;
820
        switch ($responseCode) {
821 3
            case 201: //Success Write
0 ignored issues
show
Coding Style introduced by
There must be a comment when fall-through is intentional in a non-empty case body
Loading history...
822
                if (isset($responseDecoded[$this->resultField][0]['id'])) {
823
                    $this->lastInsertedID = $responseDecoded[$this->resultField][0]['id'];
824
                    $this->setMyKey($this->lastInsertedID);
825
                    $this->apiURL         = $this->getEvidenceURL().'/'.$this->lastInsertedID;
826
                } else {
827
                    $this->lastInsertedID = null;
828
                }
829 3
            case 200: //Success Read
830 3
                $response         = $this->lastResult = $this->unifyResponseFormat($responseDecoded);
831 3
                if (isset($responseDecoded['@rowCount'])) {
832
                    $this->rowCount = (int) $responseDecoded['@rowCount'];
833
                }
834 3
                if (isset($responseDecoded['@globalVersion'])) {
835
                    $this->globalVersion = (int) $responseDecoded['@globalVersion'];
836
                }
837 3
                break;
838
839
            case 500: // Internal Server Error
0 ignored issues
show
Coding Style introduced by
There must be a comment when fall-through is intentional in a non-empty case body
Loading history...
840
                if ($this->debug === true) {
841
                    $this->error500Reporter($responseDecoded);
842
                }
843
            case 404: // Page not found
0 ignored issues
show
Coding Style introduced by
There must be a comment when fall-through is intentional in a non-empty case body
Loading history...
844
                if ($this->ignoreNotFound === true) {
845
                    break;
846
                }
847
            case 400: //Bad Request parameters
848
            default: //Something goes wrong
849
                $this->addStatusMessage($this->lastResponseCode.': '.$this->curlInfo['url'],
850
                    'warning');
851
                if (is_array($responseDecoded)) {
852
                    $this->parseError($responseDecoded);
853
                }
854
                $this->logResult($responseDecoded, $this->curlInfo['url']);
855
                break;
856
        }
857 3
        return $response;
858
    }
859
860
    /**
861
     * Parse error message response
862
     *
863
     * @param array $responseDecoded
864
     * @return int number of errors processed
865
     */
866
    public function parseError(array $responseDecoded)
867
    {
868
        if (array_key_exists('results', $responseDecoded)) {
869
            $this->errors = $responseDecoded['results'][0]['errors'];
870
        } else {
871
            if (array_key_exists('message', $responseDecoded)) {
872
                $this->errors = [['message' => $responseDecoded['message']]];
873
            }
874
        }
875
        return count($this->errors);
876
    }
877
878
    /**
879
     * Vykonej HTTP požadavek
880
     *
881
     * @link https://www.flexibee.eu/api/dokumentace/ref/urls/ Sestavování URL
882
     * @param string $url    URL požadavku
883
     * @param string $method HTTP Method GET|POST|PUT|OPTIONS|DELETE
884
     * @param string $format požadovaný formát komunikace
885
     * @return int HTTP Response CODE
886
     */
887 3
    public function doCurlRequest($url, $method, $format = null)
888
    {
889 3
        if (is_null($format)) {
890 3
            $format = $this->format;
891 3
        }
892 3
        curl_setopt($this->curl, CURLOPT_URL, $url);
893
// Nastavení samotné operace
894 3
        curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, strtoupper($method));
895
//Vždy nastavíme byť i prázná postdata jako ochranu před chybou 411
896 3
        curl_setopt($this->curl, CURLOPT_POSTFIELDS, $this->postFields);
897
898 3
        $httpHeaders = $this->defaultHttpHeaders;
899
900 3
        $formats = Formats::bySuffix();
901
902 3
        if (!isset($httpHeaders['Accept'])) {
903 3
            $httpHeaders['Accept'] = $formats[$format]['content-type'];
904 3
        }
905 3
        if (!isset($httpHeaders['Content-Type'])) {
906 3
            $httpHeaders['Content-Type'] = $formats[$format]['content-type'];
907 3
        }
908 3
        $httpHeadersFinal = [];
909 3
        foreach ($httpHeaders as $key => $value) {
910 3
            if (($key == 'User-Agent') && ($value == 'FlexiPeeHP')) {
911 3
                $value .= ' v'.self::$libVersion;
912 3
            }
913 3
            $httpHeadersFinal[] = $key.': '.$value;
914 3
        }
915
916 3
        curl_setopt($this->curl, CURLOPT_HTTPHEADER, $httpHeadersFinal);
917
918
// Proveď samotnou operaci
919 3
        $this->lastCurlResponse            = curl_exec($this->curl);
920 3
        $this->curlInfo                    = curl_getinfo($this->curl);
921 3
        $this->curlInfo['when']            = microtime();
922 3
        $this->curlInfo['request_headers'] = $httpHeadersFinal;
923 3
        $this->responseFormat              = isset($this->curlInfo['content_type'])
924 3
                ? Formats::contentTypeToSuffix($this->curlInfo['content_type']) : 'txt';
925 3
        $this->lastResponseCode            = $this->curlInfo['http_code'];
926 3
        $this->lastCurlError               = curl_error($this->curl);
927 3
        if (strlen($this->lastCurlError)) {
928
            $this->addStatusMessage(sprintf('Curl Error (HTTP %d): %s',
929
                    $this->lastResponseCode, $this->lastCurlError), 'error');
930
        }
931
932 3
        if ($this->debug === true) {
933
            $this->saveDebugFiles();
934
        }
935
936 3
        return $this->lastResponseCode;
937
    }
938
939
    /**
940
     * Nastaví druh prováděné akce.
941
     *
942
     * @link https://demo.flexibee.eu/devdoc/actions Provádění akcí
943
     * @param string $action
944
     * @return boolean
945
     */
946 23
    public function setAction($action)
947
    {
948 23
        $result           = false;
949 23
        $actionsAvailable = $this->getActionsInfo();
950 23
        if (is_array($actionsAvailable) && array_key_exists($action,
951 23
                $actionsAvailable)) {
952 15
            $this->action = $action;
953 15
            $result       = true;
954 15
        }
955 23
        return $result;
956
    }
957
958
    /**
959
     * Convert XML to array.
960
     *
961
     * @param string $xml
962
     *
963
     * @return array
964
     */
965 23
    public static function xml2array($xml)
966
    {
967 23
        $arr = [];
968 23
        if (!empty($xml)) {
969 23
            if (is_string($xml)) {
970 23
                $xml = simplexml_load_string($xml);
971 23
            }
972
973 23
            foreach ($xml->children() as $r) {
974 23
                if (count($r->children()) == 0) {
975 23
                    $arr[$r->getName()] = strval($r);
976 23
                } else {
977 23
                    $arr[$r->getName()][] = self::xml2array($r);
978
                }
979 23
            }
980 23
        }
981 23
        return $arr;
982
    }
983
984
    /**
985
     * Odpojení od FlexiBee.
986
     */
987 1
    public function disconnect()
988
    {
989 1
        if (is_resource($this->curl)) {
990 1
            curl_close($this->curl);
991 1
        }
992 1
        $this->curl = null;
993 1
    }
994
995
    /**
996
     * Disconnect CURL befere pass away
997
     */
998 1
    public function __destruct()
999
    {
1000 1
        $this->disconnect();
1001 1
    }
1002
1003
    /**
1004
     * Načte řádek dat z FlexiBee.
1005
     *
1006
     * @param int $recordID id požadovaného záznamu
1007
     *
1008
     * @return array
1009
     */
1010 23
    public function getFlexiRow($recordID)
1011
    {
1012 23
        $record   = null;
1013 23
        $response = $this->performRequest($this->evidence.'/'.$recordID.'.json');
1014 23
        if (isset($response[$this->evidence])) {
1015
            $record = $response[$this->evidence][0];
1016
        }
1017
1018 23
        return $record;
1019
    }
1020
1021
    /**
1022
     * Oddělí z pole podmínek ty jenž patří za ? v URL požadavku
1023
     *
1024
     * @link https://www.flexibee.eu/api/dokumentace/ref/urls/ Sestavování URL
1025
     * @param array $conditions pole podmínek   - rendrují se do ()
1026
     * @param array $urlParams  pole parametrů  - rendrují za ?
1027
     */
1028
    public function extractUrlParams(&$conditions, &$urlParams)
1029
    {
1030
        foreach ($this->urlParams as $urlParam) {
1031
            if (isset($conditions[$urlParam])) {
1032
                \Ease\Sand::divDataArray($conditions, $urlParams, $urlParam);
1033
            }
1034
        }
1035
    }
1036
1037
    /**
1038
     * convert unicode to entities
1039
     *
1040
     * @param string $urlRaw
1041
     * @return string
1042
     */
1043
    public static function urlEncode($urlRaw)
1044
    {
1045
        return str_replace(['%27'], ["'"], rawurlencode($urlRaw));
1046
    }
1047
1048
    /**
1049
     * Načte data z FlexiBee.
1050
     *
1051
     * @param string $suffix     dotaz
1052
     * @param string|array $conditions Volitelný filtrovací výraz
1053
     *
1054
     * @return array Data obtained
1055
     */
1056 16
    public function getFlexiData($suffix = null, $conditions = null)
1057
    {
1058 16
        $finalUrl  = '';
1059 16
        $urlParams = $this->defaultUrlParams;
1060
1061 16
        if (!empty($conditions)) {
1062 8
            if (is_array($conditions)) {
1063 7
                $this->extractUrlParams($conditions, $urlParams);
1064 7
                $conditions = $this->flexiUrl($conditions);
1065 7
            }
1066
1067 8
            if (strlen($conditions) && ($conditions[0] != '/')) {
1068 1
                $conditions = '('.self::urlEncode($conditions).')';
1069 1
            }
1070 8
        }
1071
1072 16
        if (strlen($suffix)) {
1073 4
            if (preg_match('/^http/', $suffix) || ($suffix[0] == '/') || is_numeric($suffix)) {
1074 4
                $finalUrl = $suffix;
1075 4
            } else {
1076
                if (preg_match('/^(code|ext):(.*)/', $suffix, $matches)) {
1077
                    $finalUrl = $matches[1].':'.rawurlencode($matches[2]);
1078
                }
1079
            }
1080 4
        }
1081
1082 16
        $finalUrl .= $conditions;
1083
1084 16
        if (count($urlParams)) {
1085 16
            if (strstr($finalUrl, '?')) {
1086
                $finalUrl .= '&';
1087
            } else {
1088 16
                $finalUrl .= '?';
1089
            }
1090 16
            $finalUrl .= http_build_query($urlParams, null, '&',
1091 16
                PHP_QUERY_RFC3986);
1092 16
        }
1093
1094 16
        $transactions = $this->performRequest($finalUrl, 'GET');
1095
1096 16
        $responseEvidence = $this->getResponseEvidence();
1097 16
        if (is_array($transactions) && array_key_exists($responseEvidence,
1098 16
                $transactions)) {
1099 10
            $result = $transactions[$responseEvidence];
1100 10
            if ((count($result) == 1) && (count(current($result)) == 0 )) {
1101 6
                $result = null; // Response is empty Array
1102 6
            }
1103 10
        } else {
1104 6
            $result = $transactions;
1105
        }
1106
1107 16
        return $result;
1108
    }
1109
1110
    /**
1111
     * Načte záznam z FlexiBee a uloží v sobě jeho data
1112
     * Read FlexiBee record and store it inside od object
1113
     *
1114
     * @param int $id ID or conditions
1115
     *
1116
     * @return int počet načtených položek
1117
     */
1118 23
    public function loadFromFlexiBee($id = null)
1119
    {
1120 23
        $data = [];
1121 23
        if (is_null($id)) {
1122 23
            $id = $this->getMyKey();
1123 23
        }
1124 23
        if (is_array($id)) {
1125
            $id = rawurlencode('('.self::flexiUrl($id).')');
1126
        }
1127
1128 23
        if (preg_match('/^code/', $id)) {
1129
            $id = self::code(rawurlencode(self::uncode($id)));
1130
        }
1131
1132 23
        $flexidata    = $this->getFlexiData($this->getEvidenceUrl().'/'.$id);
1133 23
        $this->apiURL = $this->curlInfo['url'];
1134 23
        if (is_array($flexidata) && (count($flexidata) == 1)) {
1135 9
            $data = current($flexidata);
1136 9
        }
1137 23
        return $this->takeData($data);
1138
    }
1139
1140
    /**
1141
     * Převede data do Json formátu pro FlexiBee.
1142
     * Convert data to FlexiBee like Json format
1143
     *
1144
     * @param array $data
1145
     *
1146
     * @return string
1147
     */
1148 23
    public function jsonizeData($data)
1149
    {
1150
        $dataToJsonize = [
1151 23
            $this->nameSpace => [
1152 23
                '@version' => $this->protoVersion,
1153 23
                $this->evidence => $this->objectToID($data),
1154 23
            ],
1155 23
        ];
1156
1157 23 View Code Duplication
        if (!is_null($this->action)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1158 15
            $dataToJsonize[$this->nameSpace][$this->evidence.'@action'] = $this->action;
1159 15
            $this->action                                               = null;
1160 15
        }
1161
1162 23 View Code Duplication
        if (!is_null($this->filter)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1163
            $dataToJsonize[$this->nameSpace][$this->evidence.'@filter'] = $this->filter;
1164
        }
1165
1166 23
        return json_encode($dataToJsonize);
1167
    }
1168
1169
    /**
1170
     * Test if given record ID exists in FlexiBee.
1171
     *
1172
     * @param boolean $identifer presence state
1173
     */
1174 17
    public function idExists($identifer = null)
1175
    {
1176 17
        if (is_null($identifer)) {
1177 10
            $identifer = $this->getMyKey();
1178 10
        }
1179 17
        $ignorestate = $this->ignore404();
1180 17
        $this->ignore404(true);
1181 17
        $this->getFlexiData(null,
1182
            [
1183 17
                'detail' => 'custom:'.$this->getmyKeyColumn(),
1184 17
                $this->getmyKeyColumn() => $identifer
1185 17
        ]);
1186 17
        $this->ignore404($ignorestate);
1187 17
        return $this->lastResponseCode == 200;
1188
    }
1189
1190
    /**
1191
     * Test if given record exists in FlexiBee.
1192
     *
1193
     * @param array $data
1194
     * @return boolean Record presence status
1195
     */
1196 15
    public function recordExists($data = [])
1197
    {
1198
1199 15
        if (empty($data)) {
1200 10
            $data = $this->getData();
1201 10
        }
1202 15
        $ignorestate = $this->ignore404();
1203 15
        $this->ignore404(true);
1204 15
        $res         = $this->getColumnsFromFlexibee([$this->myKeyColumn],
1205 15
            [self::flexiUrl($data)]);
1206
1207 15
        if (!count($res) || (isset($res['success']) && ($res['success'] == 'false'))
1208 15
            || !count($res[0])) {
1209 15
            $found = false;
1210 15
        } else {
1211 10
            $found = true;
1212
        }
1213 15
        $this->ignore404($ignorestate);
1214 15
        return $found;
1215
    }
1216
1217
    /**
1218
     * Vrací z FlexiBee sloupečky podle podmínek.
1219
     *
1220
     * @param array|int|string $conditions pole podmínek nebo ID záznamu
1221
     * @param string           $indexBy    klice vysledku naplnit hodnotou ze
1222
     *                                     sloupečku
1223
     * @return array
1224
     */
1225
    public function getAllFromFlexibee($conditions = null, $indexBy = null)
1226
    {
1227
        if (is_int($conditions)) {
1228
            $conditions = [$this->getmyKeyColumn() => $conditions];
1229
        }
1230
1231
        $flexiData = $this->getFlexiData('', $conditions);
1232
1233
        if (!is_null($indexBy)) {
1234
            $flexiData = $this->reindexArrayBy($flexiData);
1235
        }
1236
1237
        return $flexiData;
1238
    }
1239
1240
    /**
1241
     * Vrací z FlexiBee sloupečky podle podmínek.
1242
     *
1243
     * @param string[] $columnsList seznam položek
1244
     * @param array    $conditions  pole podmínek nebo ID záznamu
1245
     * @param string   $indexBy     Sloupeček podle kterého indexovat záznamy
1246
     *
1247
     * @return array
1248
     */
1249 15
    public function getColumnsFromFlexibee($columnsList, $conditions = [],
1250
                                           $indexBy = null)
1251
    {
1252 15
        $detail = 'full';
1253 15
        switch (gettype($columnsList)) {
1254 15
            case 'integer': //Record ID
0 ignored issues
show
Coding Style introduced by
There must be a comment when fall-through is intentional in a non-empty case body
Loading history...
1255
                $conditions = [$this->getmyKeyColumn() => $conditions];
1256 15
            case 'array': //Few Conditions
0 ignored issues
show
Coding Style introduced by
There must be a comment when fall-through is intentional in a non-empty case body
Loading history...
1257 15
                if (!is_null($indexBy) && !array_key_exists($indexBy,
1258 15
                        $columnsList)) {
1259 15
                    $columnsList[] = $indexBy;
1260 15
                }
1261 15
                $columns = implode(',', array_unique($columnsList));
1262 15
                $detail  = 'custom:'.$columns;
1263 15
            default:
1264
                switch ($columnsList) {
1265 15
                    case 'id':
1266
                        $detail = 'id';
1267
                        break;
1268 15
                    case 'summary':
1269
                        $detail = 'summary';
1270
                        break;
1271 15
                    default:
1272 15
                        break;
1273 15
                }
1274 15
                break;
1275 15
        }
1276
1277 15
        $conditions['detail'] = $detail;
1278
1279 15
        $flexiData = $this->getFlexiData(null, $conditions);
1280
1281 15
        if (!is_null($indexBy) && count($flexiData) && count(current($flexiData))) {
1282 9
            $flexiData = $this->reindexArrayBy($flexiData, $indexBy);
1283 9
        }
1284
1285 15
        return $flexiData;
1286
    }
1287
1288
    /**
1289
     * Vrací kód záznamu.
1290
     * Obtain record CODE
1291
     *
1292
     * @param mixed $data
1293
     *
1294
     * @return string
1295
     */
1296 23
    public function getKod($data = null, $unique = true)
1297
    {
1298 23
        $kod = null;
1299
1300 23
        if (is_null($data)) {
1301 23
            $data = $this->getData();
1302 23
        }
1303
1304 23
        if (is_string($data)) {
1305 23
            $data = [$this->nameColumn => $data];
1306 23
        }
1307
1308 23
        if (isset($data['kod'])) {
1309 23
            $kod = $data['kod'];
1310 23
        } else {
1311 23
            if (isset($data[$this->nameColumn])) {
1312 23
                $kod = preg_replace('/[^a-zA-Z0-9]/', '',
1313 23
                    \Ease\Sand::rip($data[$this->nameColumn]));
1314 23
            } else {
1315 23
                if (isset($data[$this->myKeyColumn])) {
1316 23
                    $kod = \Ease\Sand::rip($data[$this->myKeyColumn]);
1317 23
                }
1318
            }
1319
        }
1320
1321 23
        if (!strlen($kod)) {
1322 23
            $kod = 'NOTSET';
1323 23
        }
1324
1325 23
        if (strlen($kod) > 18) {
1326 23
            $kodfinal = strtoupper(substr($kod, 0, 18));
1327 23
        } else {
1328 23
            $kodfinal = strtoupper($kod);
1329
        }
1330
1331 23
        if ($unique) {
1332 23
            $counter = 0;
1333 23
            if (count($this->codes)) {
1334 23
                foreach ($this->codes as $codesearch => $keystring) {
1335 23
                    if (strstr($codesearch, $kodfinal)) {
1336 23
                        ++$counter;
1337 23
                    }
1338 23
                }
1339 23
            }
1340 23
            if ($counter) {
1341 23
                $kodfinal = $kodfinal.$counter;
1342 23
            }
1343
1344 23
            $this->codes[$kodfinal] = $kod;
1345 23
        }
1346
1347 23
        return self::code($kodfinal);
1348
    }
1349
1350
    /**
1351
     * Write Operation Result.
1352
     *
1353
     * @param array  $resultData
1354
     * @param string $url        URL
1355
     * @return boolean Log save success
1356
     */
1357 23
    public function logResult($resultData = null, $url = null)
1358
    {
1359 23
        $logResult = false;
1360 23
        if (isset($resultData['success']) && ($resultData['success'] == 'false')) {
1361 23
            if (isset($resultData['message'])) {
1362
                $this->addStatusMessage($resultData['message'], 'warning');
1363
            }
1364 23
            $this->addStatusMessage('Error '.$this->lastResponseCode.': '.urldecode($url),
1365 23
                'warning');
1366 23
            unset($url);
1367 23
        }
1368 23
        if (is_null($resultData)) {
1369
            $resultData = $this->lastResult;
1370
        }
1371 23
        if (isset($url)) {
1372 23
            $this->logger->addStatusMessage($this->lastResponseCode.':'.urldecode($url));
1373 23
        }
1374
1375 23
        if (isset($resultData['results'])) {
1376 23
            if ($resultData['success'] == 'false') {
1377 23
                $status = 'error';
1378 23
            } else {
1379 23
                $status = 'success';
1380
            }
1381 23
            foreach ($resultData['results'] as $result) {
1382 23
                if (isset($result['request-id'])) {
1383 23
                    $rid = $result['request-id'];
1384 23
                } else {
1385 23
                    $rid = '';
1386
                }
1387 23
                if (isset($result['errors'])) {
1388 23
                    foreach ($result['errors'] as $error) {
1389 23
                        $message = $error['message'];
1390 23
                        if (isset($error['for'])) {
1391
                            $message .= ' for: '.$error['for'];
1392
                        }
1393 23
                        if (isset($error['value'])) {
1394
                            $message .= ' value:'.$error['value'];
1395
                        }
1396 23
                        if (isset($error['code'])) {
1397
                            $message .= ' code:'.$error['code'];
1398
                        }
1399 23
                        $this->addStatusMessage($rid.': '.$message, $status);
1400 23
                    }
1401 23
                }
1402 23
            }
1403 23
        }
1404 23
        return $logResult;
1405
    }
1406
1407
    /**
1408
     * Save RAW Curl Request & Response to files in Temp directory
1409
     */
1410
    public function saveDebugFiles()
1411
    {
1412
        $tmpdir   = sys_get_temp_dir();
1413
        $fname    = $this->evidence.'-'.$this->curlInfo['when'].'.'.$this->format;
1414
        $reqname  = $tmpdir.'/request-'.$fname;
1415
        $respname = $tmpdir.'/response-'.$fname;
1416
        file_put_contents($reqname, $this->postFields);
1417
        file_put_contents($respname, $this->lastCurlResponse);
1418
    }
1419
1420
    /**
1421
     * Připraví data pro odeslání do FlexiBee
1422
     *
1423
     * @param string $data
1424
     */
1425
    public function setPostFields($data)
1426
    {
1427
        $this->postFields = $data;
1428
    }
1429
1430
    /**
1431
     * Generuje fragment url pro filtrování.
1432
     *
1433
     * @see https://www.flexibee.eu/api/dokumentace/ref/filters
1434
     *
1435
     * @param array  $data
1436
     * @param string $joiner default and/or
1437
     * @param string $defop  default operator
1438
     *
1439
     * @return string
1440
     */
1441 23
    public static function flexiUrl(array $data, $joiner = 'and', $defop = 'eq')
1442
    {
1443 23
        $parts = [];
1444
1445 23
        foreach ($data as $column => $value) {
1446 23
            if (!is_numeric($column)) {
1447 23
                if (is_integer($data[$column]) || is_float($data[$column])) {
1448 23
                    $parts[$column] = $column.' eq \''.$data[$column].'\'';
1449 23
                } elseif (is_bool($data[$column])) {
1450 23
                    $parts[$column] = $data[$column] ? $column.' eq true' : $column.' eq false';
1451 23
                } elseif (is_null($data[$column])) {
1452 23
                    $parts[$column] = $column." is null";
1453 23
                } else {
1454
                    switch ($value) {
1455 23
                        case '!null':
1456 23
                            $parts[$column] = $column." is not null";
1457 23
                            break;
1458 23
                        case 'is empty':
1459 23
                        case 'is not empty':
1460
                            $parts[$column] = $column.' '.$value;
1461
                            break;
1462 23
                        default:
1463 23
                            if ($column == 'stitky') {
1464
                                $parts[$column] = $column."='".self::code($data[$column])."'";
1465
                            } else {
1466 23
                                $parts[$column] = $column." $defop '".$data[$column]."'";
1467
                            }
1468 23
                            break;
1469 23
                    }
1470
                }
1471 23
            } else {
1472
                $parts[] = $value;
1473
            }
1474 23
        }
1475 23
        return implode(' '.$joiner.' ', $parts);
1476
    }
1477
1478
    /**
1479
     * Obtain record/object identificator code: or id:
1480
     * Vrací identifikátor objektu code: nebo id:
1481
     *
1482
     * @link https://demo.flexibee.eu/devdoc/identifiers Identifikátory záznamů
1483
     *
1484
     * @return string|int indentifikátor záznamu reprezentovaného objektem
1485
     */
1486 65
    public function getRecordID()
1487
    {
1488 65
        $myCode = $this->getDataValue('kod');
1489 65
        if ($myCode) {
1490
            $id = self::code($myCode);
1491
        } else {
1492 65
            $id = $this->getDataValue('id');
1493 65
            if (($this->debug === true) && is_null($id)) {
1494
                $this->addToLog('Object Data does not contain code: or id: cannot match with statement!',
1495
                    'warning');
1496
            }
1497
        }
1498 65
        return is_numeric($id) ? intval($id) : strval($id);
1499
    }
1500
1501
    /**
1502
     * Obtain record/object identificator code: or id:
1503
     * Vrací identifikátor objektu code: nebo id:
1504
     *
1505
     * @link https://demo.flexibee.eu/devdoc/identifiers Identifikátory záznamů
1506
     * @return string indentifikátor záznamu reprezentovaného objektem
1507
     */
1508 71
    public function __toString()
1509
    {
1510 71
        return strval($this->getRecordID());
1511
    }
1512
1513
    /**
1514
     * Gives you FlexiPeeHP class name for Given Evidence
1515
     *
1516
     * @param string $evidence
1517
     * @return string Class name
1518
     */
1519 23
    public static function evidenceToClassName($evidence)
1520
    {
1521 23
        return str_replace(' ', '', ucwords(str_replace('-', ' ', $evidence)));
1522
    }
1523
1524
    /**
1525
     * Obtain ID of first record in evidence
1526
     *
1527
     * @return string|null id or null if no records
1528
     */
1529 15
    public function getFirstRecordID()
1530
    {
1531 15
        $firstID    = null;
1532 15
        $keyColumn  = $this->getmyKeyColumn();
1533 15
        $firstIdRaw = $this->getColumnsFromFlexibee([$keyColumn],
1534 15
            ['limit' => 1, 'order' => $keyColumn], $keyColumn);
1535 15
        if (count($firstIdRaw)) {
1536 9
            $firstID = current($firstIdRaw)[$keyColumn];
1537 9
        }
1538 15
        return is_numeric($firstID) ? intval($firstID) : $firstID;
1539
    }
1540
1541
    /**
1542
     * Vrací hodnotu daného externího ID
1543
     *
1544
     * @param string $want Which ? If empty,you obtain the first one.
1545
     * @return string
1546
     */
1547 23
    public function getExternalID($want = null)
1548
    {
1549 23
        $extid = null;
1550 23
        $ids   = $this->getDataValue('external-ids');
1551 23
        if (is_null($want)) {
1552 23
            if (count($ids)) {
1553 23
                $extid = current($ids);
1554 23
            }
1555 23
        } else {
1556 23
            if (!is_null($ids) && is_array($ids)) {
1557 23
                foreach ($ids as $id) {
1558 23
                    if (strstr($id, 'ext:'.$want)) {
1559 23
                        $extid = str_replace('ext:'.$want.':', '', $id);
1560 23
                    }
1561 23
                }
1562 23
            }
1563
        }
1564 23
        return $extid;
1565
    }
1566
1567
    /**
1568
     * Obtain actual GlobalVersion
1569
     * Vrací aktuální globální verzi změn
1570
     *
1571
     * @link https://www.flexibee.eu/api/dokumentace/ref/changes-api#globalVersion Globální Verze
1572
     * @return type
1573
     */
1574 22
    public function getGlobalVersion()
1575
    {
1576 22
        $this->getFlexiData(null, ['add-global-version' => 'true', 'limit' => 1]);
1577
1578 22
        return $this->globalVersion;
1579
    }
1580
1581
    /**
1582
     * Obtain content type of last response
1583
     *
1584
     * @return string
1585
     */
1586 23
    public function getResponseFormat()
1587
    {
1588 23
        if (isset($this->curlInfo['content_type'])) {
1589 22
            $responseFormat = $this->curlInfo['content_type'];
1590 22
        } else {
1591 1
            $responseFormat = null;
1592
        }
1593 23
        return $responseFormat;
1594
    }
1595
1596
    /**
1597
     * Return the same response format for one and multiplete results
1598
     *
1599
     * @param array $responseBody
1600
     * @return array
1601
     */
1602 22
    public function unifyResponseFormat($responseBody)
1603
    {
1604 22
        if (!is_array($responseBody) || array_key_exists('message',
1605 22
                $responseBody)) { //Unifi response format
1606 22
            $response = $responseBody;
1607 22
        } else {
1608 22
            $evidence = $this->getResponseEvidence();
1609 22
            if (array_key_exists($evidence, $responseBody)) {
1610 22
                $response        = [];
1611 22
                $evidenceContent = $responseBody[$evidence];
1612 22
                if (array_key_exists(0, $evidenceContent)) {
1613 22
                    $response[$evidence] = $evidenceContent; //Multiplete Results
1614 22
                } else {
1615 22
                    $response[$evidence][0] = $evidenceContent; //One result
1616
                }
1617 22
            } else {
1618
                if (isset($responseBody['priloha'])) {
1619
                    $response = $responseBody['priloha'];
1620
                } else {
1621
                    if (array_key_exists('results', $responseBody)) {
1622
                        $response = $responseBody['results'];
1623
                    } else {
1624
                        $response = $responseBody;
1625
                    }
1626
                }
1627
            }
1628
        }
1629 22
        return $response;
1630
    }
1631
1632
    /**
1633
     * Obtain structure for current (or given) evidence
1634
     *
1635
     * @param string $evidence
1636
     * @return array Evidence structure
1637
     */
1638 23
    public function getColumnsInfo($evidence = null)
1639
    {
1640 23
        $columnsInfo = null;
1641 23
        $infoSource  = self::$infoDir.'/Properties.'.(empty($evidence) ? $this->getEvidence()
1642 23
                : $evidence).'.json';
1643 23
        if (file_exists($infoSource)) {
1644 16
            $columnsInfo = json_decode(file_get_contents($infoSource), true);
1645 16
        }
1646 23
        return $columnsInfo;
1647
    }
1648
1649
    /**
1650
     * Obtain actions for current (or given) evidence
1651
     *
1652
     * @param string $evidence
1653
     * @return array Evidence structure
1654
     */
1655 23
    public function getActionsInfo($evidence = null)
1656
    {
1657 23
        $actionsInfo = null;
1658 23
        if (is_null($evidence)) {
1659 23
            $evidence = $this->getEvidence();
1660 23
        }
1661 23
        $propsName = lcfirst(FlexiBeeRO::evidenceToClassName($evidence));
1662 23
        if (isset(\FlexiPeeHP\Actions::$$propsName)) {
1663 23
            $actionsInfo = Actions::$$propsName;
1664 23
        }
1665 23
        return $actionsInfo;
1666
    }
1667
1668
    /**
1669
     * Obtain relations for current (or given) evidence
1670
     *
1671
     * @param string $evidence
1672
     * @return array Evidence structure
1673
     */
1674 23
    public function getRelationsInfo($evidence = null)
1675
    {
1676 23
        $relationsInfo = null;
1677 23
        if (is_null($evidence)) {
1678 23
            $evidence = $this->getEvidence();
1679 23
        }
1680 23
        $propsName = lcfirst(FlexiBeeRO::evidenceToClassName($evidence));
1681 23
        if (isset(\FlexiPeeHP\Relations::$$propsName)) {
1682 13
            $relationsInfo = Relations::$$propsName;
1683 13
        }
1684 23
        return $relationsInfo;
1685
    }
1686
1687
    /**
1688
     * Obtain info for current (or given) evidence
1689
     *
1690
     * @param string $evidence
1691
     * @return array Evidence info
1692
     */
1693 23 View Code Duplication
    public function getEvidenceInfo($evidence = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1694
    {
1695 23
        $evidencesInfo = null;
1696 23
        if (is_null($evidence)) {
1697 23
            $evidence = $this->getEvidence();
1698 23
        }
1699 23
        if (isset(EvidenceList::$evidences[$evidence])) {
1700 16
            $evidencesInfo = EvidenceList::$evidences[$evidence];
1701 16
        }
1702 23
        return $evidencesInfo;
1703
    }
1704
1705
    /**
1706
     * Obtain name for current (or given) evidence path
1707
     *
1708
     * @param string $evidence Evidence Path
1709
     * @return array Evidence info
1710
     */
1711 23 View Code Duplication
    public function getEvidenceName($evidence = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1712
    {
1713 23
        $evidenceName = null;
1714 23
        if (is_null($evidence)) {
1715 23
            $evidence = $this->getEvidence();
1716 23
        }
1717 23
        if (isset(EvidenceList::$name[$evidence])) {
1718 16
            $evidenceName = EvidenceList::$name[$evidence];
1719 16
        }
1720 23
        return $evidenceName;
1721
    }
1722
1723
    /**
1724
     * Save current object to file
1725
     *
1726
     * @param string $destfile path to file
1727
     */
1728 23
    public function saveResponseToFile($destfile)
1729
    {
1730 23
        if (strlen($this->lastCurlResponse)) {
1731 1
            $this->doCurlRequest($this->apiURL, 'GET', $this->format);
1732 1
        }
1733 23
        file_put_contents($destfile, $this->lastCurlResponse);
1734 23
    }
1735
1736
    /**
1737
     * Obtain established relations listing
1738
     *
1739
     * @return array Null or Relations
1740
     */
1741 20
    public function getVazby($id = null)
1742
    {
1743 20
        if (is_null($id)) {
1744 20
            $id = $this->getRecordID();
1745 20
        }
1746 20
        if (!empty($id)) {
1747
            $vazbyRaw = $this->getColumnsFromFlexibee(['vazby'],
1748
                ['relations' => 'vazby', 'id' => $id]);
1749
            $vazby    = array_key_exists('vazby', $vazbyRaw[0]) ? $vazbyRaw[0]['vazby']
1750
                    : null;
1751
        } else {
1752 20
            throw new \Exception(_('ID requied to get record relations '));
1753
        }
1754
        return $vazby;
1755
    }
1756
1757
    /**
1758
     * Gives You URL for Current Record in FlexiBee web interface
1759
     *
1760
     * @return string url
1761
     */
1762
    public function getFlexiBeeURL()
1763
    {
1764
        $parsed_url = parse_url(str_replace('.'.$this->format, '', $this->apiURL));
1765
        $scheme     = isset($parsed_url['scheme']) ? $parsed_url['scheme'].'://'
1766
                : '';
1767
        $host       = isset($parsed_url['host']) ? $parsed_url['host'] : '';
1768
        $port       = isset($parsed_url['port']) ? ':'.$parsed_url['port'] : '';
1769
        $user       = isset($parsed_url['user']) ? $parsed_url['user'] : '';
1770
        $pass       = isset($parsed_url['pass']) ? ':'.$parsed_url['pass'] : '';
1771
        $pass       = ($user || $pass) ? "$pass@" : '';
1772
        $path       = isset($parsed_url['path']) ? $parsed_url['path'] : '';
1773
        return $scheme.$user.$pass.$host.$port.$path;
1774
    }
1775
1776
    /**
1777
     * Set Record Key
1778
     *
1779
     * @param int|string $myKeyValue
1780
     * @return boolean
1781
     */
1782
    public function setMyKey($myKeyValue)
1783
    {
1784
        $res = parent::setMyKey($myKeyValue);
1785
        $this->updateApiURL();
1786
        return $res;
1787
    }
1788
1789
    /**
1790
     * Set or get ignore not found pages flag
1791
     *
1792
     * @param boolean $ignore set flag to
1793
     *
1794
     * @return boolean get flag state
1795
     */
1796
    public function ignore404($ignore = null)
1797
    {
1798
        if (!is_null($ignore)) {
1799
            $this->ignoreNotFound = $ignore;
1800
        }
1801
        return $this->ignoreNotFound;
1802
    }
1803
1804
    /**
1805
     * Send Document by mail
1806
     *
1807
     * @url https://www.flexibee.eu/api/dokumentace/ref/odesilani-mailem/
1808
     *
1809
     * @param string $to
1810
     * @param string $subject
1811
     * @param string $body Email Text
1812
     *
1813
     * @return int http response code
1814
     */
1815
    public function sendByMail($to, $subject, $body, $cc = null)
1816
    {
1817
        $this->setPostFields($body);
1818
        $result = $this->doCurlRequest(urlencode($this->getRecordID()).'/odeslani-dokladu?to='.$to.'&subject='.urlencode($subject).'&cc='.$cc
1819
            , 'PUT', 'xml');
1820
        return $result == 200;
1821
    }
1822
1823
    /**
1824
     * Send all unsent Invoices by mail
1825
     *
1826
     * @url https://www.flexibee.eu/api/dokumentace/ref/odesilani-mailem/
1827
     * @return int http response code
1828
     */
1829
    public function sendUnsent()
1830
    {
1831
        return $this->doCurlRequest('automaticky-odeslat-neodeslane', 'PUT',
1832
                'xml');
1833
    }
1834
1835
    /**
1836
     * FlexiBee date to PHP DateTime conversion
1837
     *
1838
     * @param string $flexidate 2017-05-26+02:00
1839
     *
1840
     * @return \DateTime | false
1841
     */
1842 23
    public static function flexiDateToDateTime($flexidate)
1843
    {
1844 23
        return \DateTime::createFromFormat('Y-m-dO', $flexidate)->setTime(0, 0);
1845
    }
1846
1847
    /**
1848
     * FlexiBee dateTime to PHP DateTime conversion
1849
     *
1850
     * @param string $flexidatetime 2017-09-26T10:00:53.755+02:00
1851
     *
1852
     * @return \DateTime | false
1853
     */
1854 23
    public static function flexiDateTimeToDateTime($flexidatetime)
1855
    {
1856 23
        return \DateTime::createFromFormat('Y-m-j\TH:i:s.u+P', $flexidatetime);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The expression \DateTime::createFromFor....u+P', $flexidatetime); of type DateTime|false adds false to the return on line 1856 which is incompatible with the return type documented by FlexiPeeHP\FlexiBeeRO::flexiDateTimeToDateTime of type DateTime. It seems like you forgot to handle an error condition.
Loading history...
1857
    }
1858
1859
    /**
1860
     * Získá dokument v daném formátu
1861
     * Obtain document in given format
1862
     *
1863
     * @param string $format  pdf/csv/xml/json/ ...
1864
     * @param string $reportName Template used to generate PDF
0 ignored issues
show
Bug introduced by
There is no parameter named $reportName. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
1865
     *
1866
     * @return string|null filename downloaded or none
1867
     */
1868
    public function getInFormat($format)
1869
    {
1870
        $response = null;
1871
        if ($this->setFormat($format)) {
1872
            $urlParams = [];
1873
            if (!empty($reportName)) {
0 ignored issues
show
Bug introduced by
The variable $reportName seems to never exist, and therefore empty should always return true. Did you maybe rename this variable?

This check looks for calls to isset(...) or empty() on variables that are yet undefined. These calls will always produce the same result and can be removed.

This is most likely caused by the renaming of a variable or the removal of a function/method parameter.

Loading history...
1874
                $urlParams['report-name'] = $reportName;
1875
            }
1876
            if ($format == 'html') {
1877
                $urlParams['inDesktopApp'] = 'true';
1878
            }
1879
            if (($this->doCurlRequest($this->addUrlParams($this->apiURL,
1880
                        $urlParams), 'GET') == 200)) {
1881
                $response = $this->lastCurlResponse;
1882
            }
1883
        }
1884
        return $response;
1885
    }
1886
1887
    /**
1888
     * Uloží dokument v daném formátu do složky v systému souborů
1889
     * Save document in given format to directory in filesystem
1890
     *
1891
     * @param string $format  pdf/csv/xml/json/ ...
1892
     * @param string $destDir where to put file (prefix)
1893
     * @param string $reportName Template used to generate PDF
1894
     *
1895
     * @return string|null filename downloaded or none
1896
     */
1897
    public function downloadInFormat($format, $destDir = './',
1898
                                     $reportName = null)
1899
    {
1900
        $fileOnDisk   = null;
1901
        $formatBackup = $this->format;
1902
        if ($this->setFormat($format)) {
1903
            $downloadTo = $destDir.$this->getEvidence().'_'.$this->getMyKey().'.'.$format;
1904
            if (($this->doCurlRequest(empty($reportName) ? $this->apiURL : $this->addUrlParams($this->apiURL,
1905
                            ['report-name' => $reportName]), 'GET') == 200) && (file_put_contents($downloadTo,
1906
                    $this->lastCurlResponse) !== false)) {
1907
                $fileOnDisk = $downloadTo;
1908
            }
1909
            $this->setFormat($formatBackup);
1910
        }
1911
        return $fileOnDisk;
1912
    }
1913
1914
    /**
1915
     * Compile and send Report about Error500 to FlexiBee developers
1916
     * If FlexiBee is running on localost try also include java backtrace
1917
     *
1918
     * @param array $errorResponse result of parseError();
1919
     */
1920
    public function error500Reporter($errorResponse)
1921
    {
1922
        $ur = str_replace('/c/'.$this->company, '',
1923
            str_replace($this->url, '', $this->curlInfo['url']));
1924
        if (!array_key_exists($ur, $this->reports)) {
1925
            $tmpdir   = sys_get_temp_dir();
1926
            $myTime   = $this->curlInfo['when'];
1927
            $curlname = $tmpdir.'/curl-'.$this->evidence.'-'.$myTime.'.json';
1928
            file_put_contents($curlname,
1929
                json_encode($this->curlInfo, JSON_PRETTY_PRINT));
1930
1931
            $report = new \Ease\Mailer($this->reportRecipient,
1932
                'Error report 500 - '.$ur);
1933
1934
            $d     = dir($tmpdir);
1935
            while (false !== ($entry = $d->read())) {
1936
                if (strstr($entry, $myTime)) {
1937
                    $ext  = pathinfo($tmpdir.'/'.$entry, PATHINFO_EXTENSION);
1938
                    $mime = Formats::suffixToContentType($ext);
1939
                    $report->addFile($tmpdir.'/'.$entry,
1940
                        empty($mime) ? 'text/plain' : $mime);
1941
                }
1942
            }
1943
            $d->close();
1944
1945
            if ((strstr($this->url, '://localhost') || strstr($this->url,
1946
                    '://127.')) && file_exists('/var/log/flexibee.log')) {
1947
1948
                $fl = fopen("/var/log/flexibee.log", "r");
1949
                if ($fl) {
1950
                    $tracelog = [];
1951
                    for ($x_pos = 0, $ln = 0, $output = array(); fseek($fl,
1952
                            $x_pos, SEEK_END) !== -1; $x_pos--) {
1953
                        $char = fgetc($fl);
1954
                        if ($char === "\n") {
1955
                            $tracelog[] = $output[$ln];
1956
                            if (strstr($output[$ln], $errorResponse['message'])) {
1957
                                break;
1958
                            }
1959
                            $ln++;
1960
                            continue;
1961
                        }
1962
                        $output[$ln] = $char.((array_key_exists($ln, $output)) ? $output[$ln]
1963
                                : '');
1964
                    }
1965
1966
                    $trace     = implode("\n", array_reverse($tracelog));
1967
                    $tracefile = $tmpdir.'/trace-'.$this->evidence.'-'.$myTime.'.log';
1968
                    file_put_contents($tracefile, $trace);
1969
                    $report->addItem("\n\n".$trace);
1970
                    fclose($fl);
1971
                }
1972
            } else {
1973
                $report->addItem($errorResponse['message']);
1974
            }
1975
1976
            $licenseInfo = $this->performRequest($this->url.'/default-license.json');
1977
1978
            $report->addItem("\n\n".json_encode($licenseInfo['license'],
1979
                    JSON_PRETTY_PRINT));
1980
1981
            if ($report->send()) {
1982
                $this->reports[$ur] = $myTime;
1983
            }
1984
        }
1985
    }
1986
1987
    /**
1988
     * Returns code:CODE
1989
     *
1990
     * @param string $code
1991
     *
1992
     * @return string
1993
     */
1994
    public static function code($code)
1995
    {
1996
        return 'code:'.self::uncode($code);
1997
    }
1998
1999
    /**
2000
     * Returns CODE without code: prefix
2001
     *
2002
     * @param string $code
2003
     *
2004
     * @return string
2005
     */
2006
    public static function uncode($code)
2007
    {
2008
        return str_replace(['code:', 'code%3A'], '', $code);
2009
    }
2010
2011
    /**
2012
     * Remove all @ items from array
2013
     *
2014
     * @param array $data original data
2015
     *
2016
     * @return array data without @ columns
2017
     */
2018
    public static function arrayCleanUP($data)
2019
    {
2020
        return array_filter(
2021
            $data,
2022
            function ($key) {
2023
            return !strchr($key, '@');
2024
        }, ARRAY_FILTER_USE_KEY);
2025
    }
2026
2027
    /**
2028
     * Add Info about used user, server and libraries
2029
     *
2030
     * @param string $additions Additional note text
2031
     */
2032 23
    function logBanner($additions = null)
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
2033
    {
2034 23
        $this->addStatusMessage('FlexiBee '.str_replace('://',
2035 23
                '://'.$this->user.'@', str_replace('.json', '', $this->apiURL)).' FlexiPeeHP v'.self::$libVersion.' (FlexiBee '.EvidenceList::$version.') EasePHP Framework v'.\Ease\Atom::$frameworkVersion.' '.$additions,
2036 23
            'debug');
2037 23
    }
2038
2039
    /**
2040
     * Reconnect After unserialization
2041
     */
2042
    public function __wakeup()
2043
    {
2044
        parent::__wakeup();
2045
        $this->curlInit();
2046
    }
2047
}
2048