Test Failed
Push — master ( b5725b...c73c28 )
by Vítězslav
02:40
created

FlexiBeeRO::getFlexiBeeURL()   C

Complexity

Conditions 9
Paths 256

Size

Total Lines 13
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 90

Importance

Changes 0
Metric Value
cc 9
eloc 11
nc 256
nop 0
dl 0
loc 13
ccs 0
cts 0
cp 0
crap 90
rs 6.4615
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,
0 ignored issues
show
Bug introduced by
It seems like $this->rawResponseToArra... $this->responseFormat) targeting FlexiPeeHP\FlexiBeeRO::rawResponseToArray() can also be of type string; however, FlexiPeeHP\FlexiBeeRO::parseResponse() does only seem to accept array, maybe add an additional type check?

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

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

An additional type check may prevent trouble.

Loading history...
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'].' "'. (array_keys('for', $errorInfo) ? $errorInfo['for'].'" = '.$errorInfo['value'] : '') ,
1038
                    'error');
1039
            }
1040
        } else {
1041
            if (array_key_exists('message', $responseDecoded)) {
1042
                $this->errors = [['message' => $responseDecoded['message']]];
1043
            }
1044
        }
1045
        return count($this->errors);
1046
    }
1047
1048
    /**
1049
     * Vykonej HTTP požadavek
1050
     *
1051
     * @link https://www.flexibee.eu/api/dokumentace/ref/urls/ Sestavování URL
1052
     * @param string $url    URL požadavku
1053
     * @param string $method HTTP Method GET|POST|PUT|OPTIONS|DELETE
1054
     * @param string $format požadovaný formát komunikace
1055
     * 
1056
     * @return int HTTP Response CODE
1057
     */
1058
    public function doCurlRequest($url, $method, $format = null)
1059 15
    {
1060
        if (is_null($format)) {
1061 15
            $format = $this->format;
1062 15
        }
1063
        curl_setopt($this->curl, CURLOPT_URL, $url);
1064 15
// Nastavení samotné operace
1065 8
        curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, strtoupper($method));
1066 7
//Vždy nastavíme byť i prázná postdata jako ochranu před chybou 411
1067 7
        curl_setopt($this->curl, CURLOPT_POSTFIELDS, $this->postFields);
1068 7
1069
        $httpHeaders = $this->defaultHttpHeaders;
1070 8
1071 1
        $formats = Formats::bySuffix();
1072 1
1073 8
        if (!isset($httpHeaders['Accept'])) {
1074
            $httpHeaders['Accept'] = $formats[$format]['content-type'];
1075 15
        }
1076 4
        if (!isset($httpHeaders['Content-Type'])) {
1077 4
            $httpHeaders['Content-Type'] = $formats[$format]['content-type'];
1078 4
        }
1079
        $httpHeadersFinal = [];
1080
        foreach ($httpHeaders as $key => $value) {
1081
            if (($key == 'User-Agent') && ($value == 'FlexiPeeHP')) {
1082
                $value .= ' v'.self::$libVersion;
1083 4
            }
1084
            $httpHeadersFinal[] = $key.': '.$value;
1085 15
        }
1086
1087 15
        curl_setopt($this->curl, CURLOPT_HTTPHEADER, $httpHeadersFinal);
1088 15
1089
// Proveď samotnou operaci
1090
        $this->lastCurlResponse            = curl_exec($this->curl);
1091 15
        $this->curlInfo                    = curl_getinfo($this->curl);
1092
        $this->curlInfo['when']            = microtime();
1093 15
        $this->curlInfo['request_headers'] = $httpHeadersFinal;
1094 15
        $this->responseFormat              = isset($this->curlInfo['content_type'])
1095 15
                ? Formats::contentTypeToSuffix($this->curlInfo['content_type']) : 'txt';
1096
        $this->lastResponseCode            = $this->curlInfo['http_code'];
1097 15
        $this->lastCurlError               = curl_error($this->curl);
1098
        if (strlen($this->lastCurlError)) {
1099 15
            $this->addStatusMessage(sprintf('Curl Error (HTTP %d): %s',
1100 15
                    $this->lastResponseCode, $this->lastCurlError), 'error');
1101 15
        }
1102 9
1103 9
        if ($this->debug === true) {
1104 6
            $this->saveDebugFiles();
1105 6
        }
1106 9
1107 6
        return $this->lastResponseCode;
1108
    }
1109
1110 15
    /**
1111
     * Nastaví druh prováděné akce.
1112
     *
1113
     * @link https://demo.flexibee.eu/devdoc/actions Provádění akcí
1114
     * @param string $action
1115
     * 
1116
     * @return boolean
1117
     */
1118
    public function setAction($action)
1119
    {
1120
        $result           = false;
1121 23
        $actionsAvailable = $this->getActionsInfo();
1122
        if (is_array($actionsAvailable) && array_key_exists($action,
1123 23
                $actionsAvailable)) {
1124 23
            $this->action = $action;
1125 23
            $result       = true;
1126 23
        }
1127 23
        return $result;
1128
    }
1129
1130
    /**
1131 23
     * Convert XML to array.
1132
     *
1133
     * @param string $xml
1134
     *
1135 23
     * @return array
1136 22
     */
1137 22
    public static function xml2array($xml)
1138 9
    {
1139 9
        $arr = [];
1140 22
        if (!empty($xml)) {
1141
            if (is_string($xml)) {
1142
                $xml = simplexml_load_string($xml);
1143
            }
1144
1145
            foreach ($xml->children() as $r) {
1146
                if (count($r->children()) == 0) {
1147
                    $arr[$r->getName()] = strval($r);
1148
                } else {
1149
                    $arr[$r->getName()][] = self::xml2array($r);
1150
                }
1151 6
            }
1152
        }
1153
        return $arr;
1154 6
    }
1155 6
1156 6
    /**
1157 6
     * Odpojení od FlexiBee.
1158 6
     */
1159
    public function disconnect()
1160 6
    {
1161
        if (is_resource($this->curl)) {
1162
            curl_close($this->curl);
1163
        }
1164
        $this->curl = null;
1165 6
    }
1166
1167
    /**
1168
     * Disconnect CURL befere pass away
1169 6
     */
1170
    public function __destruct()
1171
    {
1172
        $this->disconnect();
1173
    }
1174
1175
    /**
1176
     * Načte řádek dat z FlexiBee.
1177 16
     *
1178
     * @param int $recordID id požadovaného záznamu
1179 16
     *
1180 9
     * @return array
1181 9
     */
1182 16
    public function getFlexiRow($recordID)
1183 16
    {
1184 16
        $record   = null;
1185
        $response = $this->performRequest($this->evidence.'/'.$recordID.'.json');
1186 16
        if (isset($response[$this->evidence])) {
1187 16
            $record = $response[$this->evidence][0];
1188 16
        }
1189 15
1190 15
        return $record;
1191
    }
1192
1193
    /**
1194
     * Oddělí z pole podmínek ty jenž patří za ? v URL požadavku
1195
     *
1196
     * @link https://www.flexibee.eu/api/dokumentace/ref/urls/ Sestavování URL
1197
     * @param array $conditions pole podmínek   - rendrují se do ()
1198
     * @param array $urlParams  pole parametrů  - rendrují za ?
1199 15
     */
1200
    public function extractUrlParams(&$conditions, &$urlParams)
1201
    {
1202 15
        foreach ($this->urlParams as $urlParam) {
1203 10
            if (isset($conditions[$urlParam])) {
1204 10
                \Ease\Sand::divDataArray($conditions, $urlParams, $urlParam);
1205 15
            }
1206 15
        }
1207 15
    }
1208 15
1209
    /**
1210 14
     * convert unicode to entities for use with FlexiBee queries
1211 14
     *
1212 14
     * @param string $urlRaw
1213 14
     * 
1214 10
     * @return string
1215
     */
1216 14
    public static function urlEncode($urlRaw)
1217 14
    {
1218
        return str_replace(['%27', '%3A'], ["'", ':'], rawurlencode($urlRaw));
1219
    }
1220
1221
    /**
1222
     * Načte data z FlexiBee.
1223
     *
1224
     * @param string $suffix     dotaz
1225
     * @param string|array $conditions Volitelný filtrovací výraz
1226
     *
1227
     * @return array Data obtained
1228
     */
1229
    public function getFlexiData($suffix = null, $conditions = null)
1230
    {
1231
        $finalUrl  = '';
1232
        $urlParams = $this->defaultUrlParams;
1233
1234
        if (!empty($conditions)) {
1235
            if (is_array($conditions)) {
1236
                $this->extractUrlParams($conditions, $urlParams);
1237
                $conditions = $this->flexiUrl($conditions);
1238
            }
1239
1240
            if (strlen($conditions) && ($conditions[0] != '/')) {
1241
                $conditions = '('.self::urlEncode($conditions).')';
1242
            }
1243
        }
1244
1245
        if (strlen($suffix)) {
1246
            if (preg_match('/^http/', $suffix) || ($suffix[0] == '/') || is_numeric($suffix)) {
1247
                $finalUrl = $suffix;
1248
            } else {
1249
                if (preg_match('/^(code|ext):(.*)/', $suffix, $matches)) {
1250
                    $finalUrl = $matches[1].':'.rawurlencode($matches[2]);
1251
                }
1252 15
            }
1253
        }
1254
1255 15
        $finalUrl .= $conditions;
1256 15
1257 15
        if (count($urlParams)) {
1258
            if (strstr($finalUrl, '?')) {
1259 15
                $finalUrl .= '&';
1260 15
            } else {
1261 15
                $finalUrl .= '?';
1262 15
            }
1263 15
            $finalUrl .= http_build_query($urlParams, null, '&',
1264 15
                PHP_QUERY_RFC3986);
1265 15
        }
1266 15
1267
        $transactions = $this->performRequest($finalUrl, 'GET');
1268 15
1269
        $responseEvidence = $this->getResponseEvidence();
1270
        if (is_array($transactions) && array_key_exists($responseEvidence,
1271 15
                $transactions)) {
1272
            $result = $transactions[$responseEvidence];
1273
            if ((count($result) == 1) && (count(current($result)) == 0 )) {
1274 15
                $result = null; // Response is empty Array
1275 15
            }
1276 15
        } else {
1277 15
            $result = $transactions;
1278 15
        }
1279
1280 15
        return $result;
1281
    }
1282 15
1283
    /**
1284 15
     * Načte záznam z FlexiBee a uloží v sobě jeho data
1285 9
     * Read FlexiBee record and store it inside od object
1286 9
     *
1287
     * @param int $id ID or conditions
1288 15
     *
1289
     * @return int počet načtených položek
1290
     */
1291
    public function loadFromFlexiBee($id = null)
1292
    {
1293
        $data = [];
1294
        if (is_null($id)) {
1295
            $id = $this->getMyKey();
1296
        }
1297
        if (is_array($id)) {
1298
            $id = rawurlencode('('.self::flexiUrl($id).')');
1299 23
        } else if (preg_match('/^ext:/', $id)) {
1300
            $id = self::urlEncode($id);
1301 23
        } else if (preg_match('/^code:/', $id)) {
1302
            $id = self::code(rawurlencode(self::uncode($id)));
1303 23
        }
1304 23
1305 23
        $flexidata    = $this->getFlexiData($this->getEvidenceUrl().'/'.$id);
1306
        $this->apiURL = $this->curlInfo['url'];
1307 23
        if (is_array($flexidata) && (count($flexidata) == 1)) {
1308 23
            $data = current($flexidata);
1309 23
        }
1310
        return $this->takeData($data);
1311 23
    }
1312 23
1313 23
    /**
1314 23
     * Set Filter code for requests
1315 23
     *
1316 23
     * @link https://www.flexibee.eu/api/dokumentace/ref/zamykani-odemykani/
1317 23
     *
1318 23
     * @param array|string $filter filter formula or ['key'=>'value']
1319 23
     *
1320 23
     * @return string Filter code
1321
     */
1322
    public function setFilter($filter)
1323
    {
1324 23
        return $this->filter = is_array($filter) ? self::flexiUrl($filter) : $filter;
1325 23
    }
1326 23
1327
    /**
1328 23
     * Převede data do Json formátu pro FlexiBee.
1329 23
     * Convert data to FlexiBee like Json format
1330 23
     *
1331 23
     * @url https://www.flexibee.eu/api/dokumentace/ref/actions/
1332
     * @url https://www.flexibee.eu/api/dokumentace/ref/zamykani-odemykani/
1333
     *
1334 23
     * @param array $data    object data
1335 23
     * @param int   $options json_encode options like JSON_PRETTY_PRINT etc
1336 23
     *
1337 23
     * @return string
1338 23
     */
1339 23
    public function getJsonizedData($data = null, $options = 0)
1340 23
    {
1341 23
        if (is_null($data)) {
1342 23
            $data = $this->getData();
1343 23
        }
1344 23
1345 23
        $dataToJsonize = array_merge(['@version' => $this->protoVersion],
1346
            $this->getDataForJSON($data));
1347 23
        $jsonRaw       = json_encode([$this->nameSpace => $dataToJsonize],
1348 23
            $options);
1349
1350 23
        return $jsonRaw;
1351
    }
1352
1353
    /**
1354
     * Get Data Fragment specific for current object
1355
     *
1356
     * @param array $data
1357
     *
1358
     * @return array
1359
     */
1360 23
    public function getDataForJSON($data = null)
1361
    {
1362 23
        if (is_null($data)) {
1363 23
            $data = $this->getData();
1364 23
        }
1365
1366
        $dataForJson = [$this->getEvidence() => $this->objectToID($data)];
1367 23
1368 23
        if (!is_null($this->action)) {
1369 23
            $dataForJson[$this->evidence.'@action'] = $this->action;
1370 23
            $this->action                           = null;
1371 23
        }
1372
1373
        if (!is_null($this->filter)) {
1374 23
            $dataForJson[$this->evidence.'@filter'] = $this->filter;
1375 23
        }
1376 23
1377
1378 23
        foreach ($this->chained as $chained) {
1379 23
            $chainedData = $chained->getDataForJSON();
1380 23
            foreach ($chainedData as $chainedItemEvidence => $chainedItemData) {
1381 23
                if (array_key_exists($chainedItemEvidence, $dataForJson)) {
1382 23
                    if (is_string(key($dataForJson[$chainedItemEvidence]))) {
1383
                        $dataBackup                          = $dataForJson[$chainedItemEvidence];
1384 23
                        $dataForJson[$chainedItemEvidence]   = [];
1385 23
                        $dataForJson[$chainedItemEvidence][] = $dataBackup;
1386 23
                    }
1387 23
                    if (array_key_exists(0, $chainedItemData)) {
1388 23
                        foreach ($chainedItemData as $chainedItem) {
1389
                            $dataForJson[$chainedItemEvidence][] = $chainedItem;
1390 23
                        }
1391 23
                    } else {
1392 23
                        $dataForJson[$chainedItemEvidence][] = $chainedItemData;
1393 23
                    }
1394
                } else {
1395
                    $dataForJson[$chainedItemEvidence] = $chainedItemData;
1396 23
                }
1397
            }
1398
        }
1399 23
1400
1401
        return $dataForJson;
1402 23
    }
1403 23
1404 23
    /**
1405 23
     * Join another FlexiPeeHP Object
1406 23
     *
1407 23
     * @param FlexiBeeRO $object
1408
     *
1409
     * @return boolean adding to stack success
1410
     */
1411
    public function join(&$object)
1412
    {
1413
        $result = true;
1414
        if (method_exists($object, 'getDataForJSON')) {
1415
            $this->chained[] = $object;
1416
        } else {
1417
            throw new \Ease\Exception('$object->getDataForJSON() does not exist');
1418
        }
1419
1420
        return $result;
1421
    }
1422
1423
    /**
1424
     * Test if given record ID exists in FlexiBee.
1425
     *
1426
     * @param mixed $identifer presence state
1427
     *
1428
     * @return boolean
1429
     */
1430
    public function idExists($identifer = null)
1431
    {
1432
        if (is_null($identifer)) {
1433
            $identifer = $this->getMyKey();
1434
        }
1435
        $ignorestate = $this->ignore404();
1436
        $this->ignore404(true);
1437
        $this->getFlexiData(null,
1438
            [
1439
                'detail' => 'custom:'.$this->getKeyColumn(),
1440
                $this->getKeyColumn() => $identifer
1441
        ]);
1442
        $this->ignore404($ignorestate);
1443
        return $this->lastResponseCode == 200;
1444 23
    }
1445
1446 23
    /**
1447
     * Test if given record exists in FlexiBee.
1448 23
     *
1449 23
     * @param array|string|int $data ext:id:23|code:ITEM|['id'=>23]|23
1450 23
     * 
1451 23
     * @return boolean Record presence status
1452 23
     */
1453 23
    public function recordExists($data = [])
1454 23
    {
1455 23
1456 23
        if (empty($data)) {
1457
            $data = $this->getData();
1458 23
        }
1459 23
        $ignorestate = $this->ignore404();
1460 23
        $this->ignore404(true);
1461 23
        $keyColumn   = $this->getKeyColumn();
1462 23
        $res         = $this->getColumnsFromFlexibee([$keyColumn],
1463
            is_array($data) ? $data : [$keyColumn => $data]);
1464
1465 23
        if (!count($res) || (isset($res['success']) && ($res['success'] == 'false'))
1466 23
            || ((isset($res) && is_array($res)) && !isset($res[0]) )) {
1467
            $found = false;
1468
        } else {
1469 23
            $found = true;
1470
        }
1471 23
        $this->ignore404($ignorestate);
1472 23
        return $found;
1473
    }
1474 23
1475
    /**
1476
     * Vrací z FlexiBee sloupečky podle podmínek.
1477 23
     *
1478 23
     * @param array|int|string $conditions pole podmínek nebo ID záznamu
1479
     * @param string           $indexBy    klice vysledku naplnit hodnotou ze
1480
     *                                     sloupečku
1481
     * @return array
1482
     */
1483
    public function getAllFromFlexibee($conditions = null, $indexBy = null)
1484
    {
1485
        if (is_int($conditions)) {
1486
            $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...
1487
        }
1488
1489 65
        $flexiData = $this->getFlexiData('', $conditions);
1490
1491 65
        if (!is_null($indexBy)) {
1492 65
            $flexiData = $this->reindexArrayBy($flexiData);
1493
        }
1494
1495 65
        return $flexiData;
1496 65
    }
1497
1498
    /**
1499
     * Vrací z FlexiBee sloupečky podle podmínek.
1500
     *
1501 65
     * @param string[] $columnsList seznam položek
1502
     * @param array    $conditions  pole podmínek nebo ID záznamu
1503
     * @param string   $indexBy     Sloupeček podle kterého indexovat záznamy
1504
     *
1505
     * @return array
1506
     */
1507
    public function getColumnsFromFlexibee($columnsList, $conditions = [],
1508
                                           $indexBy = null)
1509
    {
1510
        $detail = 'full';
1511 71
        switch (gettype($columnsList)) {
1512
            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...
1513 71
                $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...
1514
            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...
1515
                if (!is_null($indexBy) && !array_key_exists($indexBy,
1516
                        $columnsList)) {
1517
                    $columnsList[] = $indexBy;
1518
                }
1519
                $columns = implode(',', array_unique($columnsList));
1520
                $detail  = 'custom:'.$columns;
1521
            default:
1522 23
                switch ($columnsList) {
1523
                    case 'id':
1524 23
                        $detail = 'id';
1525
                        break;
1526
                    case 'summary':
1527
                        $detail = 'summary';
1528
                        break;
1529
                    default:
1530
                        break;
1531
                }
1532 15
                break;
1533
        }
1534 15
1535 15
        $conditions['detail'] = $detail;
1536 15
1537 15
        $flexiData = $this->getFlexiData(null, $conditions);
1538 15
1539 9
        if (is_array($indexBy) && count($flexiData) && count(current($flexiData))) {
1540 9
            $flexiData = $this->reindexArrayBy($flexiData, $indexBy);
0 ignored issues
show
Documentation introduced by
$indexBy is of type array, but the function expects a string|null.

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