-
Notifications
You must be signed in to change notification settings - Fork 291
/
Copy pathDataSet.php
1257 lines (1058 loc) · 39.7 KB
/
DataSet.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/*
* Copyright (C) 2023 Xibo Signage Ltd
*
* Xibo - Digital Signage - https://xibosignage.com
*
* This file is part of Xibo.
*
* Xibo is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* Xibo is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Xibo. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Xibo\Entity;
use Carbon\Carbon;
use Carbon\Factory;
use Respect\Validation\Validator as v;
use Stash\Interfaces\PoolInterface;
use Xibo\Factory\DataSetColumnFactory;
use Xibo\Factory\DataSetFactory;
use Xibo\Factory\PermissionFactory;
use Xibo\Helper\SanitizerService;
use Xibo\Service\ConfigServiceInterface;
use Xibo\Service\DisplayNotifyServiceInterface;
use Xibo\Service\LogServiceInterface;
use Xibo\Storage\StorageServiceInterface;
use Xibo\Support\Exception\ConfigurationException;
use Xibo\Support\Exception\DuplicateEntityException;
use Xibo\Support\Exception\GeneralException;
use Xibo\Support\Exception\InvalidArgumentException;
use Xibo\Support\Exception\NotFoundException;
/**
* Class DataSet
* @package Xibo\Entity
*
* @SWG\Definition()
*/
class DataSet implements \JsonSerializable
{
use EntityTrait;
/**
* @SWG\Property(description="The dataSetId")
* @var int
*/
public $dataSetId;
/**
* @SWG\Property(description="The dataSet Name")
* @var string
*/
public $dataSet;
/**
* @SWG\Property(description="The dataSet description")
* @var string
*/
public $description;
/**
* @SWG\Property(description="The userId of the User that owns this DataSet")
* @var int
*/
public $userId;
/**
* @SWG\Property(description="Timestamp indicating the date/time this DataSet was edited last")
* @var int
*/
public $lastDataEdit;
/**
* @SWG\Property(description="The user name of the User that owns this DataSet")
* @var string
*/
public $owner;
/**
* @SWG\Property(description="A comma separated list of Groups/Users that have permission to this DataSet")
* @var string
*/
public $groupsWithPermissions;
/**
* @SWG\Property(description="A code for this Data Set")
* @var string
*/
public $code;
/**
* @SWG\Property(description="Flag to indicate whether this DataSet is a lookup table")
* @var int
*/
public $isLookup = 0;
/**
* @SWG\Property(description="Flag to indicate whether this DataSet is Remote")
* @var int
*/
public $isRemote = 0;
/**
* @SWG\Property(description="Method to fetch the Data, can be GET or POST")
* @var string
*/
public $method;
/**
* @SWG\Property(description="URI to call to fetch Data from. Replacements are {{DATE}}, {{TIME}} and, in case this is a sequencial used DataSet, {{COL.NAME}} where NAME is a ColumnName from the underlying DataSet.")
* @var string
*/
public $uri;
/**
* @SWG\Property(description="Data to send as POST-Data to the remote host with the same Replacements as in the URI.")
* @var string
*/
public $postData;
/**
* @SWG\Property(description="Authentication method, can be none, digest, basic")
* @var string
*/
public $authentication;
/**
* @SWG\Property(description="Username to authenticate with")
* @var string
*/
public $username;
/**
* @SWG\Property(description="Corresponding password")
* @var string
*/
public $password;
/**
* @SWG\Property(description="Oauth2.0 Authorization URL")
* @var string
*/
public $oauth2Url;
/**
* @SWG\Property(description="Oauth2.0 Client ID")
* @var string
*/
public $oauth2Client;
/**
* @SWG\Property(description="Oauth2.0 Client Secret")
* @var string
*/
public $oauth2ClientSecret;
/**
* @SWG\Property(description="Oauth2.0 Grant Type")
* @var string
*/
public $oauth2GrantType;
/**
* @SWG\Property(description="Comma separated string of custom HTTP headers")
* @var string
*/
public $customHeaders;
/**
* @SWG\Property(description="Custom User agent")
* @var string
*/
public $userAgent;
/**
* @SWG\Property(description="Time in seconds this DataSet should fetch new Datas from the remote host")
* @var int
*/
public $refreshRate;
/**
* @SWG\Property(description="Time in seconds when this Dataset should be cleared. If here is a lower value than in RefreshRate it will be cleared when the data is refreshed")
* @var int
*/
public $clearRate;
/**
* @SWG\Property(description="Flag whether to truncate DataSet data if no new data is pulled from remote source")
* @var int
*/
public $truncateOnEmpty;
/**
* @SWG\Property(description="DataSetID of the DataSet which should be fetched and present before the Data from this DataSet are fetched")
* @var int
*/
public $runsAfter;
/**
* @SWG\Property(description="Last Synchronisation Timestamp")
* @var int
*/
public $lastSync = 0;
/**
* @SWG\Property(description="Last Clear Timestamp")
* @var int
*/
public $lastClear = 0;
/**
* @SWG\Property(description="Root-Element form JSON where the data are stored in")
* @var String
*/
public $dataRoot;
/**
* @SWG\Property(description="Optional function to use for summarize or count unique fields in a remote request")
* @var String
*/
public $summarize;
/**
* @SWG\Property(description="JSON-Element below the Root-Element on which the consolidation should be applied on")
* @var String
*/
public $summarizeField;
/**
* @SWG\Property(description="The source id for remote dataSet, 1 - JSON, 2 - CSV")
* @var integer
*/
public $sourceId;
/**
* @SWG\Property(description="A flag whether to ignore the first row, for CSV source remote dataSet")
* @var integer
*/
public $ignoreFirstRow;
/**
* @SWG\Property(description="Soft limit on number of rows per DataSet, if left empty the global DataSet row limit will be used.")
* @var integer
*/
public $rowLimit = null;
/**
* @SWG\Property(description="Type of action that should be taken on next remote DataSet sync - stop, fifo or truncate")
* @var string
*/
public $limitPolicy;
/**
* @SWG\Property(description="Custom separator for CSV source, comma will be used by default")
* @var string
*/
public $csvSeparator;
/**
* @SWG\Property(description="The id of the Folder this DataSet belongs to")
* @var int
*/
public $folderId;
/**
* @SWG\Property(description="The id of the Folder responsible for providing permissions for this DataSet")
* @var int
*/
public $permissionsFolderId;
/** @var array Permissions */
private $permissions = [];
/**
* @var DataSetColumn[]
*/
public $columns = [];
private $countLast = 0;
/** @var array Blacklist for SQL */
private $blackList = array(';', 'INSERT', 'UPDATE', 'SELECT', 'DELETE', 'TRUNCATE', 'TABLE', 'FROM', 'WHERE');
/** @var \Xibo\Helper\SanitizerService */
private $sanitizerService;
/** @var ConfigServiceInterface */
private $config;
/** @var PoolInterface */
private $pool;
/** @var DataSetFactory */
private $dataSetFactory;
/** @var DataSetColumnFactory */
private $dataSetColumnFactory;
/** @var PermissionFactory */
private $permissionFactory;
/** @var DisplayNotifyServiceInterface */
private $displayNotifyService;
/**
* Entity constructor.
* @param StorageServiceInterface $store
* @param LogServiceInterface $log
* @param \Symfony\Component\EventDispatcher\EventDispatcherInterface $dispatcher
* @param SanitizerService $sanitizerService
* @param ConfigServiceInterface $config
* @param PoolInterface $pool
* @param DataSetFactory $dataSetFactory
* @param DataSetColumnFactory $dataSetColumnFactory
* @param PermissionFactory $permissionFactory
* @param DisplayNotifyServiceInterface $displayNotifyService
*/
public function __construct($store, $log, $dispatcher, $sanitizerService, $config, $pool, $dataSetFactory, $dataSetColumnFactory, $permissionFactory, $displayNotifyService)
{
$this->setCommonDependencies($store, $log, $dispatcher);
$this->sanitizerService = $sanitizerService;
$this->config = $config;
$this->pool = $pool;
$this->dataSetFactory = $dataSetFactory;
$this->dataSetColumnFactory = $dataSetColumnFactory;
$this->permissionFactory = $permissionFactory;
$this->displayNotifyService = $displayNotifyService;
}
/**
* @param $array
* @return \Xibo\Support\Sanitizer\SanitizerInterface
*/
protected function getSanitizer($array)
{
return $this->sanitizerService->getSanitizer($array);
}
/**
* Clone
*/
public function __clone()
{
$this->dataSetId = null;
$this->columns = array_map(function ($object) { return clone $object; }, $this->columns);
}
/**
* @return int
*/
public function getId()
{
return $this->dataSetId;
}
public function getPermissionFolderId()
{
return $this->permissionsFolderId;
}
/**
* @return int
*/
public function getOwnerId()
{
return $this->userId;
}
/**
* Set the owner of this DataSet
* @param $userId
*/
public function setOwner($userId)
{
$this->userId = $userId;
}
/**
* Get the Count of Records in the last getData()
* @return int
*/
public function countLast()
{
return $this->countLast;
}
/**
* Get the Display Notify Service
* @return DisplayNotifyServiceInterface
*/
public function getDisplayNotifyService(): DisplayNotifyServiceInterface
{
return $this->displayNotifyService->init();
}
/**
* Get Column
* @param int[Optional] $dataSetColumnId
* @return DataSetColumn[]|DataSetColumn
* @throws NotFoundException when the heading is provided and the column cannot be found
*/
public function getColumn($dataSetColumnId = 0)
{
$this->load();
if ($dataSetColumnId != 0) {
foreach ($this->columns as $column) {
/* @var DataSetColumn $column */
if ($column->dataSetColumnId == $dataSetColumnId)
return $column;
}
throw new NotFoundException(sprintf(__('Column %s not found'), $dataSetColumnId));
} else {
return $this->columns;
}
}
/**
* Get Column
* @param string $dataSetColumn
* @return DataSetColumn[]|DataSetColumn
* @throws NotFoundException when the heading is provided and the column cannot be found
*/
public function getColumnByName($dataSetColumn)
{
$this->load();
foreach ($this->columns as $column) {
/* @var DataSetColumn $column */
if ($column->heading == $dataSetColumn)
return $column;
}
throw new NotFoundException(sprintf(__('Column %s not found'), $dataSetColumn));
}
/**
* @param string[] $columns Column Names to select
* @return array
* @throws InvalidArgumentException
*/
public function getUniqueColumnValues($columns)
{
$this->load();
$select = '';
foreach ($columns as $heading) {
// Check this exists
$found = false;
foreach ($this->columns as $column) {
if ($column->heading == $heading) {
// Formula column?
if ($column->dataSetColumnTypeId == 2) {
$select .= str_replace($this->blackList, '', htmlspecialchars_decode($column->formula, ENT_QUOTES)) . ' AS `' . $column->heading . '`,';
}
else {
$select .= '`' . $column->heading . '`,';
}
$found = true;
break;
}
}
if (!$found) {
throw new InvalidArgumentException(__('Unknown Column ' . $heading));
}
}
$select = rtrim($select, ',');
// $select is safe
return $this->getStore()->select('SELECT DISTINCT ' . $select . ' FROM `dataset_' . $this->dataSetId . '`', []);
}
/**
* Get DataSet Data
* @param array $filterBy
* @param array $options
* @return array
* @throws NotFoundException
*/
public function getData($filterBy = [], $options = [])
{
$sanitizer = $this->getSanitizer($filterBy);
$start = $sanitizer->getInt('start', ['default' => 0]);
$size = $sanitizer->getInt('size', ['default' => 0]);
$filter = $filterBy['filter'] ?? '';
$ordering = $sanitizer->getString('order');
$displayId = $sanitizer->getInt('displayId', ['default' => 0]);
$options = array_merge([
'includeFormulaColumns' => true,
'requireTotal' => true,
'connection' => 'default'
], $options);
// Params
$params = [];
// Sanitize the filter options provided
// Get the Latitude and Longitude ( might be used in a formula )
if ($displayId == 0) {
$displayGeoLocation =
"ST_GEOMFROMTEXT('POINT(" . $this->config->getSetting('DEFAULT_LAT') .
' ' . $this->config->getSetting('DEFAULT_LONG') . ")')";
} else {
$displayGeoLocation = '(SELECT GeoLocation FROM `display` WHERE DisplayID =' . $displayId. ')';
}
// Build a SQL statement, based on the columns for this dataset
$this->load();
$select = 'SELECT * FROM ( ';
$body = 'SELECT id';
// Keep track of the columns we are allowed to order by
$allowedOrderCols = ['id'];
// Are there any client side formulas
$clientSideFormula = [];
// Select (columns)
foreach ($this->getColumn() as $column) {
/* @var DataSetColumn $column */
if ($column->dataSetColumnTypeId == 2 && !$options['includeFormulaColumns']) {
continue;
}
// Formula column?
if ($column->dataSetColumnTypeId == 2) {
// Is this a client side column?
if (substr($column->formula, 0, 1) === '$') {
$clientSideFormula[] = $column;
continue;
}
$formula = str_ireplace($this->blackList, '', htmlspecialchars_decode($column->formula, ENT_QUOTES));
$formula = str_replace('[DisplayId]', $displayId, $formula);
$heading = str_replace('[DisplayGeoLocation]', $displayGeoLocation, $formula) . ' AS `' . $column->heading . '`';
} else {
$heading = '`' . $column->heading . '`';
}
$allowedOrderCols[] = $column->heading;
$body .= ', ' . $heading;
}
$body .= ' FROM `dataset_' . $this->dataSetId . '`) dataset WHERE 1 = 1 ';
// Filtering
if ($filter != '') {
// Support display filtering.
$filter = str_replace('[DisplayId]', $displayId, $filter);
$filter = str_ireplace($this->blackList, '', $filter);
$body .= ' AND ' . $filter;
}
// Filter by ID
if ($sanitizer->getInt('id') !== null) {
$body .= ' AND id = :id ';
$params['id'] = $sanitizer->getInt('id');
}
// Ordering
$order = '';
if ($ordering != '') {
$order = ' ORDER BY ';
$ordering = explode(',', $ordering);
foreach ($ordering as $orderPair) {
// Sanitize the clause
$sanitized = str_replace('`', '', str_replace(' ASC', '', str_replace(' DESC', '', $orderPair)));
// Check allowable
if (!in_array($sanitized, $allowedOrderCols)) {
$found = false;
$this->getLog()->info('Potentially disallowed column: ' . $sanitized);
// the gridRenderSort will strip spaces on column names go through allowed order columns
// and see if we can find a match by stripping spaces from the heading
foreach ($allowedOrderCols as $allowedOrderCol) {
$this->getLog()->info('Checking spaces in original name : ' . $sanitized);
if (str_replace(' ', '', $allowedOrderCol) === $sanitized) {
$found = true;
// put the column heading with the space as sanitized to make sql happy.
$sanitized = $allowedOrderCol;
}
}
// we tried, but it was not found, omit this pair
if (!$found) {
continue;
}
}
// Substitute
if (strripos($orderPair, ' DESC')) {
$order .= sprintf(' `%s` DESC,', $sanitized);
} else if (strripos($orderPair, ' ASC')) {
$order .= sprintf(' `%s` ASC,', $sanitized);
} else {
$order .= sprintf(' `%s`,', $sanitized);
}
}
$order = trim($order, ',');
// if after all that we still do not have any column name to order by, default to order by id
if (trim($order) === 'ORDER BY') {
$order = ' ORDER BY id ';
}
} else {
$order = ' ORDER BY id ';
}
// Limit
$limit = '';
if ($start != 0 || $size != 0) {
// Substitute in
// handle case where lower limit is set to > 0 and upper limit to 0 https://github.com/xibosignage/xibo/issues/2187
// it is with <= 0 because in some Widgets we calculate the size as upper - lower, https://github.com/xibosignage/xibo/issues/2263.
if ($start != 0 && $size <= 0) {
$size = PHP_INT_MAX;
}
$limit = sprintf(' LIMIT %d, %d ', $start, $size);
}
$sql = $select . $body . $order . $limit;
$data = $this->getStore()->select($sql, $params, $options['connection']);
// If there are limits run some SQL to work out the full payload of rows
if ($options['requireTotal']) {
$results = $this->getStore()->select(
'SELECT COUNT(*) AS total FROM (' . $body,
$params,
$options['connection']
);
$this->countLast = intval($results[0]['total']);
}
// Are there any client side formulas?
if (count($clientSideFormula) > 0) {
$renderedData = [];
foreach ($data as $item) {
foreach ($clientSideFormula as $column) {
// Run the formula and add the resulting value to the list
$value = null;
try {
if (substr($column->formula, 0, strlen('$dateFormat(')) === '$dateFormat(') {
// Pull out the column name and date format
$details = explode(',', str_replace(')', '', str_replace('$dateFormat(', '', $column->formula)));
if (isset($details[2])) {
$language = str_replace(' ', '', $details[2]);
} else {
$language = $this->config->getSetting('DEFAULT_LANGUAGE', 'en_GB');
}
$carbonFactory = new Factory(['locale' => $language], Carbon::class);
$value = $carbonFactory->parse($item[$details[0]])->translatedFormat($details[1]);
}
} catch (\Exception $e) {
$this->getLog()->error('DataSet client side formula error in dataSetId ' . $this->dataSetId . ' with column formula ' . $column->formula);
}
$item[$column->heading] = $value;
}
$renderedData[] = $item;
}
} else {
$renderedData = $data;
}
return $renderedData;
}
/**
* Assign a column
* @param DataSetColumn $column
*/
public function assignColumn($column)
{
$this->load();
// Set the dataSetId
$column->dataSetId = $this->dataSetId;
// Set the column order if we need to
if ($column->columnOrder == 0)
$column->columnOrder = count($this->columns) + 1;
$this->columns[] = $column;
}
/**
* Has Data?
* @return bool
*/
public function hasData()
{
return $this->getStore()->exists('SELECT id FROM `dataset_' . $this->dataSetId . '` LIMIT 1', [], 'isolated');
}
/**
* Returns a Timestamp for the next Synchronisation process.
* @return int Seconds
*/
public function getNextSyncTime()
{
return $this->lastSync + $this->refreshRate;
}
/**
* @return bool
*/
public function isTruncateEnabled()
{
return $this->clearRate !== 0;
}
/**
* Returns a Timestamp for the next Clearing process.
* @return int Seconds
*/
public function getNextClearTime()
{
return $this->lastClear + $this->clearRate;
}
/**
* Returns if there is a consolidation field and method present or not.
* @return boolean
*/
public function doConsolidate()
{
return ($this->summarizeField != null) && ($this->summarizeField != '')
&& ($this->summarize != null) && ($this->summarize != '');
}
/**
* Returns the last Part of the Fieldname on which the consolidation should be applied on
* @return String
*/
public function getConsolidationField()
{
$pos = strrpos($this->summarizeField, '.');
if ($pos !== false) {
return substr($this->summarizeField, $pos + 1);
}
return $this->summarizeField;
}
/**
* Tests if this DataSet contains parameters for getting values on the dependant DataSet
* @return boolean
*/
public function containsDependantFieldsInRequest()
{
return strpos($this->postData, '{{COL.') !== false || strpos($this->uri, '{{COL.') !== false;
}
/**
* Validate
* @throws InvalidArgumentException
* @throws DuplicateEntityException
*/
public function validate()
{
if (!v::stringType()->notEmpty()->length(null, 50)->validate($this->dataSet)) {
throw new InvalidArgumentException(__('Name must be between 1 and 50 characters'), 'dataSet');
}
if ($this->description != null && !v::stringType()->length(null, 254)->validate($this->description)) {
throw new InvalidArgumentException(__('Description can not be longer than 254 characters'), 'description');
}
// If we are a remote dataset do some additional checks
if ($this->isRemote === 1) {
if (!v::stringType()->notEmpty()->validate($this->uri)) {
throw new InvalidArgumentException(__('A remote DataSet must have a URI.'), 'uri');
}
if ($this->rowLimit > $this->config->getSetting('DATASET_HARD_ROW_LIMIT')) {
throw new InvalidArgumentException(__('DataSet row limit cannot be larger than the CMS dataSet row limit'));
}
}
try {
$existing = $this->dataSetFactory->getByName($this->dataSet, $this->userId);
if ($this->dataSetId == 0 || $this->dataSetId != $existing->dataSetId) {
throw new DuplicateEntityException(sprintf(__('There is already dataSet called %s. Please choose another name.'), $this->dataSet));
}
}
catch (NotFoundException $e) {
// This is good
}
}
/**
* Load all known information
*/
public function load()
{
if ($this->loaded || $this->dataSetId == 0)
return;
// Load Columns
$this->columns = $this->dataSetColumnFactory->getByDataSetId($this->dataSetId);
// Load Permissions
$this->permissions = $this->permissionFactory->getByObjectId(get_class($this), $this->getId());
$this->loaded = true;
}
/**
* Save this DataSet
* @param array $options
* @throws InvalidArgumentException
* @throws DuplicateEntityException
*/
public function save($options = [])
{
$options = array_merge([
'validate' => true,
'saveColumns' => true,
'activate' => true,
'notify' => true,
], $options);
if ($options['validate']) {
$this->validate();
}
if ($this->dataSetId == 0) {
$this->add();
} else {
$this->edit();
}
// Columns
if ($options['saveColumns']) {
foreach ($this->columns as $column) {
$column->dataSetId = $this->dataSetId;
$column->save($options);
}
}
// We've been touched
if ($options['activate']) {
$this->setActive();
}
// Notify Displays?
if ($options['notify']) {
$this->notify();
}
}
/**
* @param int $time
* @return $this
*/
public function saveLastSync($time)
{
$this->lastSync = $time;
$this->getStore()->update('UPDATE `dataset` SET lastSync = :lastSync WHERE dataSetId = :dataSetId', [
'dataSetId' => $this->dataSetId,
'lastSync' => $this->lastSync
]);
return $this;
}
/**
* @param int $time
* @return $this
*/
public function saveLastClear($time)
{
$this->lastSync = $time;
$this->getStore()->update('UPDATE `dataset` SET lastClear = :lastClear WHERE dataSetId = :dataSetId', [
'dataSetId' => $this->dataSetId,
'lastClear' => $this->lastClear
]);
return $this;
}
/**
* Is this DataSet active currently
* @return bool
*/
public function isActive()
{
$cache = $this->pool->getItem('/dataset/accessed/' . $this->dataSetId);
return $cache->isHit();
}
/**
* Indicate that this DataSet has been accessed recently
* @return $this
*/
public function setActive()
{
$this->getLog()->debug('Setting ' . $this->dataSetId . ' as active');
$cache = $this->pool->getItem('/dataset/accessed/' . $this->dataSetId);
$cache->set('true');
$cache->expiresAfter(intval($this->config->getSetting('REQUIRED_FILES_LOOKAHEAD')) * 1.5);
$this->pool->saveDeferred($cache);
return $this;
}
/**
* Delete DataSet
* @throws ConfigurationException
* @throws InvalidArgumentException
*/
public function delete()
{
$this->load();
if ($this->isLookup) {
throw new ConfigurationException(__('Lookup Tables cannot be deleted'));
}
// check if any other DataSet depends on this DataSet
if ($this->getStore()->exists(
'SELECT dataSetId FROM dataset WHERE runsAfter = :runsAfter AND dataSetId <> :dataSetId',
[
'runsAfter' => $this->dataSetId,
'dataSetId' => $this->dataSetId
])) {
throw new InvalidArgumentException(__('Cannot delete because this DataSet is set as dependent DataSet for another DataSet'), 'dataSetId');
}
// Make sure we're able to delete
if ($this->getStore()->exists('
SELECT widgetId
FROM `widgetoption`
WHERE `widgetoption`.type = \'attrib\'
AND `widgetoption`.option = \'dataSetId\'
AND `widgetoption`.value = :dataSetId
', ['dataSetId' => $this->dataSetId])) {
throw new InvalidArgumentException(__('Cannot delete because DataSet is in use on one or more Layouts.'), 'dataSetId');
}
// Delete Permissions
foreach ($this->permissions as $permission) {
/* @var Permission $permission */
$permission->deleteAll();
}
// Delete Columns
foreach ($this->columns as $column) {
$column->delete(true);
}
// Delete any dataSet rss
$this->getStore()->update('DELETE FROM `datasetrss` WHERE dataSetId = :dataSetId', ['dataSetId' => $this->dataSetId]);
// Delete the data set
$this->getStore()->update('DELETE FROM `dataset` WHERE dataSetId = :dataSetId', ['dataSetId' => $this->dataSetId]);
// The last thing we do is drop the dataSet table
$this->dropTable();
}
/**
* Delete all data
*/
public function deleteData()
{
// The last thing we do is drop the dataSet table