Test Failed
Push — master ( 0e13f3...6d8a3f )
by Vítězslav
06:17
created

FlexiBeeRO::evidenceUrlWithSuffix()   B

Complexity

Conditions 5
Paths 3

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
cc 5
eloc 8
nc 3
nop 1
dl 0
loc 12
ccs 0
cts 2
cp 0
crap 30
rs 8.8571
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-2018 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\Sand
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.9.2.1';
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
        'add-global-version',
271
        'add-row-count',
272
        'as-gui',
273
        'auth',
274
        'authSessionId',
275
        'code-as-id',
276
        'code-in-response',
277
        'delimeter',
278
        'detail', //See: https://www.flexibee.eu/api/dokumentace/ref/detail-levels
279
        'dir',
280
        'dry-run',
281
        'dry-run', // See: https://www.flexibee.eu/api/dokumentace/ref/dry-run/
282
        'encoding',
283
        'export-settings',
284
        'fail-on-warning',
285
        'filter',
286
        'format',
287
        'idUcetniObdobi',
288
        'includes',
289
        'inDesktopApp', // Note: Undocumented function (html only)
290
        'limit',
291
        'mode',
292
        'no-ext-ids',
293
        'no-http-errors',
294
        'no-ids',
295
        'only-ext-ids',
296
        'order',
297
        'relations',
298
        'report-lang',
299
        'report-name',
300
        'report-sign',
301
        'skupina-stitku',
302
        'sort',
303
        'start',
304
        'stitky-as-ids',
305
        'use-ext-id',
306
        'use-internal-id',
307
        'xpath', // See: https://www.flexibee.eu/api/dokumentace/ref/xpath/
308
    ];
309
310
    /**
311
     * Session ID
312
     * @var string
313
     */
314
    public $authSessionId = null;
315
316
    /**
317
     * Save 404 results to log ?
318
     * @var boolean
319
     */
320
    protected $ignoreNotFound = false;
321
322
    /**
323
     * Array of errors caused by last request
324
     * @var array
325
     */
326
    private $errors = [];
327
328
    /**
329
     * List of Error500 reports sent
330
     * @var array
331
     */
332
    private $reports = [];
333
334
    /**
335
     * Send Error500 Report to
336
     * @var string email address
337
     */
338
    public $reportRecipient = '[email protected]';
339
340 70
    /**
341
     * Formating string for \DateTime::format() for datetime columns
342 70
     * @var string
343
     */
344 70
    static public $DateTimeFormat = 'Y-m-d\TH:i:s.u+P';
345 70
346 70
    /**
347 70
     * Formating string for \DateTime::format() for date columns
348 22
     * @var string
349 22
     */
350 70
    static public $DateFormat = 'Y-m-d';
351
352
    /**
353
     * Last Request response stats
354
     * @var array 
355
     */
356
    private $responseStats = null;
357
358 71
    /**
359
     * Chained Objects
360 71
     * @var array
361 71
     */
362 71
    public $chained = [];
363 71
364 71
    /**
365 23
     * We Connect to server by default
366 23
     * @var boolean
367 71
     */
368 71
    public $offline = false;
369 23
370 23
    /**
371 71
     * Override cURL timeout
372
     * @var int seconds
373
     */
374 71
    public $timeout = null;
375 71
376 71
    /**
377
     * Class for read only interaction with FlexiBee.
378
     *
379
     * @param mixed $init default record id or initial data
380
     * @param array $options Connection settings and other options override
381
     */
382
    public function __construct($init = null, $options = [])
383
    {
384
        $this->init = $init;
385 48
386
        parent::__construct();
387 48
        $this->setUp($options);
388
        $this->curlInit();
389
        if (!empty($init)) {
390 48
            $this->processInit($init);
391 48
        }
392 48
    }
393
394 48
    /**
395
     * SetUp Object to be ready for work
396
     *
397
     * @param array $options Object Options ( user,password,authSessionId
398
     *                                        company,url,evidence,
399 94
     *                                        prefix,defaultUrlParams,debug,
400
     *                                        detail,offline,filter,ignore404
401 94
     *                                        timeout
402 94
     */
403 94
    public function setUp($options = [])
404 94
    {
405 94
        $this->setupProperty($options, 'company', 'FLEXIBEE_COMPANY');
406 94
        $this->setupProperty($options, 'url', 'FLEXIBEE_URL');
407 94
        $this->setupProperty($options, 'user', 'FLEXIBEE_LOGIN');
408 94
        $this->setupProperty($options, 'password', 'FLEXIBEE_PASSWORD');
409 94
        $this->setupProperty($options, 'authSessionId', 'FLEXIBEE_AUTHSESSID');
410 94
        $this->setupProperty($options, 'timeout', 'FLEXIBEE_TIMEOUT');
411
        if (!empty($this->authSessionId)) {
412
            $this->defaultHttpHeaders['X-authSessionId'] = $this->authSessionId;
413
        }
414
        if (isset($options['evidence'])) {
415
            $this->setEvidence($options['evidence']);
416
        }
417
        $this->setupProperty($options, 'defaultUrlParams');
418
        if (isset($options['prefix'])) {
419
            $this->setPrefix($options['prefix']);
420
        }
421
        if (array_key_exists('detail', $options)) {
422
            $this->defaultUrlParams['detail'] = $options['detail'];
423 13
        }
424
        $this->setupProperty($options, 'filter');
425 13
        if (array_key_exists('offline', $options)) {
426 10
            $this->offline = (boolean) $options['offline'];
427 13
        }
428 13
429 13
        if (array_key_exists('ignore404', $options)) {
430 10
            $this->ignore404($options['ignore404']);
431 10
        }
432 10
433 8
        $this->setupProperty($options, 'debug');
434
        $this->updateApiURL();
435 13
    }
436
437
    /**
438
     * Set up one of properties
439
     *
440
     * @param array  $options  array of given properties
441
     * @param string $name     name of property to process
442 23
     * @param string $constant load default property value from constant
443
     */
444
    public function setupProperty($options, $name, $constant = null)
445 23
    {
446 23
        if (array_key_exists($name, $options)) {
447 23
            $this->$name = $options[$name];
448 23
        } else {
449 23
            if (property_exists($this, $name) && !empty($constant) && defined($constant)) {
450 23
                $this->$name = constant($constant);
451 23
            }
452 23
        }
453 23
    }
454 23
455 23
    /**
456 23
     * Get Current connection options for use in another object
457 23
     *
458 23
     * @return array usable as second constructor parameter
459 23
     */
460 23
    public function getConnectionOptions()
461 23
    {
462 23
        $conOpts = ['url' => $this->url];
463
        if (empty($this->authSessionId)) {
464
            $conOpts ['user']    = $this->user;
465
            $conOpts['password'] = $this->password;
466
        } else {
467
            $conOpts['authSessionId'] = $this->authSessionId;
468
        }
469
        $company = $this->getCompany();
470
        if (!empty($company)) {
471 23
            $conOpts['company'] = $company;
472
        }
473 23
        if (!is_null($this->timeout)) {
474 23
            $conOpts['timeout'] = $this->timeout;
475
        }
476
        return $conOpts;
477
    }
478
479
    /**
480 23
     * Inicializace CURL
481 23
     *
482 23
     * @return boolean Online Status
483 23
     */
484 23
    public function curlInit()
485
    {
486
        if ($this->offline === false) {
487
            $this->curl = \curl_init(); // create curl resource
488
            curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, true); // return content as a string from curl_exec
489
            curl_setopt($this->curl, CURLOPT_FOLLOWLOCATION, true); // follow redirects (compatibility for future changes in FlexiBee)
490
            curl_setopt($this->curl, CURLOPT_HTTPAUTH, true);       // HTTP authentication
491
            curl_setopt($this->curl, CURLOPT_SSL_VERIFYPEER, false); // FlexiBee by default uses Self-Signed certificates
492
            curl_setopt($this->curl, CURLOPT_SSL_VERIFYHOST, false);
493
            curl_setopt($this->curl, CURLOPT_VERBOSE, ($this->debug === true)); // For debugging
494 23
            if (empty($this->authSessionId)) {
495
                curl_setopt($this->curl, CURLOPT_USERPWD,
496 23
                    $this->user.':'.$this->password); // set username and password
497 23
            }
498 23
            if (!is_null($this->timeout)) {
499 23
                curl_setopt($this->curl, CURLOPT_TIMEOUT, $this->timeout);
500
            }
501
        }
502
        return !$this->offline;
503 23
    }
504 23
505
    /**
506
     * Zinicializuje objekt dle daných dat. Možné hodnoty:
507 20
     *
508 20
     *  * 234                              - interní číslo záznamu k načtení
509
     *  * code:LOPATA                      - kód záznamu
510 20
     *  * BAGR                             - kód záznamu k načtení
511 3
     *  * ['id'=>24,'nazev'=>'hoblík']     - pole hodnot k předvyplnění
512 3
     *  * 743.json?relations=adresa,vazby  - část url s parametry k načtení
513 3
     *
514 3
     * @param mixed $init číslo/"(code:)kód"/(část)URI záznamu k načtení | pole hodnot k předvyplnění
515 23
     */
516 23
    public function processInit($init)
517 23
    {
518
        if (is_integer($init)) {
519
            $this->loadFromFlexiBee($init);
520
        } elseif (is_array($init)) {
521
            $this->takeData($init);
522
        } elseif (preg_match('/\.(json|xml|csv)/', $init)) {
523
            $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...
524
                            : $init)));
525
        } else {
526 69
            $this->loadFromFlexiBee($init);
527
        }
528 69
    }
529
530
    /**
531
     * Set Data Field value
532
     *
533
     * @param string $columnName field name
534
     * @param mixed  $value      field data value
535
     *
536
     * @return bool Success
537 23
     */
538
    public function setDataValue($columnName, $value)
539 23
    {
540 23
        switch ($columnName) {
541
            case 'kod':
542
                $value = self::uncode($value); //Alwyas uncode "kod" column
543
                break;
544
            default:
545
                break;
546
        }
547
        if (is_object($value)) {
548 23
            switch (get_class($value)) {
549
                case 'DateTime':
550 23
                    $columnInfo = $this->getColumnInfo($columnName);
551
                    switch ($columnInfo['type']) {
552
                        case 'date':
553
                            $value = self::dateToFlexiDate($value);
554
                            break;
555
                        case 'datetime':
556
                            $value = self::dateToFlexiDateTime($value);
557
                            break;
558 25
                    }
559
                    break;
560 25
            }
561 25
        }
562
        return parent::setDataValue($columnName, $value);
563
    }
564 25
565 1
    /**
566 1
     * PHP Date object to FlexiBee date format
567 24
     * 
568 24
     * @param \DateTime $date
569 24
     */
570 25
    public static function dateToFlexiDate($date)
571 25
    {
572
        return $date->format(self::$DateFormat);
573
    }
574
575
    /**
576
     * PHP Date object to FlexiBee date format
577
     * 
578
     * @param \DateTime $dateTime
579
     */
580
    public static function dateToFlexiDateTime($dateTime)
581 23
    {
582
        return $dateTime->format(self::$DateTimeFormat);
583 23
    }
584 23
585 23
    /**
586 23
     * Set URL prefix
587 23
     *
588 23
     * @param string $prefix
589 23
     */
590 23
    public function setPrefix($prefix)
591 23
    {
592 23
        switch ($prefix) {
593 23
            case 'a': //Access
594 23
            case 'c': //Company
595 23
            case 'u': //User
596
            case 'g': //License Groups
597
            case 'admin':
598
            case 'status':
599 23
            case 'login-logout':
600
                $this->prefix = '/'.$prefix.'/';
601
                break;
602
            case null:
603
            case '':
604
            case '/':
605
                $this->prefix = '';
606
                break;
607
            default:
608
                throw new \Exception(sprintf('Unknown prefix %s', $prefix));
609 23
        }
610
    }
611 23
612 23
    /**
613 22
     * Set communication format.
614 22
     * One of html|xml|json|csv|dbf|xls|isdoc|isdocx|edi|pdf|pdf|vcf|ical
615 23
     *
616 17
     * @param string $format
617 17
     * 
618 17
     * @return boolen format is availble
619 17
     */
620 23
    public function setFormat($format)
621
    {
622
        $result = true;
623
        if (($this->debug === true) && !empty($this->evidence) && isset(Formats::$$this->evidence)) {
624 23
            if (array_key_exists($format, array_flip(Formats::$$this->evidence))
625
                === false) {
626
                $result = false;
627
            }
628
        }
629
        if ($result === true) {
630
            $this->format = $format;
631
            $this->updateApiURL();
632
        }
633
        return $result;
634 68
    }
635
636 68
    /**
637 68
     * Nastaví Evidenci pro Komunikaci.
638 68
     * Set evidence for communication
639 62
     *
640 62
     * @param string $evidence evidence pathName to use
641 68
     * 
642
     * @return boolean evidence switching status
643
     */
644
    public function setEvidence($evidence)
645
    {
646
        switch ($this->prefix) {
647
            case '/c/':
648
                if ($this->debug === true) {
649
                    if (array_key_exists($evidence, EvidenceList::$name)) {
650
                        $this->evidence = $evidence;
651 23
                        $result         = true;
652
                    } else {
653 23
                        throw new \Exception(sprintf('Try to set unsupported evidence %s',
654 23
                                $evidence));
655 23
                    }
656 23
                } else {
657 23
                    $this->evidence = $evidence;
658 23
                    $result         = true;
659 23
                }
660 23
                break;
661 23
            default:
662
                $this->evidence = $evidence;
663
                $result         = true;
664
                break;
665
        }
666
        $this->updateApiURL();
667 48
        return $result;
668
    }
669 48
670 48
    /**
671 48
     * Vrací právě používanou evidenci pro komunikaci
672
     * Obtain current used evidence
673
     *
674 48
     * @return string
675 48
     */
676
    public function getEvidence()
677
    {
678
        return $this->evidence;
679
    }
680
681
    /**
682
     * Set used company.
683
     * Nastaví Firmu.
684
     *
685
     * @param string $company
686 23
     */
687
    public function setCompany($company)
688 23
    {
689 23
        $this->company = $company;
690 23
    }
691 23
692 23
    /**
693 23
     * Obtain company now used
694 23
     * Vrací právě používanou firmu
695 23
     *
696 23
     * @return string
697 23
     */
698 23
    public function getCompany()
699 23
    {
700 23
        return $this->company;
701
    }
702
703 23
    /**
704 23
     * Vrací název evidence použité v odpovědích z FlexiBee
705 23
     *
706
     * @return string
707
     */
708 23
    public function getResponseEvidence()
709
    {
710
        switch ($this->evidence) {
711
            case 'c':
712
                $evidence = 'company';
713
                break;
714
            case 'evidence-list':
715
                $evidence = 'evidence';
716
                break;
717
            default:
718 23
                $evidence = $this->getEvidence();
719
                break;
720 23
        }
721
        return $evidence;
722
    }
723
724
    /**
725
     * Převede rekurzivně Objekt na pole.
726
     *
727
     * @param object|array $object
728
     *
729
     * @return array
730
     */
731 25
    public static function object2array($object)
732
    {
733
        $result = null;
734 25
        if (is_object($object)) {
735
            $objectData = get_object_vars($object);
736 25
            if (is_array($objectData) && count($objectData)) {
737
                $result = array_map('self::object2array', $objectData);
738 25
            }
739 4
        } else {
740 4
            if (is_array($object)) {
741 22
                foreach ($object as $item => $value) {
742
                    $result[$item] = self::object2array($value);
743
                }
744 25
            } else {
745
                $result = $object;
746 25
            }
747 25
        }
748
749
        return $result;
750
    }
751
752
    /**
753
     * Převede rekurzivně v poli všechny objekty na jejich identifikátory.
754
     *
755
     * @param object|array $object
756
     *
757
     * @return array
758 3
     */
759
    public static function objectToID($object)
760 3
    {
761
        $resultID = null;
762 3
        if (is_object($object) && method_exists($object, '__toString')
763 3
        ) {
764 3
            $resultID = $object->__toString();
765
        } else {
766
            if (is_array($object)) {
767
                foreach ($object as $item => $value) {
768
                    $resultID[$item] = self::objectToID($value);
769
                }
770
            } else { //String
771
                $resultID = $object;
772
            }
773 3
        }
774
775 3
        return $resultID;
776
    }
777
778
    /**
779
     * Return basic URL for used Evidence
780
     *
781
     * @link https://www.flexibee.eu/api/dokumentace/ref/urls/ Sestavování URL
782
     *
783
     * @return string Evidence URL
784
     */
785 3
    public function getEvidenceURL()
786
    {
787 3
        $evidenceUrl = $this->url.$this->prefix.$this->company;
788 3
        $evidence    = $this->getEvidence();
789 3
        if (!empty($evidence)) {
790 3
            $evidenceUrl .= '/'.$evidence;
791
        }
792
        return $evidenceUrl;
793 3
    }
794
795
    /**
796
     * Add suffix to Evidence URL
797 3
     *
798
     * @param string $urlSuffix
799
     *
800
     * @return string
801
     */
802
    public function evidenceUrlWithSuffix($urlSuffix)
803
    {
804
        $evidenceUrl = $this->getEvidenceUrl();
805
        if (!empty($urlSuffix)) {
806
            if (($urlSuffix[0] != '/') && ($urlSuffix[0] != ';') && ($urlSuffix[0]
807
                != '?')) {
808
                $evidenceUrl .= '/';
809
            }
810
            $evidenceUrl .= $urlSuffix;
811
        }
812
        return $evidenceUrl;
813
    }
814
815
    /**
816
     * Update $this->apiURL
817
     */
818
    public function updateApiURL()
819
    {
820 3
        $this->apiURL = $this->getEvidenceURL();
821
        $id           = $this->__toString();
822 3
        if (!empty($id)) {
823
            $this->apiURL .= '/'.self::urlEncode($id);
824 3
        }
825
        $this->apiURL .= '.'.$this->format;
826
    }
827
828
    /**
829
     * Add params to url
830
     *
831
     * @param string  $url      originall url
832 3
     * @param array   $addParams   value to add
833 3
     * @param boolean $override replace already existing values ?
834 3
     *
835
     * @return string url with parameters added
836
     */
837 3
    public function addUrlParams($url, $addParams, $override = false)
838
    {
839
        $urlParts = parse_url($url);
840 3
        $urlFinal = '';
841
        if (array_key_exists('scheme', $urlParts)) {
842
            $urlFinal .= $urlParts['scheme'].'://'.$urlParts['host'];
843
        }
844
        if (array_key_exists('port', $urlParts)) {
845
            $urlFinal .= ':'.$urlParts['port'];
846
        }
847
        if (array_key_exists('path', $urlParts)) {
848
            $urlFinal .= $urlParts['path'];
849
        }
850
        if (array_key_exists('query', $urlParts)) {
851
            parse_str($urlParts['query'], $queryUrlParams);
852
            $urlParams = $override ? array_merge($queryUrlParams, $addParams) : array_merge($addParams,
853
                    $queryUrlParams);
854
        } else {
855
            $urlParams = $addParams;
856
        }
857
858
        if (!empty($urlParams)) {
859
            $urlFinal .= '?';
860 3
            if (is_array($urlParams)) {
861
                $urlFinal .= http_build_query($urlParams);
862
            } else {
863
                $urlFinal .= $urlParams;
864
            }
865
        }
866
        return $urlFinal;
867
    }
868
869
    /**
870
     * Add Default Url params to given url if not overrided
871
     *
872
     * @param string $urlRaw
873
     *
874
     * @return string url with default params added
875
     */
876
    public function addDefaultUrlParams($urlRaw)
877
    {
878
        return $this->addUrlParams($urlRaw, $this->defaultUrlParams, false);
879
    }
880
881
    /**
882
     * Funkce, která provede I/O operaci a vyhodnotí výsledek.
883
     *
884
     * @param string $urlSuffix část URL za identifikátorem firmy.
885
     * @param string $method    HTTP/REST metoda
886
     * @param string $format    Requested format
887
     * 
888
     * @return array|boolean Výsledek operace
889
     */
890 3
    public function performRequest($urlSuffix = null, $method = 'GET',
891
                                   $format = null)
892 3
    {
893 3
        $this->rowCount      = null;
894 3
        $this->responseStats = [];
895 3
896
        if (preg_match('/^http/', $urlSuffix)) {
897 3
            $url = $urlSuffix;
898
        } elseif (strlen($urlSuffix) && ($urlSuffix[0] == '/')) {
899 3
            $url = $this->url.$urlSuffix;
900
        } else {
901 3
            $url = $this->evidenceUrlWithSuffix($urlSuffix);
902
        }
903 3
904
        $responseCode = $this->doCurlRequest($this->addDefaultUrlParams($url),
905 3
            $method, $format);
906 3
907 3
        return $this->parseResponse($this->rawResponseToArray($this->lastCurlResponse,
908 3
                    $this->responseFormat), $responseCode);
909 3
    }
910 3
911 3
    /**
912 3
     * Parse Raw FlexiBee response in several formats
913 3
     *
914 3
     * @param string $responseRaw raw response body
915 3
     * @param string $format      Raw Response format json|xml|etc
916 3
     *
917 3
     * @return array
918
     */
919 3
    public function rawResponseToArray($responseRaw, $format)
920
    {
921
        $responseDecoded = [];
922 3
        if (!empty(trim($responseRaw))) {
923 3
            switch ($format) {
924 3
                case 'json':
925 3
                    $responseDecoded = $this->rawJsonToArray($responseRaw);
926 3
                    break;
927 3
                case 'xml':
928 3
                    $responseDecoded = $this->rawXmlToArray($this->lastCurlResponse);
929 3
                    break;
930 3
                case 'txt':
931
                default:
932
                    $responseDecoded = [$this->lastCurlResponse];
933
                    break;
934
            }
935 3
        }
936
        return $responseDecoded;
937
    }
938
939 3
    /**
940
     * Convert FlexiBee Response JSON to Array
941
     *
942
     * @param string $rawJson
943
     *
944
     * @return array
945
     */
946
    public function rawJsonToArray($rawJson)
947
    {
948
        $responseDecoded = json_decode($rawJson, true, 10);
949 23
        $decodeError     = json_last_error_msg();
950
        if ($decodeError == 'No error') {
951 23
            if (array_key_exists($this->nameSpace, $responseDecoded)) {
952 23
                $responseDecoded = $responseDecoded[$this->nameSpace];
953 23
            }
954 23
        } else {
955 15
            $this->addStatusMessage('JSON Decoder: '.$decodeError, 'error');
956 15
            $this->addStatusMessage($rawJson, 'debug');
957 15
        }
958 23
        return $responseDecoded;
959
    }
960
961
    /**
962
     * Convert FlexiBee Response XML to Array
963
     *
964
     * @param string $rawXML
965
     *
966
     * @return array
967
     */
968 23
    public function rawXmlToArray($rawXML)
969
    {
970 23
        return self::xml2array($rawXML);
971 23
    }
972 23
973 23
    /**
974 23
     * Parse Response array
975
     *
976 23
     * @param array $responseDecoded
977 23
     * @param int $responseCode Request Response Code
978 23
     *
979 23
     * @return array main data part of response
980 23
     */
981
    public function parseResponse($responseDecoded, $responseCode)
982 23
    {
983 23
        if (is_array($responseDecoded)) {
984 23
            $mainResult          = $this->unifyResponseFormat($responseDecoded);
985
            $this->responseStats = array_key_exists('stats', $responseDecoded) ? (isset($responseDecoded['stats'][0])
986
                    ? $responseDecoded['stats'][0] : $responseDecoded['stats']) : null;
987
        } else {
988
            $mainResult = $responseDecoded;
989
        }
990 1
        switch ($responseCode) {
991
            case 201: //Success Write
992 1
            case 200: //Success Read
993 1
                if (is_array($responseDecoded)) {
994 1
                    $this->lastResult = $mainResult;
995 1
                    if (isset($responseDecoded['@rowCount'])) {
996 1
                        $this->rowCount = (int) $responseDecoded['@rowCount'];
997
                    }
998
                    if (isset($responseDecoded['@globalVersion'])) {
999
                        $this->globalVersion = (int) $responseDecoded['@globalVersion'];
1000
                    }
1001 1
                }
1002
                break;
1003 1
1004 1
            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...
1005
                if ($this->debug === true) {
1006
                    $this->error500Reporter($responseDecoded);
1007
                }
1008
            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...
1009
                if ($this->ignoreNotFound === true) {
1010
                    break;
1011
                }
1012
            case 400: //Bad Request parameters
1013 23
            default: //Something goes wrong
1014
                $this->addStatusMessage($this->lastResponseCode.': '.$this->curlInfo['url'],
1015 23
                    'warning');
1016 23
                if (is_array($responseDecoded)) {
1017 22
                    $this->parseError($responseDecoded);
1018
                }
1019
                $this->logResult($responseDecoded, $this->curlInfo['url']);
1020
                break;
1021 22
        }
1022
        return $mainResult;
1023
    }
1024
1025
    /**
1026
     * Parse error message response
1027
     *
1028
     * @param array $responseDecoded
1029
     * 
1030
     * @return int number of errors processed
1031
     */
1032
    public function parseError(array $responseDecoded)
1033
    {
1034
        if (array_key_exists('results', $responseDecoded)) {
1035
            $this->errors = $responseDecoded['results'][0]['errors'];
1036
            foreach ($this->errors as $errorInfo) {
1037
                $this->addStatusMessage($errorInfo['message'], 'error');
1038
                if (array_key_exists('for', $errorInfo)) {
1039
                    unset($errorInfo['message']);
1040
                    $this->addStatusMessage(json_encode($errorInfo), 'debug');                    
1041
                }
1042
            }
1043
        } else {
1044
            if (array_key_exists('message', $responseDecoded)) {
1045
                $this->errors = [['message' => $responseDecoded['message']]];
1046
            }
1047
        }
1048
        return count($this->errors);
1049
    }
1050
1051
    /**
1052
     * Vykonej HTTP požadavek
1053
     *
1054
     * @link https://www.flexibee.eu/api/dokumentace/ref/urls/ Sestavování URL
1055
     * @param string $url    URL požadavku
1056
     * @param string $method HTTP Method GET|POST|PUT|OPTIONS|DELETE
1057
     * @param string $format požadovaný formát komunikace
1058
     * 
1059 15
     * @return int HTTP Response CODE
1060
     */
1061 15
    public function doCurlRequest($url, $method, $format = null)
1062 15
    {
1063
        if (is_null($format)) {
1064 15
            $format = $this->format;
1065 8
        }
1066 7
        curl_setopt($this->curl, CURLOPT_URL, $url);
1067 7
// Nastavení samotné operace
1068 7
        curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, strtoupper($method));
1069
//Vždy nastavíme byť i prázná postdata jako ochranu před chybou 411
1070 8
        curl_setopt($this->curl, CURLOPT_POSTFIELDS, $this->postFields);
1071 1
1072 1
        $httpHeaders = $this->defaultHttpHeaders;
1073 8
1074
        $formats = Formats::bySuffix();
1075 15
1076 4
        if (!isset($httpHeaders['Accept'])) {
1077 4
            $httpHeaders['Accept'] = $formats[$format]['content-type'];
1078 4
        }
1079
        if (!isset($httpHeaders['Content-Type'])) {
1080
            $httpHeaders['Content-Type'] = $formats[$format]['content-type'];
1081
        }
1082
        $httpHeadersFinal = [];
1083 4
        foreach ($httpHeaders as $key => $value) {
1084
            if (($key == 'User-Agent') && ($value == 'FlexiPeeHP')) {
1085 15
                $value .= ' v'.self::$libVersion;
1086
            }
1087 15
            $httpHeadersFinal[] = $key.': '.$value;
1088 15
        }
1089
1090
        curl_setopt($this->curl, CURLOPT_HTTPHEADER, $httpHeadersFinal);
1091 15
1092
// Proveď samotnou operaci
1093 15
        $this->lastCurlResponse            = curl_exec($this->curl);
1094 15
        $this->curlInfo                    = curl_getinfo($this->curl);
1095 15
        $this->curlInfo['when']            = microtime();
1096
        $this->curlInfo['request_headers'] = $httpHeadersFinal;
1097 15
        $this->responseFormat              = isset($this->curlInfo['content_type'])
1098
                ? Formats::contentTypeToSuffix($this->curlInfo['content_type']) : 'txt';
1099 15
        $this->lastResponseCode            = $this->curlInfo['http_code'];
1100 15
        $this->lastCurlError               = curl_error($this->curl);
1101 15
        if (strlen($this->lastCurlError)) {
1102 9
            $this->addStatusMessage(sprintf('Curl Error (HTTP %d): %s',
1103 9
                    $this->lastResponseCode, $this->lastCurlError), 'error');
1104 6
        }
1105 6
1106 9
        if ($this->debug === true) {
1107 6
            $this->saveDebugFiles();
1108
        }
1109
1110 15
        return $this->lastResponseCode;
1111
    }
1112
1113
    /**
1114
     * Nastaví druh prováděné akce.
1115
     *
1116
     * @link https://demo.flexibee.eu/devdoc/actions Provádění akcí
1117
     * @param string $action
1118
     * 
1119
     * @return boolean
1120
     */
1121 23
    public function setAction($action)
1122
    {
1123 23
        $result           = false;
1124 23
        $actionsAvailable = $this->getActionsInfo();
1125 23
        if (is_array($actionsAvailable) && array_key_exists($action,
1126 23
                $actionsAvailable)) {
1127 23
            $this->action = $action;
1128
            $result       = true;
1129
        }
1130
        return $result;
1131 23
    }
1132
1133
    /**
1134
     * Convert XML to array.
1135 23
     *
1136 22
     * @param string $xml
1137 22
     *
1138 9
     * @return array
1139 9
     */
1140 22
    public static function xml2array($xml)
1141
    {
1142
        $arr = [];
1143
        if (!empty($xml)) {
1144
            if (is_string($xml)) {
1145
                $xml = simplexml_load_string($xml);
1146
            }
1147
            foreach ($xml->attributes() as $a) {
1148
                $arr['@'.$a->getName()] = strval($a);
1149
            }
1150
            foreach ($xml->children() as $r) {
1151 6
                if (count($r->children()) == 0) {
1152
                    $arr[$r->getName()] = strval($r);
1153
                } else {
1154 6
                    $arr[$r->getName()][] = self::xml2array($r);
1155 6
                }
1156 6
            }
1157 6
        }
1158 6
        return $arr;
1159
    }
1160 6
1161
    /**
1162
     * Odpojení od FlexiBee.
1163
     */
1164
    public function disconnect()
1165 6
    {
1166
        if (is_resource($this->curl)) {
1167
            curl_close($this->curl);
1168
        }
1169 6
        $this->curl = null;
1170
    }
1171
1172
    /**
1173
     * Disconnect CURL befere pass away
1174
     */
1175
    public function __destruct()
1176
    {
1177 16
        $this->disconnect();
1178
    }
1179 16
1180 9
    /**
1181 9
     * Načte řádek dat z FlexiBee.
1182 16
     *
1183 16
     * @param int $recordID id požadovaného záznamu
1184 16
     *
1185
     * @return array
1186 16
     */
1187 16
    public function getFlexiRow($recordID)
1188 16
    {
1189 15
        $record   = null;
1190 15
        $response = $this->performRequest($this->evidence.'/'.$recordID.'.json');
1191
        if (isset($response[$this->evidence])) {
1192
            $record = $response[$this->evidence][0];
1193
        }
1194
1195
        return $record;
1196
    }
1197
1198
    /**
1199 15
     * Oddělí z pole podmínek ty jenž patří za ? v URL požadavku
1200
     *
1201
     * @link https://www.flexibee.eu/api/dokumentace/ref/urls/ Sestavování URL
1202 15
     * @param array $conditions pole podmínek   - rendrují se do ()
1203 10
     * @param array $urlParams  pole parametrů  - rendrují za ?
1204 10
     */
1205 15
    public function extractUrlParams(&$conditions, &$urlParams)
1206 15
    {
1207 15
        foreach ($this->urlParams as $urlParam) {
1208 15
            if (isset($conditions[$urlParam])) {
1209
                \Ease\Sand::divDataArray($conditions, $urlParams, $urlParam);
1210 14
            }
1211 14
        }
1212 14
    }
1213 14
1214 10
    /**
1215
     * convert unicode to entities for use with FlexiBee queries
1216 14
     *
1217 14
     * @param string $urlRaw
1218
     * 
1219
     * @return string
1220
     */
1221
    public static function urlEncode($urlRaw)
1222
    {
1223
        return str_replace(['%27', '%3A'], ["'", ':'], rawurlencode($urlRaw));
1224
    }
1225
1226
    /**
1227
     * Načte data z FlexiBee.
1228
     *
1229
     * @param string $suffix     dotaz
1230
     * @param string|array $conditions Volitelný filtrovací výraz
1231
     *
1232
     * @return array Data obtained
1233
     */
1234
    public function getFlexiData($suffix = null, $conditions = null)
1235
    {
1236
        $finalUrl  = '';
1237
        $urlParams = $this->defaultUrlParams;
1238
1239
        if (!empty($conditions)) {
1240
            if (is_array($conditions)) {
1241
                $this->extractUrlParams($conditions, $urlParams);
1242
                $conditions = $this->flexiUrl($conditions);
1243
            }
1244
1245
            if (strlen($conditions) && ($conditions[0] != '/')) {
1246
                $conditions = '('.self::urlEncode($conditions).')';
1247
            }
1248
        }
1249
1250
        if (strlen($suffix)) {
1251
            if (preg_match('/^http/', $suffix) || ($suffix[0] == '/') || is_numeric($suffix)) {
1252 15
                $finalUrl = $suffix;
1253
            } else {
1254
                if (preg_match('/^(code|ext):(.*)/', $suffix, $matches)) {
1255 15
                    $finalUrl = $matches[1].':'.rawurlencode($matches[2]);
1256 15
                }
1257 15
            }
1258
        }
1259 15
1260 15
        $finalUrl .= $conditions;
1261 15
1262 15
        if (count($urlParams)) {
1263 15
            if (strstr($finalUrl, '?')) {
1264 15
                $finalUrl .= '&';
1265 15
            } else {
1266 15
                $finalUrl .= '?';
1267
            }
1268 15
            $finalUrl .= http_build_query($urlParams, null, '&',
1269
                PHP_QUERY_RFC3986);
1270
        }
1271 15
1272
        $transactions = $this->performRequest($finalUrl, 'GET');
1273
1274 15
        $responseEvidence = $this->getResponseEvidence();
1275 15
        if (is_array($transactions) && array_key_exists($responseEvidence,
1276 15
                $transactions)) {
1277 15
            $result = $transactions[$responseEvidence];
1278 15
            if ((count($result) == 1) && (count(current($result)) == 0 )) {
1279
                $result = null; // Response is empty Array
1280 15
            }
1281
        } else {
1282 15
            $result = $transactions;
1283
        }
1284 15
1285 9
        return $result;
1286 9
    }
1287
1288 15
    /**
1289
     * Načte záznam z FlexiBee a uloží v sobě jeho data
1290
     * Read FlexiBee record and store it inside od object
1291
     *
1292
     * @param int $id ID or conditions
1293
     *
1294
     * @return int počet načtených položek
1295
     */
1296
    public function loadFromFlexiBee($id = null)
1297
    {
1298
        $data = [];
1299 23
        if (is_null($id)) {
1300
            $id = $this->getMyKey();
1301 23
        }
1302
        if (is_array($id)) {
1303 23
            $id = rawurlencode('('.self::flexiUrl($id).')');
1304 23
        } else if (preg_match('/^ext:/', $id)) {
1305 23
            $id = self::urlEncode($id);
1306
        } else if (preg_match('/^code:/', $id)) {
1307 23
            $id = self::code(rawurlencode(self::uncode($id)));
1308 23
        }
1309 23
1310
        $flexidata    = $this->getFlexiData($this->getEvidenceUrl().'/'.$id);
1311 23
        $this->apiURL = $this->curlInfo['url'];
1312 23
        if (is_array($flexidata) && (count($flexidata) == 1)) {
1313 23
            $data = current($flexidata);
1314 23
        }
1315 23
        return $this->takeData($data);
1316 23
    }
1317 23
1318 23
    /**
1319 23
     * Set Filter code for requests
1320 23
     *
1321
     * @link https://www.flexibee.eu/api/dokumentace/ref/zamykani-odemykani/
1322
     *
1323
     * @param array|string $filter filter formula or ['key'=>'value']
1324 23
     *
1325 23
     * @return string Filter code
1326 23
     */
1327
    public function setFilter($filter)
1328 23
    {
1329 23
        return $this->filter = is_array($filter) ? self::flexiUrl($filter) : $filter;
1330 23
    }
1331 23
1332
    /**
1333
     * Převede data do Json formátu pro FlexiBee.
1334 23
     * Convert data to FlexiBee like Json format
1335 23
     *
1336 23
     * @url https://www.flexibee.eu/api/dokumentace/ref/actions/
1337 23
     * @url https://www.flexibee.eu/api/dokumentace/ref/zamykani-odemykani/
1338 23
     *
1339 23
     * @param array $data    object data
1340 23
     * @param int   $options json_encode options like JSON_PRETTY_PRINT etc
1341 23
     *
1342 23
     * @return string
1343 23
     */
1344 23
    public function getJsonizedData($data = null, $options = 0)
1345 23
    {
1346
        if (is_null($data)) {
1347 23
            $data = $this->getData();
1348 23
        }
1349
1350 23
        $dataToJsonize = array_merge(['@version' => $this->protoVersion],
1351
            $this->getDataForJSON($data));
1352
        $jsonRaw       = json_encode([$this->nameSpace => $dataToJsonize],
1353
            $options);
1354
1355
        return $jsonRaw;
1356
    }
1357
1358
    /**
1359
     * Get Data Fragment specific for current object
1360 23
     *
1361
     * @param array $data
1362 23
     *
1363 23
     * @return array
1364 23
     */
1365
    public function getDataForJSON($data = null)
1366
    {
1367 23
        if (is_null($data)) {
1368 23
            $data = $this->getData();
1369 23
        }
1370 23
1371 23
        $dataForJson = [$this->getEvidence() => $this->objectToID($data)];
1372
1373
        if (!is_null($this->action)) {
1374 23
            $dataForJson[$this->evidence.'@action'] = $this->action;
1375 23
            $this->action                           = null;
1376 23
        }
1377
1378 23
        if (!is_null($this->filter)) {
1379 23
            $dataForJson[$this->evidence.'@filter'] = $this->filter;
1380 23
        }
1381 23
1382 23
1383
        foreach ($this->chained as $chained) {
1384 23
            $chainedData = $chained->getDataForJSON();
1385 23
            foreach ($chainedData as $chainedItemEvidence => $chainedItemData) {
1386 23
                if (array_key_exists($chainedItemEvidence, $dataForJson)) {
1387 23
                    if (is_string(key($dataForJson[$chainedItemEvidence]))) {
1388 23
                        $dataBackup                          = $dataForJson[$chainedItemEvidence];
1389
                        $dataForJson[$chainedItemEvidence]   = [];
1390 23
                        $dataForJson[$chainedItemEvidence][] = $dataBackup;
1391 23
                    }
1392 23
                    if (array_key_exists(0, $chainedItemData)) {
1393 23
                        foreach ($chainedItemData as $chainedItem) {
1394
                            $dataForJson[$chainedItemEvidence][] = $chainedItem;
1395
                        }
1396 23
                    } else {
1397
                        $dataForJson[$chainedItemEvidence][] = $chainedItemData;
1398
                    }
1399 23
                } else {
1400
                    $dataForJson[$chainedItemEvidence] = $chainedItemData;
1401
                }
1402 23
            }
1403 23
        }
1404 23
1405 23
1406 23
        return $dataForJson;
1407 23
    }
1408
1409
    /**
1410
     * Join another FlexiPeeHP Object
1411
     *
1412
     * @param FlexiBeeRO $object
1413
     *
1414
     * @return boolean adding to stack success
1415
     */
1416
    public function join(&$object)
1417
    {
1418
        $result = true;
1419
        if (method_exists($object, 'getDataForJSON')) {
1420
            $this->chained[] = $object;
1421
        } else {
1422
            throw new \Ease\Exception('$object->getDataForJSON() does not exist');
1423
        }
1424
1425
        return $result;
1426
    }
1427
1428
    /**
1429
     * Test if given record ID exists in FlexiBee.
1430
     *
1431
     * @param mixed $identifer presence state
1432
     *
1433
     * @return boolean
1434
     */
1435
    public function idExists($identifer = null)
1436
    {
1437
        if (is_null($identifer)) {
1438
            $identifer = $this->getMyKey();
1439
        }
1440
        $ignorestate = $this->ignore404();
1441
        $this->ignore404(true);
1442
        $this->getFlexiData(null,
1443
            [
1444 23
                'detail' => 'custom:'.$this->getKeyColumn(),
1445
                $this->getKeyColumn() => $identifer
1446 23
        ]);
1447
        $this->ignore404($ignorestate);
1448 23
        return $this->lastResponseCode == 200;
1449 23
    }
1450 23
1451 23
    /**
1452 23
     * Test if given record exists in FlexiBee.
1453 23
     *
1454 23
     * @param array|string|int $data ext:id:23|code:ITEM|['id'=>23]|23
1455 23
     * 
1456 23
     * @return boolean Record presence status
1457
     */
1458 23
    public function recordExists($data = [])
1459 23
    {
1460 23
1461 23
        if (empty($data)) {
1462 23
            $data = $this->getData();
1463
        }
1464
        $ignorestate = $this->ignore404();
1465 23
        $this->ignore404(true);
1466 23
        $keyColumn   = $this->getKeyColumn();
1467
        $res         = $this->getColumnsFromFlexibee([$keyColumn],
1468
            is_array($data) ? $data : [$keyColumn => $data]);
1469 23
1470
        if (!count($res) || (isset($res['success']) && ($res['success'] == 'false'))
1471 23
            || ((isset($res) && is_array($res)) && !isset($res[0]) )) {
1472 23
            $found = false;
1473
        } else {
1474 23
            $found = true;
1475
        }
1476
        $this->ignore404($ignorestate);
1477 23
        return $found;
1478 23
    }
1479
1480
    /**
1481
     * Vrací z FlexiBee sloupečky podle podmínek.
1482
     *
1483
     * @param array|int|string $conditions pole podmínek nebo ID záznamu
1484
     * @param string           $indexBy    klice vysledku naplnit hodnotou ze
1485
     *                                     sloupečku
1486
     * @return array
1487
     */
1488
    public function getAllFromFlexibee($conditions = null, $indexBy = null)
1489 65
    {
1490
        if (is_int($conditions)) {
1491 65
            $conditions = [$this->getmyKeyColumn() => $conditions];
0 ignored issues
show
Bug introduced by
The method getmyKeyColumn() does not exist on FlexiPeeHP\FlexiBeeRO. Did you maybe mean getMyKey()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
1492 65
        }
1493
1494
        $flexiData = $this->getFlexiData('', $conditions);
1495 65
1496 65
        if (!is_null($indexBy)) {
1497
            $flexiData = $this->reindexArrayBy($flexiData);
1498
        }
1499
1500
        return $flexiData;
1501 65
    }
1502
1503
    /**
1504
     * Vrací z FlexiBee sloupečky podle podmínek.
1505
     *
1506
     * @param string[] $columnsList seznam položek
1507
     * @param array    $conditions  pole podmínek nebo ID záznamu
1508
     * @param string   $indexBy     Sloupeček podle kterého indexovat záznamy
1509
     *
1510
     * @return array
1511 71
     */
1512
    public function getColumnsFromFlexibee($columnsList, $conditions = [],
1513 71
                                           $indexBy = null)
1514
    {
1515
        $detail = 'full';
1516
        switch (gettype($columnsList)) {
1517
            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...
1518
                $conditions = [$this->getmyKeyColumn() => $conditions];
0 ignored issues
show
Bug introduced by
The method getmyKeyColumn() does not exist on FlexiPeeHP\FlexiBeeRO. Did you maybe mean getMyKey()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
1519
            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...
1520
                if (!is_null($indexBy) && !array_key_exists($indexBy,
1521
                        $columnsList)) {
1522 23
                    $columnsList[] = $indexBy;
1523
                }
1524 23
                $columns = implode(',', array_unique($columnsList));
1525
                $detail  = 'custom:'.$columns;
1526
            default:
1527
                switch ($columnsList) {
1528
                    case 'id':
1529
                        $detail = 'id';
1530
                        break;
1531
                    case 'summary':
1532 15
                        $detail = 'summary';
1533
                        break;
1534 15
                    default:
1535 15
                        break;
1536 15
                }
1537 15
                break;
1538 15
        }
1539 9
1540 9
        $conditions['detail'] = $detail;
1541 15
1542
        $flexiData = $this->getFlexiData(null, $conditions);
1543
1544
        if (is_string($indexBy) && count($flexiData) && is_array(current($flexiData))
1545
            && array_key_exists($indexBy, current($flexiData))) {
1546
            $flexiData = $this->reindexArrayBy($flexiData, $indexBy);
1547
        }
1548
1549
        return $flexiData;
1550 23
    }
1551
1552 23
    /**
1553 23
     * Vrací kód záznamu.
1554 23
     * Obtain record CODE
1555 23
     *
1556 23
     * @param mixed $data
1557 23
     *
1558 23
     * @return string
1559 23
     */
1560 23
    public function getKod($data = null, $unique = true)
1561 23
    {
1562 23
        $kod = null;
1563 23
1564 23
        if (is_null($data)) {
1565 23
            $data = $this->getData();
1566
        }
1567 23
1568
        if (is_string($data)) {
1569
            $data = [$this->nameColumn => $data];
1570
        }
1571
1572
        if (isset($data['kod'])) {
1573
            $kod = $data['kod'];
1574
        } else {
1575
            if (isset($data[$this->nameColumn])) {
1576
                $kod = preg_replace('/[^a-zA-Z0-9]/', '',
1577 22
                    \Ease\Sand::rip($data[$this->nameColumn]));
1578
            } else {
1579 22
                if (isset($data[$this->keyColumn])) {
1580
                    $kod = \Ease\Sand::rip($data[$this->keyColumn]);
1581 21
                }
1582
            }
1583
            $kod = substr($kod, 0, 20);
1584
        }
1585
1586
        if (!strlen($kod)) {
1587
            $kod = 'NOTSET';
1588
        }
1589 22
1590
        if (strlen($kod) > 18) {
1591 22
            $kodfinal = strtoupper(substr($kod, 0, 18));
1592 22
        } else {
1593 22
            $kodfinal = strtoupper($kod);
1594
        }
1595
1596 22
        if ($unique) {
1597
            $counter = 0;
1598
            if (count($this->codes)) {
1599
                foreach ($this->codes as $codesearch => $keystring) {
1600
                    if (strstr($codesearch, $kodfinal)) {
1601
                        ++$counter;
1602
                    }
1603
                }
1604
            }
1605 22
            if ($counter) {
1606
                $kodfinal = $kodfinal.$counter;
1607 22
            }
1608 22
1609 22
            $this->codes[$kodfinal] = $kod;
1610 22
        }
1611 22
1612 22
        return self::code($kodfinal);
1613 22
    }
1614 22
1615 22
    /**
1616 22
     * Write Operation Result.
1617 22
     *
1618 22
     * @param array  $resultData
1619
     * @param string $url        URL
1620 22
     * 
1621
     * @return boolean Log save success
1622
     */
1623
    public function logResult($resultData = null, $url = null)
1624
    {
1625
        $logResult = false;
1626
        if (isset($resultData['success']) && ($resultData['success'] == 'false')) {
1627
            if (isset($resultData['message'])) {
1628
                $this->addStatusMessage($resultData['message'], 'warning');
1629
            }
1630
            $this->addStatusMessage('Error '.$this->lastResponseCode.': '.urldecode($url),
1631
                'warning');
1632 22
            unset($url);
1633
        }
1634
        if (is_null($resultData)) {
1635
            $resultData = $this->lastResult;
1636
        }
1637
        if (isset($url)) {
1638
            $this->logger->addStatusMessage($this->lastResponseCode.':'.urldecode($url));
1639
        }
1640
1641 23
        if (isset($resultData['results'])) {
1642
            if ($resultData['success'] == 'false') {
1643 23
                $status = 'error';
1644 23
            } else {
1645 23
                $status = 'success';
1646 23
            }
1647 16
            foreach ($resultData['results'] as $result) {
1648 16
                if (isset($result['request-id'])) {
1649 23
                    $rid = $result['request-id'];
1650
                } else {
1651
                    $rid = '';
1652
                }
1653
                if (isset($result['errors'])) {
1654
                    foreach ($result['errors'] as $error) {
1655
                        $message = $error['message'];
1656
                        if (isset($error['for'])) {
1657
                            $message .= ' for: '.$error['for'];
1658 23
                        }
1659
                        if (isset($error['value'])) {
1660 23
                            $message .= ' value:'.$error['value'];
1661 23
                        }
1662 23
                        if (isset($error['code'])) {
1663 23
                            $message .= ' code:'.$error['code'];
1664 23
                        }
1665 23
                        $this->addStatusMessage($rid.': '.$message, $status);
1666 23
                    }
1667 23
                }
1668 23
            }
1669
        }
1670
        return $logResult;
1671
    }
1672
1673
    /**
1674
     * Save RAW Curl Request & Response to files in Temp directory
1675
     */
1676
    public function saveDebugFiles()
1677 23
    {
1678
        $tmpdir   = sys_get_temp_dir();
1679 23
        $fname    = $this->evidence.'-'.$this->curlInfo['when'].'.'.$this->format;
1680 23
        $reqname  = $tmpdir.'/request-'.$fname;
1681 23
        $respname = $tmpdir.'/response-'.$fname;
1682 23
        file_put_contents($reqname, $this->postFields);
1683 23
        file_put_contents($respname, $this->lastCurlResponse);
1684 23
    }
1685 13
1686 13
    /**
1687 23
     * Připraví data pro odeslání do FlexiBee
1688
     *
1689
     * @param string $data
1690
     */
1691
    public function setPostFields($data)
1692
    {
1693
        $this->postFields = $data;
1694
    }
1695
1696 23
    /**
1697
     * Get Content ready to be send as POST body
1698 23
     * @return string
1699 23
     */
1700 23
    public function getPostFields()
1701 23
    {
1702 23
        return $this->postFields;
1703 16
    }
1704 16
1705 23
    /**
1706
     * Generuje fragment url pro filtrování.
1707
     *
1708
     * @see https://www.flexibee.eu/api/dokumentace/ref/filters
1709
     *
1710
     * @param array  $data
1711
     * @param string $joiner default and/or
1712
     * @param string $defop  default operator
1713
     *
1714 23
     * @return string
1715
     */
1716 23
    public static function flexiUrl(array $data, $joiner = 'and', $defop = 'eq')
1717 23
    {
1718 23
        $parts = [];
1719 23
1720 23
        foreach ($data as $column => $value) {
1721 16
            if (!is_numeric($column)) {
1722 16
                if (is_integer($data[$column]) || is_float($data[$column])) {
1723 23
                    $parts[$column] = $column.' eq \''.$data[$column].'\'';
1724
                } elseif (is_bool($data[$column])) {
1725
                    $parts[$column] = $data[$column] ? $column.' eq true' : $column.' eq false';
1726
                } elseif (is_null($data[$column])) {
1727
                    $parts[$column] = $column." is null";
1728
                } else {
1729
                    switch ($value) {
1730
                        case '!null':
1731 23
                            $parts[$column] = $column." is not null";
1732
                            break;
1733 23
                        case 'is empty':
1734 1
                        case 'is not empty':
1735 1
                            $parts[$column] = $column.' '.$value;
1736 23
                            break;
1737 23
                        default:
1738
                            if ($column == 'stitky') {
1739
                                $parts[$column] = $column."='".self::code($data[$column])."'";
1740
                            } else {
1741
                                $parts[$column] = $column." $defop '".$data[$column]."'";
1742
                            }
1743
                            break;
1744 20
                    }
1745
                }
1746 20
            } else {
1747 20
                $parts[] = $value;
1748 20
            }
1749 20
        }
1750
        return implode(' '.$joiner.' ', $parts);
1751
    }
1752
1753
    /**
1754
     * Obtain record/object numeric identificator id:
1755 20
     * Vrací číselný identifikátor objektu id:
1756
     *
1757
     * @link https://demo.flexibee.eu/devdoc/identifiers Identifikátory záznamů
1758
     *
1759
     * @return null|int indentifikátor záznamu reprezentovaného objektem
1760
     */
1761
    public function getRecordID()
1762
    {
1763
        $id = $this->getDataValue('id');
1764
        return is_null($id) ? null : is_numeric($id) ? intval($id) : $id;
1765
    }
1766
1767
    /**
1768
     * Obtain record/object identificator code:
1769
     * Vrací identifikátor objektu code:
1770
     *
1771
     * @link https://demo.flexibee.eu/devdoc/identifiers Identifikátory záznamů
1772
     *
1773
     * @return string record code identifier
1774
     */
1775
    public function getRecordCode()
1776
    {
1777
        return empty($this->getDataValue('kod')) ? null : self::code($this->getDataValue('kod'));
1778
    }
1779
1780
    /**
1781
     * Obtain record/object identificator extId: code: or id:
1782
     * Vrací identifikátor objektu extId: code: nebo id:
1783
     *
1784
     * @link https://demo.flexibee.eu/devdoc/identifiers Identifikátory záznamů
1785
     *
1786
     * @return string|int|null record code identifier
1787
     */
1788
    public function getRecordIdent()
1789
    {
1790
        $ident = $this->getExternalID();
1791
        if (empty($ident)) {
1792
            $ident = $this->getRecordCode();
1793
        }
1794
        if (empty($ident)) {
1795
            $ident = $this->getRecordID();
1796
        }
1797
        return $ident;
1798
    }
1799
1800
    /**
1801
     * Obtain record/object identificator code: or id:
1802
     * Vrací identifikátor objektu code: nebo id:
1803
     *
1804
     * @link https://demo.flexibee.eu/devdoc/identifiers Identifikátory záznamů
1805
     * 
1806
     * @return string indentifikátor záznamu reprezentovaného objektem
1807
     */
1808
    public function __toString()
1809
    {
1810
        return strval($this->getRecordIdent());
1811
    }
1812
1813
    /**
1814
     * Gives you FlexiPeeHP class name for Given Evidence
1815
     *
1816
     * @param string $evidence
1817
     * 
1818
     * @return string Class name
1819
     */
1820
    public static function evidenceToClassName($evidence)
1821
    {
1822
        return str_replace(' ', '', ucwords(str_replace('-', ' ', $evidence)));
1823
    }
1824
1825
    /**
1826
     * Obtain ID of first record in evidence
1827
     *
1828
     * @return string|null id or null if no records
1829
     */
1830
    public function getFirstRecordID()
1831
    {
1832
        $firstID    = null;
1833
        $keyColumn  = $this->getKeyColumn();
1834
        $firstIdRaw = $this->getColumnsFromFlexibee([$keyColumn],
1835
            ['limit' => 1, 'order' => $keyColumn], $keyColumn);
1836
        if (!empty($firstIdRaw) && isset(current($firstIdRaw)[$keyColumn])) {
1837
            $firstID = current($firstIdRaw)[$keyColumn];
1838
        }
1839
        return is_numeric($firstID) ? intval($firstID) : $firstID;
1840
    }
1841
1842
    /**
1843
     * Vrací hodnotu daného externího ID
1844
     *
1845 23
     * @param string $want Namespace Selector. If empty,you obtain the first one.
1846
     * 
1847 23
     * @return string|array one id or array if multiplete
1848
     */
1849
    public function getExternalID($want = null)
1850
    {
1851
        $extid = null;
1852
        $ids   = $this->getDataValue('external-ids');
1853
        if (is_null($want)) {
1854
            if (!empty($ids)) {
1855
                $extid = current($ids);
1856
            }
1857 23
        } else {
1858
            if (!is_null($ids) && is_array($ids)) {
1859 23
                foreach ($ids as $id) {
1860
                    if (strstr($id, 'ext:'.$want)) {
1861
                        if (is_null($extid)) {
1862
                            $extid = str_replace('ext:'.$want.':', '', $id);
1863
                        } else {
1864
                            if (is_array($extid)) {
1865
                                $extid[] = str_replace('ext:'.$want.':', '', $id);
1866
                            } else {
1867
                                $extid = [$extid, str_replace('ext:'.$want.':',
1868
                                        '', $id)];
1869
                            }
1870
                        }
1871
                    }
1872
                }
1873
            }
1874
        }
1875
        return $extid;
1876
    }
1877
1878
    /**
1879
     * Obtain actual GlobalVersion
1880
     * Vrací aktuální globální verzi změn
1881
     *
1882
     * @link https://www.flexibee.eu/api/dokumentace/ref/changes-api#globalVersion Globální Verze
1883
     * 
1884
     * @return type
1885
     */
1886
    public function getGlobalVersion()
1887
    {
1888
        $this->getFlexiData(null, ['add-global-version' => 'true', 'limit' => 1]);
1889
1890
        return $this->globalVersion;
1891
    }
1892
1893
    /**
1894
     * Gives you current ApiURL with given format suffix
1895
     * 
1896
     * @param string $format json|html|xml|...
1897
     * 
1898
     * @return string API URL for current record or object/evidence
1899
     */
1900
    public function getApiURL($format = null)
1901
    {
1902
        $apiUrl = str_replace(['.'.$this->format, '?limit=0'], '', $this->apiURL);
1903
        return $apiUrl.(empty($format) ? '' : '.'.$format );
1904
    }
1905
1906
    /**
1907
     * Obtain content type of last response
1908
     *
1909
     * @return string
1910
     */
1911
    public function getResponseFormat()
1912
    {
1913
        if (isset($this->curlInfo['content_type'])) {
1914
            $responseFormat = $this->curlInfo['content_type'];
1915
        } else {
1916
            $responseFormat = null;
1917
        }
1918
        return $responseFormat;
1919
    }
1920
1921
    /**
1922
     * Return the same response format for one and multiplete results
1923
     *
1924
     * @param array $responseBody
1925
     * 
1926
     * @return array
1927
     */
1928
    public function unifyResponseFormat($responseBody)
1929
    {
1930
        if (!is_array($responseBody) || array_key_exists('message',
1931
                $responseBody)) { //Unifi response format
1932
            $response = $responseBody;
1933
        } else {
1934
            $evidence = $this->getResponseEvidence();
1935
            if (array_key_exists($evidence, $responseBody)) {
1936
                $response        = [];
1937
                $evidenceContent = $responseBody[$evidence];
1938
                if (array_key_exists(0, $evidenceContent)) {
1939
                    $response[$evidence] = $evidenceContent; //Multiplete Results
1940
                } else {
1941
                    $response[$evidence][0] = $evidenceContent; //One result
1942
                }
1943
            } else {
1944
                if (isset($responseBody['priloha'])) {
1945
                    $response = $responseBody['priloha'];
1946
                } else {
1947
                    if (array_key_exists('results', $responseBody)) {
1948
                        $response = $responseBody['results'];
1949
                    } else {
1950
                        $response = $responseBody;
1951
                    }
1952
                }
1953
            }
1954
        }
1955
        return $response;
1956
    }
1957
1958
    /**
1959
     * Obtain structure for current (or given) evidence
1960
     *
1961
     * @param string $evidence
1962
     * 
1963
     * @return array Evidence structure
1964
     */
1965
    public function getColumnsInfo($evidence = null)
1966
    {
1967
        $columnsInfo = null;
1968
        $infoSource  = self::$infoDir.'/Properties.'.(empty($evidence) ? $this->getEvidence()
1969
                : $evidence).'.json';
1970
        if (file_exists($infoSource)) {
1971
            $columnsInfo = json_decode(file_get_contents($infoSource), true);
1972
        }
1973
        return $columnsInfo;
1974
    }
1975
1976
    /**
1977
     * Gives you properties for (current) evidence column
1978
     *
1979
     * @param string $column    name of column
1980
     * @param string $evidence  evidence name if different
1981
     *
1982
     * @return array column properties or null if column not exits
1983
     */
1984
    public function getColumnInfo($column, $evidence = null)
1985
    {
1986
        $columnsInfo = $this->getColumnsInfo(empty($evidence) ? $this->getEvidence()
1987
                : $evidence);
1988
        return is_array($columnsInfo) ? array_key_exists($column, $columnsInfo) ? $columnsInfo[$column]
1989
                : null : null;
1990
    }
1991
1992
    /**
1993
     * Obtain actions for current (or given) evidence
1994
     *
1995
     * @param string $evidence
1996
     * 
1997
     * @return array Evidence structure
1998
     */
1999
    public function getActionsInfo($evidence = null)
2000
    {
2001
        $actionsInfo = null;
2002
        if (is_null($evidence)) {
2003
            $evidence = $this->getEvidence();
2004
        }
2005
        $propsName = lcfirst(FlexiBeeRO::evidenceToClassName($evidence));
2006
        if (isset(\FlexiPeeHP\Actions::$$propsName)) {
2007
            $actionsInfo = Actions::$$propsName;
2008
        }
2009
        return $actionsInfo;
2010
    }
2011
2012
    /**
2013
     * Obtain relations for current (or given) evidence
2014
     *
2015
     * @param string $evidence
2016
     * 
2017
     * @return array Evidence structure
2018
     */
2019
    public function getRelationsInfo($evidence = null)
2020
    {
2021
        $relationsInfo = null;
2022
        if (is_null($evidence)) {
2023
            $evidence = $this->getEvidence();
2024
        }
2025
        $propsName = lcfirst(FlexiBeeRO::evidenceToClassName($evidence));
2026
        if (isset(\FlexiPeeHP\Relations::$$propsName)) {
2027
            $relationsInfo = Relations::$$propsName;
2028
        }
2029
        return $relationsInfo;
2030
    }
2031
2032
    /**
2033
     * Obtain info for current (or given) evidence
2034
     *
2035 23
     * @param string $evidence
2036
     * 
2037 23
     * @return array Evidence info
2038 23
     */
2039 23
    public function getEvidenceInfo($evidence = null)
2040 23
    {
2041
        $evidencesInfo = null;
2042
        if (is_null($evidence)) {
2043
            $evidence = $this->getEvidence();
2044
        }
2045
        if (isset(EvidenceList::$evidences[$evidence])) {
2046
            $evidencesInfo = EvidenceList::$evidences[$evidence];
2047
        }
2048
        return $evidencesInfo;
2049
    }
2050
2051
    /**
2052
     * Obtain name for current (or given) evidence path
2053
     *
2054
     * @param string $evidence Evidence Path
2055
     * 
2056
     * @return array Evidence info
2057
     */
2058
    public function getEvidenceName($evidence = null)
2059
    {
2060
        $evidenceName = null;
2061
        if (is_null($evidence)) {
2062
            $evidence = $this->getEvidence();
2063
        }
2064
        if (isset(EvidenceList::$name[$evidence])) {
2065
            $evidenceName = EvidenceList::$name[$evidence];
2066
        }
2067
        return $evidenceName;
2068
    }
2069
2070
    /**
2071
     * Save current object to file
2072
     *
2073
     * @param string $destfile path to file
2074
     */
2075
    public function saveResponseToFile($destfile)
2076
    {
2077
        if (strlen($this->lastCurlResponse)) {
2078
            $this->doCurlRequest($this->apiURL, 'GET', $this->format);
2079
        }
2080
        file_put_contents($destfile, $this->lastCurlResponse);
2081
    }
2082
2083
    /**
2084
     * Obtain established relations listing
2085
     *
2086
     * @return array Null or Relations
2087
     */
2088
    public function getVazby($id = null)
2089
    {
2090
        if (is_null($id)) {
2091
            $id = $this->getRecordID();
2092
        }
2093
        if (!empty($id)) {
2094
            $vazbyRaw = $this->getColumnsFromFlexibee(['vazby'],
2095
                ['relations' => 'vazby', 'id' => $id]);
2096
            $vazby    = array_key_exists('vazby', $vazbyRaw[0]) ? $vazbyRaw[0]['vazby']
2097
                    : null;
2098
        } else {
2099
            throw new \Exception(_('ID requied to get record relations '));
2100
        }
2101
        return $vazby;
2102
    }
2103
2104
    /**
2105
     * Gives You URL for Current Record in FlexiBee web interface
2106
     *
2107
     * @return string url
2108
     */
2109
    public function getFlexiBeeURL()
2110
    {
2111
        $parsed_url = parse_url(str_replace('.'.$this->format, '', $this->apiURL));
2112
        $scheme     = isset($parsed_url['scheme']) ? $parsed_url['scheme'].'://'
2113
                : '';
2114
        $host       = isset($parsed_url['host']) ? $parsed_url['host'] : '';
2115
        $port       = isset($parsed_url['port']) ? ':'.$parsed_url['port'] : '';
2116
        $user       = isset($parsed_url['user']) ? $parsed_url['user'] : '';
2117
        $pass       = isset($parsed_url['pass']) ? ':'.$parsed_url['pass'] : '';
2118
        $pass       = ($user || $pass) ? "$pass@" : '';
2119
        $path       = isset($parsed_url['path']) ? $parsed_url['path'] : '';
2120
        return $scheme.$user.$pass.$host.$port.$path;
2121
    }
2122
2123
    /**
2124
     * Set Record Key
2125
     *
2126
     * @param int|string $myKeyValue
2127
     * 
2128
     * @return boolean
2129
     */
2130
    public function setMyKey($myKeyValue)
2131
    {
2132
        if (substr($myKeyValue, 0, 4) == 'ext:') {
2133
            $extIds = $this->getDataValue('external-ids');
2134
            if (count($extIds)) {
2135
                $extIds = array_combine($extIds, $extIds);
2136
            }
2137
            $extIds[$myKeyValue] = $myKeyValue;
2138
            $res                 = $this->setDataValue('external-ids', $extIds);
2139
        } else {
2140
            $res = parent::setMyKey($myKeyValue);
2141
        }
2142
        $this->updateApiURL();
2143
        return $res;
2144
    }
2145
2146
    /**
2147
     * Set or get ignore not found pages flag
2148
     *
2149
     * @param boolean $ignore set flag to
2150
     *
2151
     * @return boolean get flag state
2152
     */
2153
    public function ignore404($ignore = null)
2154
    {
2155
        if (!is_null($ignore)) {
2156
            $this->ignoreNotFound = $ignore;
2157
        }
2158
        return $this->ignoreNotFound;
2159
    }
2160
2161
    /**
2162
     * Send Document by mail
2163
     *
2164
     * @url https://www.flexibee.eu/api/dokumentace/ref/odesilani-mailem/
2165
     *
2166
     * @param string $to         Email ecipient
2167
     * @param string $subject    Email Subject
2168
     * @param string $body       Email Text
2169
     *
2170
     * @return int http response code
2171
     */
2172
    public function sendByMail($to, $subject, $body, $cc = null)
2173
    {
2174
        $this->setPostFields($body);
2175
2176
        $this->performRequest(rawurlencode($this->getRecordID()).'/odeslani-dokladu?to='.$to.'&subject='.urlencode($subject).'&cc='.$cc
2177
            , 'PUT', 'xml');
2178
2179
        return $this->lastResponseCode == 200;
2180
    }
2181
2182
    /**
2183
     * Send all unsent Documents by eMail
2184
     *
2185
     * @url https://www.flexibee.eu/api/dokumentace/ref/odesilani-mailem/
2186
     * 
2187
     * @return int http response code
2188
     */
2189
    public function sendUnsent()
2190
    {
2191
        return $this->doCurlRequest('automaticky-odeslat-neodeslane', 'PUT',
2192
                'xml');
2193
    }
2194
2195
    /**
2196
     * FlexiBee date to PHP DateTime conversion
2197
     *
2198
     * @param string $flexidate 2017-05-26+02:00
2199
     *
2200
     * @return \DateTime | false
2201
     */
2202
    public static function flexiDateToDateTime($flexidate)
2203
    {
2204
        return \DateTime::createFromFormat(self::$DateFormat.'O', $flexidate)->setTime(0,
2205
                0);
2206
    }
2207
2208
    /**
2209
     * FlexiBee dateTime to PHP DateTime conversion
2210
     *
2211
     * @param string $flexidatetime 2017-09-26T10:00:53.755+02:00 or older 2017-05-19T00:00:00+02:00
2212
     *
2213
     * @return \DateTime | false
2214
     */
2215
    public static function flexiDateTimeToDateTime($flexidatetime)
2216
    {
2217
        if (strchr($flexidatetime, '.')) { //NewFormat
2218
            $format = self::$DateTimeFormat;
2219
        } else { // Old format
2220
            $format = 'Y-m-d\TH:i:s+P';
2221
        }
2222
        return \DateTime::createFromFormat($format, $flexidatetime);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The expression \DateTime::createFromFor...ormat, $flexidatetime); of type DateTime|false adds false to the return on line 2222 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...
2223
    }
2224
2225
    /**
2226
     * Získá dokument v daném formátu
2227
     * Obtain document in given format
2228
     *
2229
     * @param string $format  pdf/csv/xml/json/ ...
2230
     * @param string $reportName Template used to generate PDF
2231
     *
2232
     * @return string|null filename downloaded or none
2233
     */
2234
    public function getInFormat($format, $reportName = null)
2235
    {
2236
        $response = null;
2237
        if ($this->setFormat($format)) {
2238
            $urlParams = [];
2239
            if (!empty($reportName)) {
2240
                $urlParams['report-name'] = $reportName;
2241
            }
2242
            if ($format == 'html') {
2243
                $urlParams['inDesktopApp'] = 'true';
2244
            }
2245
            if (($this->doCurlRequest($this->addUrlParams($this->apiURL,
2246
                        $urlParams), 'GET') == 200)) {
2247
                $response = $this->lastCurlResponse;
2248
            }
2249
        }
2250
        return $response;
2251
    }
2252
2253
    /**
2254
     * Uloží dokument v daném formátu do složky v systému souborů
2255
     * Save document in given format to directory in filesystem
2256
     *
2257
     * @param string $format  pdf/csv/xml/json/ ...
2258
     * @param string $destDir where to put file (prefix)
2259
     * @param string $reportName Template used to generate PDF
2260
     *
2261
     * @return string|null filename downloaded or none
2262
     */
2263
    public function downloadInFormat($format, $destDir = './',
2264
                                     $reportName = null)
2265
    {
2266
        $fileOnDisk   = null;
2267
        $formatBackup = $this->format;
2268
        if ($this->setFormat($format)) {
2269
            $downloadTo = $destDir.$this->getEvidence().'_'.$this->getMyKey().'.'.$format;
2270
            if (($this->doCurlRequest(empty($reportName) ? $this->apiURL : $this->addUrlParams($this->apiURL,
2271
                            ['report-name' => $reportName]), 'GET') == 200) && (file_put_contents($downloadTo,
2272
                    $this->lastCurlResponse) !== false)) {
2273
                $fileOnDisk = $downloadTo;
2274
            }
2275
            $this->setFormat($formatBackup);
2276
        }
2277
        return $fileOnDisk;
2278
    }
2279
2280
    /**
2281
     * Compile and send Report about Error500 to FlexiBee developers
2282
     * If FlexiBee is running on localost try also include java backtrace
2283
     *
2284
     * @param array $errorResponse result of parseError();
2285
     */
2286
    public function error500Reporter($errorResponse)
2287
    {
2288
        $ur = str_replace('/c/'.$this->company, '',
2289
            str_replace($this->url, '', $this->curlInfo['url']));
2290
        if (!array_key_exists($ur, $this->reports)) {
2291
            $tmpdir   = sys_get_temp_dir();
2292
            $myTime   = $this->curlInfo['when'];
2293
            $curlname = $tmpdir.'/curl-'.$this->evidence.'-'.$myTime.'.json';
2294
            file_put_contents($curlname,
2295
                json_encode($this->curlInfo, JSON_PRETTY_PRINT));
2296
2297
            $report = new \Ease\Mailer($this->reportRecipient,
2298
                'Error report 500 - '.$ur);
2299
2300
            $d     = dir($tmpdir);
2301
            while (false !== ($entry = $d->read())) {
2302
                if (strstr($entry, $myTime)) {
2303
                    $ext  = pathinfo($tmpdir.'/'.$entry, PATHINFO_EXTENSION);
2304
                    $mime = Formats::suffixToContentType($ext);
2305
                    $report->addFile($tmpdir.'/'.$entry,
2306
                        empty($mime) ? 'text/plain' : $mime);
2307
                }
2308
            }
2309
            $d->close();
2310
2311
            if ((strstr($this->url, '://localhost') || strstr($this->url,
2312
                    '://127.')) && file_exists('/var/log/flexibee.log')) {
2313
2314
                $fl = fopen('/var/log/'.'flexibee.log', 'r');
2315
                if ($fl) {
2316
                    $tracelog = [];
2317
                    for ($x_pos = 0, $ln = 0, $output = array(); fseek($fl,
2318
                            $x_pos, SEEK_END) !== -1; $x_pos--) {
2319
                        $char = fgetc($fl);
2320
                        if ($char === "\n") {
2321
                            $tracelog[] = $output[$ln];
2322
                            if (strstr($output[$ln], $errorResponse['message'])) {
2323
                                break;
2324
                            }
2325
                            $ln++;
2326
                            continue;
2327
                        }
2328
                        $output[$ln] = $char.((array_key_exists($ln, $output)) ? $output[$ln]
2329
                                : '');
2330
                    }
2331
2332
                    $trace     = implode("\n", array_reverse($tracelog));
2333
                    $tracefile = $tmpdir.'/trace-'.$this->evidence.'-'.$myTime.'.log';
2334
                    file_put_contents($tracefile, $trace);
2335
                    $report->addItem("\n\n".$trace);
2336
                    fclose($fl);
2337
                }
2338
            } else {
2339
                $report->addItem($errorResponse['message']);
2340
            }
2341
2342
            $licenseInfo = $this->performRequest($this->url.'/default-license.json');
2343
2344
            $report->addItem("\n\n".json_encode($licenseInfo['license'],
2345
                    JSON_PRETTY_PRINT));
2346
2347
            if ($report->send()) {
2348
                $this->reports[$ur] = $myTime;
2349
            }
2350
        }
2351
    }
2352
2353
    /**
2354
     * Returns code:CODE
2355
     *
2356
     * @param string $code
2357
     *
2358
     * @return string
2359
     */
2360
    public static function code($code)
2361
    {
2362
        return 'code:'.strtoupper(self::uncode($code));
2363
    }
2364
2365
    /**
2366
     * Returns CODE without code: prefix
2367
     *
2368
     * @param string $code
2369
     *
2370
     * @return string
2371
     */
2372
    public static function uncode($code)
2373
    {
2374
        return str_replace(['code:', 'code%3A'], '', $code);
2375
    }
2376
2377
    /**
2378
     * Remove all @ items from array
2379
     *
2380
     * @param array $data original data
2381
     *
2382
     * @return array data without @ columns
2383
     */
2384
    public static function arrayCleanUP($data)
2385
    {
2386
        return array_filter(
2387
            $data,
2388
            function ($key) {
2389
            return !strchr($key, '@');
2390
        }, ARRAY_FILTER_USE_KEY);
2391
    }
2392
2393
    /**
2394
     * Add Info about used user, server and libraries
2395
     *
2396
     * @param string $additions Additional note text
2397
     */
2398
    public function logBanner($additions = null)
2399
    {
2400
        $this->addStatusMessage('FlexiBee '.str_replace('://',
2401
                '://'.$this->user.'@', str_replace('.json', '', $this->apiURL)).' FlexiPeeHP v'.self::$libVersion.' (FlexiBee '.EvidenceList::$version.') EasePHP Framework v'.\Ease\Atom::$frameworkVersion.' '.$additions,
2402
            'debug');
2403
    }
2404
2405
    /**
2406
     * Reconnect After unserialization
2407
     */
2408
    public function __wakeup()
2409
    {
2410
        parent::__wakeup();
2411
        $this->curlInit();
2412
    }
2413
}
2414