Test Failed
Push — master ( 389a66...b1e2e1 )
by Vítězslav
07:10
created

FlexiBeeRO::urlEncode()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 4
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
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
     * Version of FlexiPeeHP library
20
     *
21
     * @var string
22
     */
23
    public static $libVersion = '1.6.4.2';
24
25
    /**
26
     * Základní namespace pro komunikaci s FlexiBee.
27
     * Basic namespace for communication with FlexiBee
28
     *
29
     * @var string Jmený prostor datového bloku odpovědi
30
     */
31
    public $nameSpace = 'winstrom';
32
33
    /**
34
     * URL of object data in FlexiBee
35
     * @var string url
36
     */
37
    public $apiURL = null;
38
39
    /**
40
     * Datový blok v poli odpovědi.
41
     * Data block in response field.
42
     *
43
     * @var string
44
     */
45
    public $resultField = 'results';
46
47
    /**
48
     * Verze protokolu použitého pro komunikaci.
49
     * Communication protocol version used.
50
     *
51
     * @var string Verze použitého API
52
     */
53
    public $protoVersion = '1.0';
54
55
    /**
56
     * Evidence užitá objektem.
57
     * Evidence used by object
58
     *
59
     * @link https://demo.flexibee.eu/c/demo/evidence-list Přehled evidencí
60
     * @var string
61
     */
62
    public $evidence = null;
63
64
    /**
65
     * Výchozí formát pro komunikaci.
66
     * Default communication format.
67
     *
68
     * @link https://www.flexibee.eu/api/dokumentace/ref/format-types Přehled možných formátů
69
     *
70
     * @var string json|xml|...
71
     */
72
    public $format = 'json';
73
74
    /**
75
     * formát příchozí odpovědi
76
     * response format
77
     *
78
     * @link https://www.flexibee.eu/api/dokumentace/ref/format-types Přehled možných formátů
79
     *
80
     * @var string json|xml|...
81
     */
82
    public $responseFormat = 'json';
83
84
    /**
85
     * Curl Handle.
86
     *
87
     * @var resource
88
     */
89
    public $curl = null;
90
91
    /**
92
     * @link https://demo.flexibee.eu/devdoc/company-identifier Identifikátor firmy
93
     * @var string
94
     */
95
    public $company = null;
96
97
    /**
98
     * Server[:port]
99
     * @var string
100
     */
101
    public $url = null;
102
103
    /**
104
     * REST API Username
105
     * @var string
106
     */
107
    public $user = null;
108
109
    /**
110
     * REST API Password
111
     * @var string
112
     */
113
    public $password = null;
114
115
    /**
116
     * @var array Pole HTTP hlaviček odesílaných s každým požadavkem
117
     */
118
    public $defaultHttpHeaders = ['User-Agent' => 'FlexiPeeHP'];
119
120
    /**
121
     * Default additional request url parameters after question mark
122
     *
123
     * @link https://www.flexibee.eu/api/dokumentace/ref/urls   Common params
124
     * @link https://www.flexibee.eu/api/dokumentace/ref/paging Paging params
125
     * @var array
126
     */
127
    public $defaultUrlParams = ['limit' => 0];
128
129
    /**
130
     * Identifikační řetězec.
131
     *
132
     * @var string
133
     */
134
    public $init = null;
135
136
    /**
137
     * Sloupeček s názvem.
138
     *
139
     * @var string
140
     */
141
    public $nameColumn = 'nazev';
142
143
    /**
144
     * Sloupeček obsahující datum vložení záznamu do shopu.
145
     *
146
     * @var string
147
     */
148
    public $myCreateColumn = 'false';
149
150
    /**
151
     * Slopecek obsahujici datum poslení modifikace záznamu do shopu.
152
     *
153
     * @var string
154
     */
155
    public $myLastModifiedColumn = 'lastUpdate';
156
157
    /**
158
     * Klíčový idendifikátor záznamu.
159
     *
160
     * @var string
161
     */
162
    public $fbKeyColumn = 'id';
163
164
    /**
165
     * Informace o posledním HTTP requestu.
166
     *
167
     * @var *
168
     */
169
    public $curlInfo;
170
171
    /**
172
     * Informace o poslední HTTP chybě.
173
     *
174
     * @var string
175
     */
176
    public $lastCurlError = null;
177
178
    /**
179
     * Used codes storage.
180
     *
181
     * @var array
182
     */
183
    public $codes = null;
184
185
    /**
186
     * Last Inserted ID.
187
     *
188
     * @var int
189
     */
190
    public $lastInsertedID = null;
191
192
    /**
193
     * Default Line Prefix.
194
     *
195
     * @var string
196
     */
197
    public $prefix = '/c/';
198
199
    /**
200
     * Raw Content of last curl response
201
     *
202
     * @var string
203
     */
204
    public $lastCurlResponse;
205
206
    /**
207
     * HTTP Response code of last request
208
     *
209
     * @var int
210
     */
211
    public $lastResponseCode = null;
212
213
    /**
214
     * Body data  for next curl POST operation
215
     *
216
     * @var string
217
     */
218
    protected $postFields = null;
219
220
    /**
221
     * Last operation result data or message(s)
222
     *
223
     * @var array
224
     */
225
    public $lastResult = null;
226
227
    /**
228
     * Nuber from  @rowCount
229
     * @var int
230
     */
231
    public $rowCount = null;
232
233
    /**
234
     * @link https://www.flexibee.eu/api/dokumentace/ref/zamykani-odemykani/
235
     * @var string filter query
236
     */
237
    public $filter;
238
239
    /**
240
     * @link https://demo.flexibee.eu/devdoc/actions Provádění akcí
241
     * @var string
242
     */
243
    protected $action;
244
245
    /**
246
     * Pole akcí které podporuje ta která evidence
247
     * @link https://demo.flexibee.eu/c/demo/faktura-vydana/actions.json Např. Akce faktury
248
     * @var array
249
     */
250
    public $actionsAvailable = null;
251
252
    /**
253
     * Parmetry pro URL
254
     * @link https://www.flexibee.eu/api/dokumentace/ref/urls/ Všechny podporované parametry
255
     * @var array
256
     */
257
    public $urlParams = [
258
        'idUcetniObdobi',
259
        'dry-run',
260
        'fail-on-warning',
261
        'report-name',
262
        'report-lang',
263
        'report-sign',
264
        'detail', //See: https://www.flexibee.eu/api/dokumentace/ref/detail-levels
265
        'mode',
266
        'limit',
267
        'start',
268
        'order',
269
        'sort',
270
        'add-row-count',
271
        'relations',
272
        'includes',
273
        'use-ext-id',
274
        'use-internal-id',
275
        'stitky-as-ids',
276
        'only-ext-ids',
277
        'no-ext-ids',
278
        'no-ids',
279
        'code-as-id',
280
        'no-http-errors',
281
        'export-settings',
282
        'as-gui',
283
        'code-in-response',
284
        'add-global-version',
285
        'encoding',
286
        'delimeter',
287
        'format',
288
        'auth',
289
        'skupina-stitku',
290
        'dir',
291
        'relations',
292
        'relations',
293
        'xpath', // See: https://www.flexibee.eu/api/dokumentace/ref/xpath/
294
        'dry-run', // See: https://www.flexibee.eu/api/dokumentace/ref/dry-run/
295
        'inDesktopApp' // Note: Undocumented function (html only)
296
    ];
297
298
    /**
299
     * Save 404 results to log ?
300
     * @var boolean
301
     */
302
    protected $ignoreNotFound = false;
303
304
    /**
305
     * Array of errors caused by last request
306
     * @var array
307
     */
308
    private $errors = [];
309
310
    /**
311
     * List of Error500 reports sent
312
     * @var array
313
     */
314
    private $reports = [];
315
316
    /**
317
     * Send Error500 Report to
318
     * @var string email address
319
     */
320
    public $reportRecipient = '[email protected]';
321
322
    /**
323
     * Class for read only interaction with FlexiBee.
324
     *
325
     * @param mixed $init default record id or initial data
326
     * @param array $options Connection settings override
327
     */
328 24
    public function __construct($init = null, $options = [])
329
    {
330 24
        $this->init = $init;
331
332 24
        parent::__construct();
333 24
        $this->setUp($options);
334 24
        $this->curlInit();
335 24
        if (!empty($init)) {
336 22
            $this->processInit($init);
337 22
        }
338 24
    }
339
340
    /**
341
     * SetUp Object to be ready for connect
342
     *
343
     * @param array $options Object Options (company,url,user,password,evidence,
344
     *                                       prefix,defaultUrlParams,debug)
345
     */
346 47
    public function setUp($options = [])
347
    {
348 47
        $this->setupProperty($options, 'company', 'FLEXIBEE_COMPANY');
349 47
        $this->setupProperty($options, 'url', 'FLEXIBEE_URL');
350 47
        $this->setupProperty($options, 'user', 'FLEXIBEE_LOGIN');
351 47
        $this->setupProperty($options, 'password', 'FLEXIBEE_PASSWORD');
352 47
        if (isset($options['evidence'])) {
353 45
            $this->setEvidence($options['evidence']);
354 45
        }
355 47
        $this->setupProperty($options, 'defaultUrlParams');
356 47
        if (isset($options['prefix'])) {
357 45
            $this->setPrefix($options['prefix']);
358 45
        }
359 47
        $this->setupProperty($options, 'debug');
360 47
        $this->updateApiURL();
361 47
    }
362
363
    /**
364
     * Set up one of properties
365
     *
366
     * @param array  $options  array of given properties
367
     * @param string $name     name of property to process
368
     * @param string $constant load default property value from constant
369
     */
370 24
    public function setupProperty($options, $name, $constant = null)
371
    {
372 24
        if (isset($options[$name])) {
373 22
            $this->$name = $options[$name];
374 22
        } else {
375 24
            if (is_null($this->$name) && !empty($constant) && defined($constant)) {
376 24
                $this->$name = constant($constant);
377 24
            }
378
        }
379 24
    }
380
381
    /**
382
     * Inicializace CURL
383
     */
384 70
    public function curlInit()
385
    {
386 70
        $this->curl = \curl_init(); // create curl resource
387 70
        curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, true); // return content as a string from curl_exec
388 70
        curl_setopt($this->curl, CURLOPT_FOLLOWLOCATION, true); // follow redirects (compatibility for future changes in FlexiBee)
389 70
        curl_setopt($this->curl, CURLOPT_HTTPAUTH, true);       // HTTP authentication
390 70
        curl_setopt($this->curl, CURLOPT_SSL_VERIFYPEER, false); // FlexiBee by default uses Self-Signed certificates
391 70
        curl_setopt($this->curl, CURLOPT_SSL_VERIFYHOST, false);
392 70
        curl_setopt($this->curl, CURLOPT_VERBOSE, ($this->debug === true)); // For debugging
393 70
        curl_setopt($this->curl, CURLOPT_USERPWD,
394 70
            $this->user.':'.$this->password); // set username and password
395 70
    }
396
397
    /**
398
     * Zinicializuje objekt dle daných dat. Možné hodnoty:
399
     *
400
     *  * 234                              - interní číslo záznamu k načtení
401
     *  * code:LOPATA                      - kód záznamu
402
     *  * BAGR                             - kód záznamu ka načtení
403
     *  * ['id'=>24,'nazev'=>'hoblík']     - pole hodnot k předvyplnění
404
     *  * 743.json?relations=adresa,vazby  - část url s parametry k načtení
405
     *
406
     * @param mixed $init číslo/"(code:)kód"/(část)URI záznamu k načtení | pole hodnot k předvyplnění
407
     */
408 44
    public function processInit($init)
409
    {
410 44
        if (is_integer($init)) {
411 42
            $this->loadFromFlexiBee($init);
412 44
        } elseif (is_array($init)) {
413 22
            $this->takeData($init);
414 22
        } elseif (preg_match('/\.(json|xml|csv)/', $init)) {
415
            $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...
416
                            : $init)));
417
        } else {
418
            $this->loadFromFlexiBee('code:'.str_replace('code:', '', $init));
419
        }
420 44
    }
421
422
    /**
423
     * Set URL prefix
424
     *
425
     * @param string $prefix
426
     */
427 45
    public function setPrefix($prefix)
428
    {
429
        switch ($prefix) {
430 45
            case 'a': //Access
431 45
            case 'c': //Company
432 45
            case 'u': //User
433 45
            case 'g': //License Groups
434 45
            case 'admin':
435 45
            case 'status':
436 45
            case 'login-logout':
437 45
                $this->prefix = '/'.$prefix.'/';
438 45
                break;
439 23
            case null:
440 23
            case '':
441 23
            case '/':
442 23
                $this->prefix = '';
443 23
                break;
444 23
            default:
445 23
                throw new \Exception(sprintf('Unknown prefix %s', $prefix));
446 23
        }
447 45
    }
448
449
    /**
450
     * Set communication format.
451
     * One of html|xml|json|csv|dbf|xls|isdoc|isdocx|edi|pdf|pdf|vcf|ical
452
     *
453
     * @param string $format
454
     * @return boolen format is availble
455
     */
456 23
    public function setFormat($format)
457
    {
458 23
        $result = true;
459 23
        if (($this->debug === true) && !empty($this->evidence) && isset(Formats::$$this->evidence)) {
460
            if (array_key_exists($format, array_flip(Formats::$$this->evidence))
461
                === false) {
462
                $result = false;
463
            }
464
        }
465 23
        if ($result === true) {
466 23
            $this->format = $format;
467 23
            $this->updateApiURL();
468 23
        }
469 23
        return $result;
470
    }
471
472
    /**
473
     * Nastaví Evidenci pro Komunikaci.
474
     * Set evidence for communication
475
     *
476
     * @param string $evidence evidence pathName to use
477
     * @return boolean evidence switching status
478
     */
479 45
    public function setEvidence($evidence)
480
    {
481 45
        switch ($this->prefix) {
482 45
            case '/c/':
483 44
                if (array_key_exists($evidence, EvidenceList::$name)) {
484 41
                    $this->evidence = $evidence;
485 41
                    $result         = true;
486 41
                } else {
487 23
                    throw new \Exception(sprintf('Try to set unsupported evidence %s',
488 23
                        $evidence));
489
                }
490 41
                break;
491 4
            default:
492 4
                $this->evidence = $evidence;
493 4
                $result         = true;
494 4
                break;
495 45
        }
496 45
        $this->updateApiURL();
497 45
        return $result;
498
    }
499
500
    /**
501
     * Vrací právě používanou evidenci pro komunikaci
502
     * Obtain current used evidence
503
     *
504
     * @return string
505
     */
506 47
    public function getEvidence()
507
    {
508 47
        return $this->evidence;
509
    }
510
511
    /**
512
     * Set used company.
513
     * Nastaví Firmu.
514
     *
515
     * @param string $company
516
     */
517 23
    public function setCompany($company)
518
    {
519 23
        $this->company = $company;
520 23
    }
521
522
    /**
523
     * Obtain company now used
524
     * Vrací právě používanou firmu
525
     *
526
     * @return string
527
     */
528 23
    public function getCompany()
529
    {
530 23
        return $this->company;
531
    }
532
533
    /**
534
     * Vrací název evidence použité v odpovědích z FlexiBee
535
     *
536
     * @return string
537
     */
538 44
    public function getResponseEvidence()
539
    {
540 44
        switch ($this->evidence) {
541 44
            case 'c':
542
                $evidence = 'company';
543
                break;
544 44
            case 'evidence-list':
545 2
                $evidence = 'evidence';
546 2
                break;
547 42
            default:
548 42
                $evidence = $this->getEvidence();
549 42
                break;
550 44
        }
551 44
        return $evidence;
552
    }
553
554
    /**
555
     * Převede rekurzivně Objekt na pole.
556
     *
557
     * @param object|array $object
558
     *
559
     * @return array
560
     */
561 23
    public static function object2array($object)
562
    {
563 23
        $result = null;
564 23
        if (is_object($object)) {
565 23
            $objectData = get_object_vars($object);
566 23
            if (is_array($objectData) && count($objectData)) {
567 23
                $result = array_map('self::object2array', $objectData);
568 23
            }
569 23
        } else {
570 23
            if (is_array($object)) {
571 23
                foreach ($object as $item => $value) {
572 23
                    $result[$item] = self::object2array($value);
573 23
                }
574 23
            } else {
575 23
                $result = $object;
576
            }
577
        }
578
579 23
        return $result;
580
    }
581
582
    /**
583
     * Převede rekurzivně v poli všechny objekty na jejich identifikátory.
584
     *
585
     * @param object|array $object
586
     *
587
     * @return array
588
     */
589 23
    public static function objectToID($object)
590
    {
591 23
        $resultID = null;
592 23
        if (is_object($object)) {
593 23
            $resultID = $object->__toString();
594 23
        } else {
595 23
            if (is_array($object)) {
596 23
                foreach ($object as $item => $value) {
597 23
                    $resultID[$item] = self::objectToID($value);
598 23
                }
599 23
            } else { //String
600 23
                $resultID = $object;
601
            }
602
        }
603
604 23
        return $resultID;
605
    }
606
607
    /**
608
     * Return basic URL for used Evidence
609
     *
610
     * @link https://www.flexibee.eu/api/dokumentace/ref/urls/ Sestavování URL
611
     *
612
     * @return string Evidence URL
613
     */
614 45
    public function getEvidenceURL()
615
    {
616 45
        $evidenceUrl = $this->url.$this->prefix.$this->company;
617 45
        $evidence    = $this->getEvidence();
618 45
        if (!empty($evidence)) {
619 43
            $evidenceUrl .= '/'.$evidence;
620 43
        }
621 45
        return $evidenceUrl;
622
    }
623
624
    /**
625
     * Add suffix to Evidence URL
626
     *
627
     * @param string $urlSuffix
628
     *
629
     * @return string
630
     */
631
    public function evidenceUrlWithSuffix($urlSuffix)
632
    {
633
        $evidenceUrl = $this->getEvidenceUrl();
634
        if (!empty($urlSuffix)) {
635
            if (($urlSuffix[0] != '/') && ($urlSuffix[0] != ';') && ($urlSuffix[0]
636
                != '?')) {
637
                $evidenceUrl .= '/';
638
            }
639
            $evidenceUrl .= $urlSuffix;
640
        }
641
        return $evidenceUrl;
642
    }
643
644
    /**
645
     * Update $this->apiURL
646
     */
647 24
    public function updateApiURL()
648
    {
649 24
        $this->apiURL = $this->getEvidenceURL();
650 24
        $id           = $this->__toString();
651 24
        if (!empty($id)) {
652 13
            $this->apiURL .= '/'.urlencode($id);
653 13
        }
654 24
        $this->apiURL .= '.'.$this->format;
655 24
    }
656
657
    /**
658
     * Funkce, která provede I/O operaci a vyhodnotí výsledek.
659
     *
660
     * @param string $urlSuffix část URL za identifikátorem firmy.
661
     * @param string $method    HTTP/REST metoda
662
     * @param string $format    Requested format
663
     * @return array|boolean Výsledek operace
664
     */
665 44
    public function performRequest($urlSuffix = null, $method = 'GET',
666
                                   $format = null)
667
    {
668 44
        $this->rowCount = null;
669
670 44
        if (preg_match('/^http/', $urlSuffix)) {
671 22
            $url = $urlSuffix;
672 44
        } elseif ($urlSuffix[0] == '/') {
673 2
            $url = $this->url.$urlSuffix;
674 2
        } else {
675 21
            $url = $this->evidenceUrlWithSuffix($urlSuffix);
676
        }
677
678 44
        $responseCode = $this->doCurlRequest($url, $method, $format);
679
680 44
        return $this->parseResponse($this->rawResponseToArray($this->lastCurlResponse,
681 44
                    $this->responseFormat), $responseCode);
682
    }
683
684
    /**
685
     * Parse Raw FlexiBee response in several formats
686
     *
687
     * @param string $responseRaw raw response body
688
     * @param string $format      Raw Response format json|xml|etc
689
     *
690
     * @return array
691
     */
692 23
    public function rawResponseToArray($responseRaw, $format)
693
    {
694
        switch ($format) {
695 23
            case 'json':
696 23
                $responseDecoded = json_decode($responseRaw, true, 10);
697 23
                $decodeError     = json_last_error_msg();
698 23
                if ($decodeError == 'No error') {
699 23
                    if (array_key_exists($this->nameSpace, $responseDecoded)) {
700 21
                        $responseDecoded = $responseDecoded[$this->nameSpace];
701 21
                    }
702 23
                } else {
703
                    $this->addStatusMessage('JSON Decoder: '.$decodeError,
704
                        'error');
705
                    $this->addStatusMessage($responseRaw, 'debug');
706
                }
707 23
                break;
708
            case 'xml':
709
                $responseDecoded = self::xml2array($this->lastCurlResponse);
710
                break;
711
            case 'txt':
712
            default:
713
                $responseDecoded = $this->lastCurlResponse;
714
                break;
715
        }
716 23
        return $responseDecoded;
717
    }
718
719
    /**
720
     * Parse Response array
721
     *
722
     * @param array $responseDecoded
723
     * @param int $responseCode Request Response Code
724
     *
725
     * @return array main data part of response
726
     */
727 23
    public function parseResponse($responseDecoded, $responseCode)
728
    {
729 23
        $response = null;
730
        switch ($responseCode) {
731 23
            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...
732
                if (isset($responseDecoded[$this->resultField][0]['id'])) {
733
                    $this->lastInsertedID = $responseDecoded[$this->resultField][0]['id'];
734
                    $this->setMyKey($this->lastInsertedID);
735
                    $this->apiURL         = $this->getEvidenceURL().'/'.$this->lastInsertedID;
736
                } else {
737
                    $this->lastInsertedID = null;
738
                }
739 23
            case 200: //Success Read
740 14
                $response         = $this->lastResult = $this->unifyResponseFormat($responseDecoded);
741 14
                if (isset($responseDecoded['@rowCount'])) {
742
                    $this->rowCount = (int) $responseDecoded['@rowCount'];
743
                }
744 14
                break;
745
746 9
            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...
747
                if ($this->debug === true) {
748
                    $this->error500Reporter($responseDecoded);
749
                }
750 9
            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...
751 8
                if ($this->ignoreNotFound === true) {
752
                    break;
753
                }
754 9
            case 400: //Bad Request parameters
755 9
            default: //Something goes wrong
756 9
                $this->addStatusMessage($this->lastResponseCode.': '.$this->curlInfo['url'],
757 9
                    'warning');
758 9
                if (is_array($responseDecoded)) {
759 9
                    $this->parseError($responseDecoded);
760 9
                }
761 9
                $this->logResult($responseDecoded, $this->curlInfo['url']);
762
                break;
763 23
        }
764
        return $response;
765
    }
766
767
    /**
768
     * Parse error message response
769
     *
770
     * @param array $responseDecoded
771
     * @return int number of errors processed
772 9
     */
773
    public function parseError(array $responseDecoded)
774 9
    {
775
        if (array_key_exists('results', $responseDecoded)) {
776
            $this->errors = $responseDecoded['results'][0]['errors'];
777 9
        } else {
778 8
            if (array_key_exists('message', $responseDecoded)) {
779 8
                $this->errors = [['message' => $responseDecoded['message']]];
780
            }
781 9
        }
782
        return count($this->errors);
783
    }
784
785
    /**
786
     * Vykonej HTTP požadavek
787
     *
788
     * @link https://www.flexibee.eu/api/dokumentace/ref/urls/ Sestavování URL
789
     * @param string $url    URL požadavku
790
     * @param string $method HTTP Method GET|POST|PUT|OPTIONS|DELETE
791
     * @param string $format požadovaný formát komunikace
792
     * @return int HTTP Response CODE
793 23
     */
794
    public function doCurlRequest($url, $method, $format = null)
795 23
    {
796 23
        if (is_null($format)) {
797 23
            $format = $this->format;
798 23
        }
799
        curl_setopt($this->curl, CURLOPT_URL, $url);
800 23
// Nastavení samotné operace
801
        curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, strtoupper($method));
802 23
//Vždy nastavíme byť i prázná postdata jako ochranu před chybou 411
803
        curl_setopt($this->curl, CURLOPT_POSTFIELDS, $this->postFields);
804 23
805
        $httpHeaders = $this->defaultHttpHeaders;
806 23
807
        $formats = Formats::bySuffix();
808 23
809 23
        if (!isset($httpHeaders['Accept'])) {
810 23
            $httpHeaders['Accept'] = $formats[$format]['content-type'];
811 23
        }
812 23
        if (!isset($httpHeaders['Content-Type'])) {
813 23
            $httpHeaders['Content-Type'] = $formats[$format]['content-type'];
814 23
        }
815 23
        $httpHeadersFinal = [];
816 23
        foreach ($httpHeaders as $key => $value) {
817 23
            if (($key == 'User-Agent') && ($value == 'FlexiPeeHP')) {
818 23
                $value .= ' v'.self::$libVersion;
819 23
            }
820 23
            $httpHeadersFinal[] = $key.': '.$value;
821
        }
822 23
823
        curl_setopt($this->curl, CURLOPT_HTTPHEADER, $httpHeadersFinal);
824
825 23
// Proveď samotnou operaci
826 23
        $this->lastCurlResponse            = curl_exec($this->curl);
827 23
        $this->curlInfo                    = curl_getinfo($this->curl);
828 23
        $this->curlInfo['when']            = microtime();
829 23
        $this->curlInfo['request_headers'] = $httpHeadersFinal;
830 23
        $this->responseFormat              = isset($this->curlInfo['content_type'])
831 23
                ? Formats::contentTypeToSuffix($this->curlInfo['content_type']) : 'txt';
832 23
        $this->lastResponseCode            = $this->curlInfo['http_code'];
833
        $this->lastCurlError               = curl_error($this->curl);
834
        if (strlen($this->lastCurlError)) {
835
            $this->addStatusMessage(sprintf('Curl Error (HTTP %d): %s',
836
                    $this->lastResponseCode, $this->lastCurlError), 'error');
837 23
        }
838
839
        if ($this->debug === true) {
840
            $this->saveDebugFiles();
841 23
        }
842
843
        return $this->lastResponseCode;
844
    }
845
846
    /**
847
     * Nastaví druh prováděné akce.
848
     *
849
     * @link https://demo.flexibee.eu/devdoc/actions Provádění akcí
850
     * @param string $action
851 20
     * @return boolean
852
     */
853 20
    public function setAction($action)
854 20
    {
855 20
        $result           = false;
856 20
        $actionsAvailable = $this->getActionsInfo();
857 15
        if (is_array($actionsAvailable) && array_key_exists($action,
858 15
                $actionsAvailable)) {
859 15
            $this->action = $action;
860 20
            $result       = true;
861
        }
862
        return $result;
863
    }
864
865
    /**
866
     * Convert XML to array.
867
     *
868
     * @param string $xml
869
     *
870 23
     * @return array
871
     */
872 23
    public static function xml2array($xml)
873
    {
874 23
        $arr = [];
875 23
876 23
        if (is_string($xml)) {
877
            $xml = simplexml_load_string($xml);
878 23
        }
879 23
880 23
        foreach ($xml->children() as $r) {
881 23
            if (count($r->children()) == 0) {
882 23
                $arr[$r->getName()] = strval($r);
883
            } else {
884 23
                $arr[$r->getName()][] = self::xml2array($r);
885
            }
886 23
        }
887
888
        return $arr;
889
    }
890
891
    /**
892 23
     * Odpojení od FlexiBee.
893
     */
894 23
    public function disconnect()
895 23
    {
896 23
        if (is_resource($this->curl)) {
897 23
            curl_close($this->curl);
898 23
        }
899
        $this->curl = null;
900
    }
901
902
    /**
903 23
     * Disconnect CURL befere pass away
904
     */
905 23
    public function __destruct()
906 23
    {
907
        $this->disconnect();
908
    }
909
910
    /**
911
     * Načte řádek dat z FlexiBee.
912
     *
913
     * @param int $recordID id požadovaného záznamu
914
     *
915 23
     * @return array
916
     */
917 23
    public function getFlexiRow($recordID)
918 23
    {
919 23
        $record   = null;
920
        $response = $this->performRequest($this->evidence.'/'.$recordID.'.json');
921
        if (isset($response[$this->evidence])) {
922
            $record = $response[$this->evidence][0];
923 23
        }
924
925
        return $record;
926
    }
927
928
    /**
929
     * Oddělí z pole podmínek ty jenž patří za ? v URL požadavku
930
     *
931
     * @link https://www.flexibee.eu/api/dokumentace/ref/urls/ Sestavování URL
932
     * @param array $conditions pole podmínek   - rendrují se do ()
933
     * @param array $urlParams  pole parametrů  - rendrují za ?
934
     */
935
    public function extractUrlParams(&$conditions, &$urlParams)
936
    {
937
        foreach ($this->urlParams as $urlParam) {
938
            if (isset($conditions[$urlParam])) {
939
                \Ease\Sand::divDataArray($conditions, $urlParams, $urlParam);
940
            }
941
        }
942
    }
943
944
945
    /**
946
     * convert unicode to entities
947
     *
948
     * @param string $urlRaw
949
     * @return string
950 41
     */
951
    public static function urlEncode($urlRaw)
952 41
    {
953 41
        return str_replace(['%27'], ["'"], rawurlencode($urlRaw));
954
    }
955 41
956 16
    /**
957
     * Načte data z FlexiBee.
958
     *
959
     * @param string $suffix     dotaz
960
     * @param string|array $conditions Volitelný filtrovací výraz
961 16
     *
962 14
     * @return array Data obtained
963 14
     */
964 16
    public function getFlexiData($suffix = null, $conditions = null)
965
    {
966 41
        $finalUrl  = '';
967 22
        $urlParams = $this->defaultUrlParams;
968 22
969 22
        if (!is_null($conditions)) {
970 22
            if (is_array($conditions)) {
971
                $this->extractUrlParams($conditions, $urlParams);
972 41
                $conditions = $this->flexiUrl($conditions);
973
            }
974 41
975 41
            if (strlen($conditions) && ($conditions[0] != '/')) {
976
                $conditions = '('.self::urlEncode($conditions).')';
977
            }
978 41
        }
979
980 41
        if (strlen($suffix)) {
981 41
            if (preg_match('/^http/', $suffix) || ($suffix[0] == '/') || is_numeric($suffix)) {
982 41
                $finalUrl = $suffix;
983
            } else {
984 41
                if (preg_match('/^(code|ext):(.*)/', $suffix, $matches)) {
985
                    $finalUrl = $matches[1].':'.rawurlencode($matches[2]);
986 41
                }
987 41
            }
988 41
        }
989 30
990 30
        $finalUrl .= $conditions;
991
992
        if (count($urlParams)) {
993 30
            if (strstr($finalUrl, '?')) {
994 11
                $finalUrl .= '&';
995
            } else {
996
                $finalUrl .= '?';
997 41
            }
998
            $finalUrl .= http_build_query($urlParams, null, '&',
999
                PHP_QUERY_RFC3986);
1000
        }
1001
1002
        $transactions = $this->performRequest($finalUrl, 'GET');
1003
1004
        $responseEvidence = $this->getResponseEvidence();
1005
        if (is_array($transactions) && array_key_exists($responseEvidence,
1006
                $transactions)) {
1007
            $result = $transactions[$responseEvidence];
1008 45
            if ((count($result) == 1) && (count(current($result)) == 0 )) {
1009
                $result = null; // Response is empty Array
1010 45
            }
1011 45
        } else {
1012 23
            $result = $transactions;
1013 23
        }
1014 45
1015
        return $result;
1016
    }
1017 45
1018 45
    /**
1019 45
     * Načte záznam z FlexiBee a uloží v sobě jeho data
1020 22
     * Read FlexiBee record and store it inside od object
1021 22
     *
1022 45
     * @param int $id ID or conditions
1023
     *
1024
     * @return int počet načtených položek
1025
     */
1026
    public function loadFromFlexiBee($id = null)
1027
    {
1028
        $data = [];
1029
        if (is_null($id)) {
1030
            $id = $this->getMyKey();
1031
        }
1032
        if (is_array($id)) {
1033 23
            $id = rawurlencode('('.self::flexiUrl($id).')');
1034
        }
1035
1036 23
        if (preg_match('/^code/', $id)) {
1037 23
            $id = self::code(rawurlencode(self::uncode($id)));
1038 23
        }
1039 23
1040 23
        $flexidata    = $this->getFlexiData($this->getEvidenceUrl().'/'.$id);
1041
        $this->apiURL = $this->curlInfo['url'];
1042 23
        if (is_array($flexidata) && (count($flexidata) == 1)) {
1043 15
            $data = current($flexidata);
1044 15
        }
1045 15
        return $this->takeData($data);
1046
    }
1047 23
1048
    /**
1049
     * Převede data do Json formátu pro FlexiBee.
1050
     * Convert data to FlexiBee like Json format
1051 23
     *
1052
     * @param array $data
1053
     *
1054
     * @return string
1055
     */
1056
    public function jsonizeData($data)
1057
    {
1058
        $dataToJsonize = [
1059 23
            $this->nameSpace => [
1060
                '@version' => $this->protoVersion,
1061 23
                $this->evidence => $this->objectToID($data),
1062
            ],
1063
        ];
1064 23
1065 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...
1066 23
            $dataToJsonize[$this->nameSpace][$this->evidence.'@action'] = $this->action;
1067
            $this->action                                               = null;
1068 23
        }
1069
1070 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...
1071
            $dataToJsonize[$this->nameSpace][$this->evidence.'@filter'] = $this->filter;
1072
        }
1073
1074
        return json_encode($dataToJsonize);
1075
    }
1076
1077 15
    /**
1078
     * Test if given record ID exists in FlexiBee.
1079
     *
1080 15
     * @param string|int $identifer
1081 15
     */
1082 15
    public function idExists($identifer = null)
1083
    {
1084 15
        if (is_null($identifer)) {
1085 15
            $identifer = $this->getMyKey();
1086
        }
1087
        $flexiData = $this->getFlexiData(
1088
            'detail=custom:'.$this->getmyKeyColumn(),
1089
            [$this->getmyKeyColumn() => $identifer]);
1090
1091
        return $flexiData;
1092
    }
1093
1094
    /**
1095
     * Test if given record exists in FlexiBee.
1096
     *
1097
     * @param array $data
1098
     * @return boolean Record presence status
1099
     */
1100
    public function recordExists($data = [])
1101
    {
1102
1103
        if (empty($data)) {
1104
            $data = $this->getData();
1105
        }
1106
1107
        $res = $this->getColumnsFromFlexibee([$this->myKeyColumn],
1108
            self::flexiUrl($data));
0 ignored issues
show
Documentation introduced by
self::flexiUrl($data) is of type string, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
1109
1110
        if (!count($res) || (isset($res['success']) && ($res['success'] == 'false'))
1111
            || !count($res[0])) {
1112
            $found = false;
1113
        } else {
1114
            $found = true;
1115
        }
1116
        return $found;
1117
    }
1118
1119
    /**
1120
     * Vrací z FlexiBee sloupečky podle podmínek.
1121
     *
1122
     * @param array|int|string $conditions pole podmínek nebo ID záznamu
1123
     * @param string           $indexBy    klice vysledku naplnit hodnotou ze
1124
     *                                     sloupečku
1125
     * @return array
1126
     */
1127
    public function getAllFromFlexibee($conditions = null, $indexBy = null)
1128 23
    {
1129
        if (is_int($conditions)) {
1130
            $conditions = [$this->getmyKeyColumn() => $conditions];
1131 23
        }
1132 23
1133 23
        $flexiData = $this->getFlexiData('', $conditions);
1134
1135 23
        if (!is_null($indexBy)) {
1136 23
            $flexiData = $this->reindexArrayBy($flexiData);
1137 23
        }
1138 23
1139 23
        return $flexiData;
1140 23
    }
1141 23
1142 23
    /**
1143
     * Vrací z FlexiBee sloupečky podle podmínek.
1144 23
     *
1145
     * @param string[] $columnsList seznam položek
1146
     * @param array    $conditions  pole podmínek nebo ID záznamu
1147 23
     * @param string   $indexBy     Sloupeček podle kterého indexovat záznamy
1148
     *
1149
     * @return array
1150 23
     */
1151 23
    public function getColumnsFromFlexibee($columnsList, $conditions = [],
1152 23
                                           $indexBy = null)
1153 23
    {
1154 23
        $detail = 'full';
1155
        switch (gettype($columnsList)) {
1156 23
            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...
1157
                $conditions = [$this->getmyKeyColumn() => $conditions];
1158 23
            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...
1159
                if (!is_null($indexBy) && !array_key_exists($indexBy,
1160 23
                        $columnsList)) {
1161 21
                    $columnsList[] = $indexBy;
1162 18
                }
1163
                $columns = implode(',', array_unique($columnsList));
1164 20
                $detail  = 'custom:'.$columns;
1165
            default:
1166
                switch ($columnsList) {
1167
                    case 'id':
1168
                        $detail = 'id';
1169
                        break;
1170
                    case 'summary':
1171
                        $detail = 'summary';
1172
                        break;
1173
                    default:
1174
                        break;
1175 23
                }
1176
                break;
1177 23
        }
1178
1179 23
        $conditions['detail'] = $detail;
1180 23
1181 23
        $flexiData = $this->getFlexiData(null, $conditions);
1182
1183 23
        if (!is_null($indexBy) && count($flexiData) && count(current($flexiData))) {
1184 23
            $flexiData = $this->reindexArrayBy($flexiData, $indexBy);
1185 23
        }
1186
1187 23
        return $flexiData;
1188 23
    }
1189 23
1190 23
    /**
1191 23
     * Vrací kód záznamu.
1192 23
     * Obtain record CODE
1193 23
     *
1194 23
     * @param mixed $data
1195 23
     *
1196 23
     * @return string
1197
     */
1198
    public function getKod($data = null, $unique = true)
1199
    {
1200 23
        $kod = null;
1201 23
1202 23
        if (is_null($data)) {
1203
            $data = $this->getData();
1204 23
        }
1205 23
1206 23
        if (is_string($data)) {
1207 23
            $data = [$this->nameColumn => $data];
1208
        }
1209
1210 23
        if (isset($data['kod'])) {
1211 23
            $kod = $data['kod'];
1212 23
        } else {
1213 23
            if (isset($data[$this->nameColumn])) {
1214 23
                $kod = preg_replace('/[^a-zA-Z0-9]/', '',
1215 23
                    \Ease\Sand::rip($data[$this->nameColumn]));
1216 23
            } else {
1217 23
                if (isset($data[$this->myKeyColumn])) {
1218 23
                    $kod = \Ease\Sand::rip($data[$this->myKeyColumn]);
1219 23
                }
1220 23
            }
1221 23
        }
1222
1223 23
        if (!strlen($kod)) {
1224 23
            $kod = 'NOTSET';
1225
        }
1226 23
1227
        if (strlen($kod) > 18) {
1228
            $kodfinal = strtoupper(substr($kod, 0, 18));
1229
        } else {
1230
            $kodfinal = strtoupper($kod);
1231
        }
1232
1233
        if ($unique) {
1234
            $counter = 0;
1235
            if (count($this->codes)) {
1236 32
                foreach ($this->codes as $codesearch => $keystring) {
1237
                    if (strstr($codesearch, $kodfinal)) {
1238 32
                        ++$counter;
1239 32
                    }
1240 31
                }
1241 8
            }
1242 8
            if ($counter) {
1243 31
                $kodfinal = $kodfinal.$counter;
1244 31
            }
1245 31
1246 31
            $this->codes[$kodfinal] = $kod;
1247 32
        }
1248
1249
        return $kodfinal;
1250 32
    }
1251 24
1252 24
    /**
1253
     * Write Operation Result.
1254 32
     *
1255 23
     * @param array  $resultData
1256 23
     * @param string $url        URL
1257 23
     * @return boolean Log save success
1258 23
     */
1259
    public function logResult($resultData = null, $url = null)
1260 23
    {
1261 23
        $logResult = false;
1262 23
        if (isset($resultData['success']) && ($resultData['success'] == 'false')) {
1263 23
            if (isset($resultData['message'])) {
1264 23
                $this->addStatusMessage($resultData['message'], 'warning');
1265
            }
1266 23
            $this->addStatusMessage('Error '.$this->lastResponseCode.': '.urldecode($url),
1267 23
                'warning');
1268 23
            unset($url);
1269 23
        }
1270
        if (is_null($resultData)) {
1271
            $resultData = $this->lastResult;
1272 23
        }
1273
        if (isset($url)) {
1274
            $this->logger->addStatusMessage($this->lastResponseCode.':'.urldecode($url));
1275 23
        }
1276
1277
        if (isset($resultData['results'])) {
1278 23
            if ($resultData['success'] == 'false') {
1279 23
                $status = 'error';
1280 23
            } else {
1281 23
                $status = 'success';
1282 23
            }
1283 32
            foreach ($resultData['results'] as $result) {
1284
                if (isset($result['request-id'])) {
1285
                    $rid = $result['request-id'];
1286
                } else {
1287
                    $rid = '';
1288
                }
1289
                if (isset($result['errors'])) {
1290
                    foreach ($result['errors'] as $error) {
1291
                        $message = $error['message'];
1292
                        if (isset($error['for'])) {
1293
                            $message .= ' for: '.$error['for'];
1294
                        }
1295
                        if (isset($error['value'])) {
1296
                            $message .= ' value:'.$error['value'];
1297
                        }
1298
                        if (isset($error['code'])) {
1299
                            $message .= ' code:'.$error['code'];
1300
                        }
1301
                        $this->addStatusMessage($rid.': '.$message, $status);
1302
                    }
1303
                }
1304
            }
1305
        }
1306
        return $logResult;
1307
    }
1308
1309
    /**
1310
     * Save RAW Curl Request & Response to files in Temp directory
1311
     */
1312
    public function saveDebugFiles()
1313
    {
1314
        $tmpdir   = sys_get_temp_dir();
1315
        $fname    = $this->evidence.'-'.$this->curlInfo['when'].'.'.$this->format;
1316
        $reqname  = $tmpdir.'/request-'.$fname;
1317
        $respname = $tmpdir.'/response-'.$fname;
1318
        file_put_contents($reqname, $this->postFields);
1319
        file_put_contents($respname, $this->lastCurlResponse);
1320 23
    }
1321
1322 23
    /**
1323
     * Připraví data pro odeslání do FlexiBee
1324 23
     *
1325 23
     * @param string $data
1326 23
     */
1327 23
    public function setPostFields($data)
1328 23
    {
1329 23
        $this->postFields = $data;
1330 23
    }
1331 23
1332 23
    /**
1333
     * Generuje fragment url pro filtrování.
1334 23
     *
1335 23
     * @see https://www.flexibee.eu/api/dokumentace/ref/filters
1336 23
     *
1337 23
     * @param array  $data
1338 23
     * @param string $joiner default and/or
1339
     * @param string $defop  default operator
1340
     *
1341 23
     * @return string
1342 23
     */
1343
    public static function flexiUrl(array $data, $joiner = 'and', $defop = 'eq')
1344
    {
1345 23
        $parts = [];
1346
1347 23
        foreach ($data as $column => $value) {
1348 23
            if (!is_numeric($column)) {
1349
                if (is_integer($data[$column]) || is_float($data[$column])) {
1350 23
                    $parts[$column] = $column.' eq \''.$data[$column].'\'';
1351
                } elseif (is_bool($data[$column])) {
1352
                    $parts[$column] = $data[$column] ? $column.' eq true' : $column.' eq false';
1353 23
                } elseif (is_null($data[$column])) {
1354 23
                    $parts[$column] = $column." is null";
1355
                } else {
1356
                    switch ($value) {
1357
                        case '!null':
1358
                            $parts[$column] = $column." is not null";
1359
                            break;
1360
                        case 'is empty':
1361
                        case 'is not empty':
1362
                            $parts[$column] = $column.' '.$value;
1363
                            break;
1364 47
                        default:
1365
                            if ($column == 'stitky') {
1366 47
                                $parts[$column] = $column."='".self::code($data[$column])."'";
1367 47
                            } else {
1368 33
                                $parts[$column] = $column." $defop '".$data[$column]."'";
1369 33
                            }
1370 47
                            break;
1371 47
                    }
1372 9
                }
1373 9
            } else {
1374 9
                $parts[] = $value;
1375
            }
1376 47
        }
1377
        return implode(' '.$joiner.' ', $parts);
1378
    }
1379
1380
    /**
1381
     * Obtain record/object identificator code: or id:
1382
     * Vrací identifikátor objektu code: nebo id:
1383
     *
1384
     * @link https://demo.flexibee.eu/devdoc/identifiers Identifikátory záznamů
1385
     * @return string|int indentifikátor záznamu reprezentovaného objektem
1386 47
     */
1387
    public function getRecordID()
1388 47
    {
1389
        $myCode = $this->getDataValue('kod');
1390
        if ($myCode) {
1391
            $id = self::code($myCode);
1392
        } else {
1393
            $id = $this->getDataValue('id');
1394
            if (($this->debug === true) && is_null($id)) {
1395
                $this->addToLog('Object Data does not contain code: or id: cannot match with statement!',
1396
                    'warning');
1397 23
            }
1398
        }
1399 23
        return is_numeric($id) ? intval($id) : strval($id);
1400
    }
1401
1402
    /**
1403
     * Obtain record/object identificator code: or id:
1404
     * Vrací identifikátor objektu code: nebo id:
1405
     *
1406
     * @link https://demo.flexibee.eu/devdoc/identifiers Identifikátory záznamů
1407 22
     * @return string indentifikátor záznamu reprezentovaného objektem
1408
     */
1409 22
    public function __toString()
1410 22
    {
1411 22
        return strval($this->getRecordID());
1412 19
    }
1413 19
1414 19
    /**
1415 19
     * Gives you FlexiPeeHP class name for Given Evidence
1416
     *
1417
     * @param string $evidence
1418
     * @return string Class name
1419
     */
1420
    public static function evidenceToClassName($evidence)
1421
    {
1422
        return str_replace(' ', '', ucwords(str_replace('-', ' ', $evidence)));
1423
    }
1424 23
1425
    /**
1426 23
     * Obtain ID of first record in evidence
1427 23
     *
1428 23
     * @return string|null id or null if no records
1429
     */
1430
    public function getFirstRecordID()
1431
    {
1432
        $firstID    = null;
1433 23
        $firstIdRaw = $this->getColumnsFromFlexibee(['id'],
1434
            ['limit' => 1, 'order' => 'id'], 'id');
1435
        if (count($firstIdRaw)) {
1436
            $firstID = (int) current($firstIdRaw)['id'];
1437
        }
1438
        return $firstID;
1439
    }
1440
1441 23
    /**
1442
     * Vrací hodnotu daného externího ID
1443
     *
1444
     * @param string $want Which ? If empty,you obtain the first one.
1445
     * @return string
1446
     */
1447
    public function getExternalID($want = null)
1448
    {
1449
        $extid = null;
1450
        $ids   = $this->getDataValue('external-ids');
1451 22
        if (is_null($want)) {
1452
            if (count($ids)) {
1453 22
                $extid = current($ids);
1454 22
            }
1455 22
        } else {
1456 22
            if (!is_null($ids) && is_array($ids)) {
1457 22
                foreach ($ids as $id) {
1458
                    if (strstr($id, 'ext:'.$want)) {
1459 22
                        $extid = str_replace('ext:'.$want.':', '', $id);
1460
                    }
1461
                }
1462
            }
1463 22
        }
1464
        return $extid;
1465
    }
1466
1467
    /**
1468
     * Obtain actual GlobalVersion
1469
     * Vrací aktuální globální verzi změn
1470
     *
1471 23
     * @link https://www.flexibee.eu/api/dokumentace/ref/changes-api#globalVersion Globální Verze
1472
     * @return type
1473 23
     */
1474 23
    public function getGlobalVersion()
1475 23
    {
1476
        $globalVersion = null;
1477
        if (!count($this->lastResult) || !isset($this->lastResult['@globalVersion'])) {
1478 23
            $this->getFlexiData(null,
1479
                ['add-global-version' => 'true', 'limit' => 1]);
1480
        }
1481
1482
        if (isset($this->lastResult['@globalVersion'])) {
1483
            $globalVersion = intval($this->lastResult['@globalVersion']);
1484
        }
1485
1486
        return $globalVersion;
1487 35
    }
1488
1489 35
    /**
1490 35
     * Obtain content type of last response
1491 22
     *
1492 22
     * @return string
1493 35
     */
1494 35
    public function getResponseFormat()
1495 35
    {
1496 35
        if (isset($this->curlInfo['content_type'])) {
1497 35
            $responseFormat = $this->curlInfo['content_type'];
1498 35
        } else {
1499 35
            $responseFormat = null;
1500 22
        }
1501
        return $responseFormat;
1502 35
    }
1503
1504
    /**
1505
     * Return the same response format for one and multiplete results
1506
     *
1507
     * @param array $responseBody
1508
     * @return array
1509
     */
1510 35
    public function unifyResponseFormat($responseBody)
1511
    {
1512
        if (!is_array($responseBody) || array_key_exists('message',
1513
                $responseBody)) { //Unifi response format
1514
            $response = $responseBody;
1515
        } else {
1516
            $evidence = $this->getResponseEvidence();
1517
            if (array_key_exists($evidence, $responseBody)) {
1518
                $response        = [];
1519 23
                $evidenceContent = $responseBody[$evidence];
1520
                if (array_key_exists(0, $evidenceContent)) {
1521 23
                    $response[$evidence] = $evidenceContent; //Multiplete Results
1522 23
                } else {
1523 23
                    $response[$evidence][0] = $evidenceContent; //One result
1524 23
                }
1525 23
            } else {
1526 23
                if (isset($responseBody['priloha'])) {
1527 21
                    $response = $responseBody['priloha'];
1528 21
                } else {
1529 23
                    $response = $responseBody;
1530
                }
1531
            }
1532
        }
1533
        return $response;
1534
    }
1535
1536
    /**
1537
     * Obtain structure for current (or given) evidence
1538 23
     *
1539
     * @param string $evidence
1540 23
     * @return array Evidence structure
1541 23
     */
1542 23 View Code Duplication
    public function getColumnsInfo($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...
1543 23
    {
1544 23
        $columnsInfo = null;
1545 23
        if (is_null($evidence)) {
1546 21
            $evidence = $this->getEvidence();
1547 21
        }
1548 23
        $propsName = lcfirst(FlexiBeeRO::evidenceToClassName($evidence));
1549
        if (isset(\FlexiPeeHP\Properties::$$propsName)) {
1550
            $columnsInfo = Properties::$$propsName;
1551
        }
1552
        return $columnsInfo;
1553
    }
1554
1555
    /**
1556
     * Obtain actions for current (or given) evidence
1557 23
     *
1558
     * @param string $evidence
1559 23
     * @return array Evidence structure
1560 23
     */
1561 23 View Code Duplication
    public function getActionsInfo($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...
1562 23
    {
1563 23
        $actionsInfo = null;
1564 23
        if (is_null($evidence)) {
1565 19
            $evidence = $this->getEvidence();
1566 19
        }
1567 23
        $propsName = lcfirst(FlexiBeeRO::evidenceToClassName($evidence));
1568
        if (isset(\FlexiPeeHP\Actions::$$propsName)) {
1569
            $actionsInfo = Actions::$$propsName;
1570
        }
1571
        return $actionsInfo;
1572
    }
1573
1574
    /**
1575
     * Obtain relations for current (or given) evidence
1576 23
     *
1577
     * @param string $evidence
1578 23
     * @return array Evidence structure
1579 23
     */
1580 23
    public function getRelationsInfo($evidence = null)
1581 23
    {
1582 23
        $relationsInfo = null;
1583 16
        if (is_null($evidence)) {
1584 16
            $evidence = $this->getEvidence();
1585 23
        }
1586
        $propsName = lcfirst(FlexiBeeRO::evidenceToClassName($evidence));
1587
        if (isset(\FlexiPeeHP\Relations::$$propsName)) {
1588
            $relationsInfo = Relations::$$propsName;
1589
        }
1590
        return $relationsInfo;
1591
    }
1592
1593
    /**
1594 23
     * Obtain info for current (or given) evidence
1595
     *
1596 23
     * @param string $evidence
1597 23
     * @return array Evidence info
1598 23
     */
1599 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...
1600 23
    {
1601 16
        $evidencesInfo = null;
1602 16
        if (is_null($evidence)) {
1603 23
            $evidence = $this->getEvidence();
1604
        }
1605
        if (isset(EvidenceList::$evidences[$evidence])) {
1606
            $evidencesInfo = EvidenceList::$evidences[$evidence];
1607
        }
1608
        return $evidencesInfo;
1609
    }
1610
1611
    /**
1612
     * Obtain name for current (or given) evidence path
1613
     *
1614 15
     * @param string $evidence Evidence Path
1615
     * @return array Evidence info
1616 15
     */
1617 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...
1618 15
    {
1619 15
        $evidenceName = null;
1620 15
        if (is_null($evidence)) {
1621 15
            $evidence = $this->getEvidence();
1622 15
        }
1623
        if (isset(EvidenceList::$name[$evidence])) {
1624
            $evidenceName = EvidenceList::$name[$evidence];
1625
        }
1626 15
        return $evidenceName;
1627 15
    }
1628 15
1629 15
    /**
1630
     * Perform given action (if availble) on current evidence/record
1631
     * @url https://demo.flexibee.eu/devdoc/actions
1632 15
     *
1633
     * @param string $action one of evidence actions
1634
     * @param string $method ext|int External method call operation in URL.
1635
     *                               Internal add the @action element to request body
1636
     */
1637
    public function performAction($action, $method = 'ext')
1638 15
    {
1639 15
        $actionsAvailble = $this->getActionsInfo();
1640 15
1641 15
        if (is_array($actionsAvailble) && array_key_exists($action,
1642 15
                $actionsAvailble)) {
1643
            switch ($actionsAvailble[$action]['actionMakesSense']) {
1644
                case 'ONLY_WITH_INSTANCE_AND_NOT_IN_EDIT':
1645
                case 'ONLY_WITH_INSTANCE': //Add instance
1646
                    $urlSuffix = '/'.$this->__toString().'/'.$action.'.'.$this->format;
1647 15
                    break;
1648
1649
                default:
1650
                    $urlSuffix = '/'.$action;
1651
                    break;
1652
            }
1653
1654
            switch ($method) {
1655 23
                case 'int':
1656
                    $this->setAction($action);
1657 23
                    $this->setPostFields($this->jsonizeData($this->getData()));
1658 1
                    $result = $this->performRequest(null, 'POST');
1659 1
                    break;
1660 23
1661 23
                default:
1662
                    $result = $this->performRequest($urlSuffix, 'GET');
1663
                    break;
1664
            }
1665
        } else {
1666
            throw new \Exception(sprintf(_('Unsupported action %s for evidence %s'),
1667
                $action, $this->getEvidence()));
1668 9
        }
1669
1670 9
        return $result;
1671 9
    }
1672 9
1673 9
    /**
1674 7
     * Save current object to file
1675 7
     *
1676 7
     * @param string $destfile path to file
1677 4
     */
1678 4
    public function saveResponseToFile($destfile)
1679 2
    {
1680
        if (strlen($this->lastCurlResponse)) {
1681 4
            $this->doCurlRequest($this->apiURL, 'GET', $this->format);
1682
        }
1683
        file_put_contents($destfile, $this->lastCurlResponse);
1684
    }
1685
1686
    /**
1687
     * Obtain established relations listing
1688
     *
1689
     * @return array Null or Relations
1690
     */
1691
    public function getVazby($id = null)
1692
    {
1693
        if (is_null($id)) {
1694
            $id = $this->getRecordID();
1695
        }
1696
        if (!empty($id)) {
1697
            $vazbyRaw = $this->getColumnsFromFlexibee(['vazby'],
1698
                ['relations' => 'vazby', 'id' => $id]);
1699
            $vazby    = array_key_exists('vazby', $vazbyRaw[0]) ? $vazbyRaw[0]['vazby']
1700
                    : null;
1701
        } else {
1702
            throw new \Exception(_('ID requied to get record relations '));
1703
        }
1704
        return $vazby;
1705
    }
1706
1707
    /**
1708
     * Gives You URL for Current Record in FlexiBee web interface
1709
     *
1710
     * @return string url
1711
     */
1712
    public function getFlexiBeeURL()
1713
    {
1714
        $parsed_url = parse_url(str_replace('.'.$this->format, '', $this->apiURL));
1715
        $scheme     = isset($parsed_url['scheme']) ? $parsed_url['scheme'].'://'
1716
                : '';
1717
        $host       = isset($parsed_url['host']) ? $parsed_url['host'] : '';
1718
        $port       = isset($parsed_url['port']) ? ':'.$parsed_url['port'] : '';
1719
        $user       = isset($parsed_url['user']) ? $parsed_url['user'] : '';
1720
        $pass       = isset($parsed_url['pass']) ? ':'.$parsed_url['pass'] : '';
1721
        $pass       = ($user || $pass) ? "$pass@" : '';
1722
        $path       = isset($parsed_url['path']) ? $parsed_url['path'] : '';
1723
        return $scheme.$user.$pass.$host.$port.$path;
1724
    }
1725
1726
    /**
1727
     * Set Record Key
1728
     *
1729
     * @param int|string $myKeyValue
1730
     * @return boolean
1731
     */
1732
    public function setMyKey($myKeyValue)
1733
    {
1734
        $res = parent::setMyKey($myKeyValue);
1735
        $this->updateApiURL();
1736
        return $res;
1737
    }
1738
1739
    /**
1740
     * Set or get ignore not found pages flag
1741
     *
1742
     * @param boolean $ignore set flag to
1743
     *
1744
     * @return boolean get flag state
1745
     */
1746
    public function ignore404($ignore = null)
1747
    {
1748
        if (!is_null($ignore)) {
1749
            $this->ignoreNotFound = $ignore;
1750
        }
1751
        return $this->ignoreNotFound;
1752
    }
1753
1754
    /**
1755
     * Send Document by mail
1756
     *
1757
     * @url https://www.flexibee.eu/api/dokumentace/ref/odesilani-mailem/
1758
     *
1759
     * @param string $to
1760
     * @param string $subject
1761
     * @param string $body Email Text
1762
     *
1763
     * @return int http response code
1764
     */
1765
    public function sendByMail($to, $subject, $body, $cc = null)
1766
    {
1767
        $this->setPostFields($body);
1768
        $result = $this->doCurlRequest(urlencode($this->getRecordID()).'/odeslani-dokladu?to='.$to.'&subject='.urlencode($subject).'&cc='.$cc
1769
            , 'PUT', 'xml');
1770
        return $result == 200;
1771
    }
1772
1773
    /**
1774
     * Send all unsent Invoices by mail
1775
     *
1776
     * @url https://www.flexibee.eu/api/dokumentace/ref/odesilani-mailem/
1777
     * @return int http response code
1778
     */
1779
    public function sendUnsent()
1780
    {
1781
        return $this->doCurlRequest('automaticky-odeslat-neodeslane', 'PUT',
1782
                'xml');
1783
    }
1784
1785
    /**
1786
     * FlexiBee date to PHP DateTime
1787
     *
1788
     * @param string $flexidate
1789
     *
1790
     * @return \DateTime | false
1791
     */
1792
    public static function flexiDateToDateTime($flexidate)
1793
    {
1794
        return \DateTime::createFromFormat('Y-m-jO', $flexidate);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The expression \DateTime::createFromFor...('Y-m-jO', $flexidate); of type DateTime|false adds false to the return on line 1794 which is incompatible with the return type documented by FlexiPeeHP\FlexiBeeRO::flexiDateToDateTime of type DateTime. It seems like you forgot to handle an error condition.
Loading history...
1795
    }
1796
1797
    /**
1798
     * Získá dokument v daném formátu
1799
     * Obtain document in given format
1800
     *
1801
     * @param string $format  pdf/csv/xml/json/ ...
1802
     *
1803
     * @return string|null filename downloaded or none
1804
     */
1805
    public function getInFormat($format)
1806
    {
1807
        $response = null;
1808
        if ($this->setFormat($format)) {
1809
            if (($this->doCurlRequest(($format == 'html') ? $this->apiURL.'?inDesktopApp=true'
1810
                            : $this->apiURL, 'GET') == 200)) {
1811
                $response = $this->lastCurlResponse;
1812
            }
1813
        }
1814
        return $response;
1815
    }
1816
1817
    /**
1818
     * Uloží dokument v daném formátu do složky v systému souborů
1819
     * Save document in given format to directory in filesystem
1820
     *
1821
     * @param string $format  pdf/csv/xml/json/ ...
1822
     * @param string $destDir where to put file (prefix)
1823
     *
1824
     * @return string|null filename downloaded or none
1825
     */
1826
    public function downloadInFormat($format, $destDir = './')
1827
    {
1828
        $fileOnDisk = null;
1829
        if ($this->setFormat($format)) {
1830
            $downloadTo = $destDir.$this->getEvidence().'_'.$this->getMyKey().'.'.$format;
1831
            if (($this->doCurlRequest($this->apiURL, 'GET') == 200) && (file_put_contents($downloadTo,
1832
                    $this->lastCurlResponse) !== false)) {
1833
                $fileOnDisk = $downloadTo;
1834
            }
1835
        }
1836
        return $fileOnDisk;
1837
    }
1838
1839
    /**
1840
     * Compile and send Report about Error500 to FlexiBee developers
1841
     * If FlexiBee is running on localost try also include java backtrace
1842
     *
1843
     * @param array $errorResponse result of parseError();
1844
     */
1845
    public function error500Reporter($errorResponse)
1846
    {
1847
        $ur = str_replace('/c/'.$this->company, '',
1848
            str_replace($this->url, '', $this->curlInfo['url']));
1849
        if (!array_key_exists($ur, $this->reports)) {
1850
            $tmpdir   = sys_get_temp_dir();
1851
            $myTime   = $this->curlInfo['when'];
1852
            $curlname = $tmpdir.'/curl-'.$this->evidence.'-'.$myTime.'.json';
1853
            file_put_contents($curlname,
1854
                json_encode($this->curlInfo, JSON_PRETTY_PRINT));
1855
1856
            $report = new \Ease\Mailer($this->reportRecipient,
1857
                'Error report 500 - '.$ur);
1858
1859
            $d     = dir($tmpdir);
1860
            while (false !== ($entry = $d->read())) {
1861
                if (strstr($entry, $myTime)) {
1862
                    $ext  = pathinfo($tmpdir.'/'.$entry, PATHINFO_EXTENSION);
1863
                    $mime = Formats::suffixToContentType($ext);
1864
                    $report->addFile($tmpdir.'/'.$entry,
1865
                        empty($mime) ? 'text/plain' : $mime);
1866
                }
1867
            }
1868
            $d->close();
1869
1870
            if ((strstr($this->url, '://localhost') || strstr($this->url,
1871
                    '://127.')) && file_exists('/var/log/flexibee.log')) {
1872
1873
                $fl = fopen("/var/log/flexibee.log", "r");
1874
                if ($fl) {
1875
                    $tracelog = [];
1876
                    for ($x_pos = 0, $ln = 0, $output = array(); fseek($fl,
1877
                            $x_pos, SEEK_END) !== -1; $x_pos--) {
1878
                        $char = fgetc($fl);
1879
                        if ($char === "\n") {
1880
                            $tracelog[] = $output[$ln];
1881
                            if (strstr($output[$ln], $errorResponse['message'])) {
1882
                                break;
1883
                            }
1884
                            $ln++;
1885
                            continue;
1886
                        }
1887
                        $output[$ln] = $char.((array_key_exists($ln, $output)) ? $output[$ln]
1888
                                : '');
1889
                    }
1890
1891
                    $trace     = implode("\n", array_reverse($tracelog));
1892
                    $tracefile = $tmpdir.'/trace-'.$this->evidence.'-'.$myTime.'.log';
1893
                    file_put_contents($tracefile, $trace);
1894
                    $report->addItem("\n\n".$trace);
1895
                    fclose($fl);
1896
                }
1897
            } else {
1898
                $report->addItem($errorResponse['message']);
1899
            }
1900
1901
            $licenseInfo = $this->performRequest($this->url.'/default-license.json');
1902
1903
            $report->addItem("\n\n".json_encode($licenseInfo['license'],
1904
                    JSON_PRETTY_PRINT));
1905
1906
            if ($report->send()) {
1907
                $this->reports[$ur] = $myTime;
1908
            }
1909
        }
1910
    }
1911
1912
    /**
1913
     * Returns code:CODE
1914
     *
1915
     * @param string $code
1916
     *
1917
     * @return string
1918
     */
1919
    public static function code($code)
1920
    {
1921
        return 'code:'.self::uncode($code);
1922
    }
1923
1924
    /**
1925
     * Returns CODE without code: prefix
1926
     *
1927
     * @param string $code
1928
     *
1929
     * @return string
1930
     */
1931
    public static function uncode($code)
1932
    {
1933
        return str_replace(['code:', 'code%3A'], '', $code);
1934
    }
1935
1936
    /**
1937
     * Reconnect After unserialization
1938
     */
1939
    public function __wakeup()
1940
    {
1941
        parent::__wakeup();
1942
        $this->curlInit();
1943
    }
1944
}
1945