-
Notifications
You must be signed in to change notification settings - Fork 263
/
ModuleFactory.php
867 lines (769 loc) · 30.1 KB
/
ModuleFactory.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
<?php
/*
* Copyright (C) 2024 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\Factory;
use Illuminate\Support\Str;
use Slim\Views\Twig;
use Stash\Interfaces\PoolInterface;
use Xibo\Entity\Module;
use Xibo\Entity\ModuleTemplate;
use Xibo\Entity\Widget;
use Xibo\Service\ConfigServiceInterface;
use Xibo\Support\Exception\NotFoundException;
use Xibo\Widget\DataType\DataTypeInterface;
use Xibo\Widget\Definition\Asset;
use Xibo\Widget\Definition\DataType;
use Xibo\Widget\Provider\DataProvider;
use Xibo\Widget\Provider\DataProviderInterface;
use Xibo\Widget\Provider\DurationProvider;
use Xibo\Widget\Provider\DurationProviderInterface;
use Xibo\Widget\Provider\WidgetProviderInterface;
use Xibo\Widget\Render\WidgetDataProviderCache;
use Xibo\Widget\Render\WidgetHtmlRenderer;
/**
* Class ModuleFactory
* @package Xibo\Factory
*/
class ModuleFactory extends BaseFactory
{
use ModuleXmlTrait;
/** @var Module[] all modules */
private $modules = null;
/** @var \Xibo\Widget\Definition\DataType[] */
private $dataTypes = null;
/** @var \Stash\Interfaces\PoolInterface */
private $pool;
/** @var string */
private $cachePath;
/** @var \Slim\Views\Twig */
private $twig;
/** @var \Xibo\Service\ConfigServiceInterface */
private $config;
/**
* Construct a factory
* @param string $cachePath
* @param PoolInterface $pool
* @param \Slim\Views\Twig $twig
* @param \Xibo\Service\ConfigServiceInterface $config
*/
public function __construct(string $cachePath, PoolInterface $pool, Twig $twig, ConfigServiceInterface $config)
{
$this->cachePath = $cachePath;
$this->pool = $pool;
$this->twig = $twig;
$this->config = $config;
}
/**
* @param \Xibo\Entity\Module $module
* @param \Xibo\Entity\Widget $widget
* @return \Xibo\Widget\Provider\DataProviderInterface
*/
public function createDataProvider(Module $module, Widget $widget): DataProviderInterface
{
return new DataProvider(
$module,
$widget,
$this->config->getGuzzleProxy(),
$this->getSanitizerService(),
$this->pool,
);
}
/**
* @param Module $module
* @param Widget $widget
* @return DurationProviderInterface
*/
public function createDurationProvider(Module $module, Widget $widget): DurationProviderInterface
{
return new DurationProvider($module, $widget);
}
/**
* Create a widget renderer
* @return \Xibo\Widget\Render\WidgetHtmlRenderer
*/
public function createWidgetHtmlRenderer(): WidgetHtmlRenderer
{
return (new WidgetHtmlRenderer($this->cachePath, $this->twig, $this->config, $this))
->useLogger($this->getLog()->getLoggerInterface());
}
/**
* Create a widget data provider cache
*/
public function createWidgetDataProviderCache(): WidgetDataProviderCache
{
return (new WidgetDataProviderCache($this->pool))
->useLogger($this->getLog()->getLoggerInterface());
}
/**
* Determine the cache key
* @param \Xibo\Entity\Module $module
* @param \Xibo\Entity\Widget $widget
* @param int $displayId the displayId (0 for preview)
* @param \Xibo\Widget\Provider\DataProviderInterface $dataProvider
* @param \Xibo\Widget\Provider\WidgetProviderInterface|null $widgetInterface
* @return string
*/
public function determineCacheKey(
Module $module,
Widget $widget,
int $displayId,
DataProviderInterface $dataProvider,
?WidgetProviderInterface $widgetInterface
): string {
// Determine the cache key
$cacheKey = null;
if ($widgetInterface !== null) {
$cacheKey = $widgetInterface->getDataCacheKey($dataProvider);
}
if ($cacheKey === null) {
// Determinthe cache key from the setting in XML.
if (empty($module->dataCacheKey)) {
// Best we can do here is a cache per widget, but we should log this as an error.
$this->getLog()->debug('determineCacheKey: module without dataCacheKey: ' . $module->moduleId);
$cacheKey = $widget->widgetId;
} else {
// Start with the one provided
$this->getLog()->debug('determineCacheKey: module dataCacheKey: ' . $module->dataCacheKey);
$cacheKey = $module->dataCacheKey;
// Properties
$module->decorateProperties($widget, true);
$properties = $module->getPropertyValues(false);
// Parse the cache key for variables.
$matches = [];
preg_match_all('/%(.*?)%/', $cacheKey, $matches);
foreach ($matches[1] as $match) {
if ($match === 'displayId') {
$cacheKey = str_replace('%displayId%', $displayId, $cacheKey);
} else if ($match === 'widgetId') {
$cacheKey = str_replace('%widgetId%', $widget->widgetId, $cacheKey);
} else {
$this->getLog()->debug($match);
$cacheKey = str_replace(
'%' . $match . '%',
$properties[$match] ?? '',
$cacheKey
);
}
}
}
}
$this->getLog()->debug('determineCacheKey: cache key is : ' . $cacheKey);
return $cacheKey;
}
/**
* @param string $dataType
* @return void
*/
public function clearCacheForDataType(string $dataType): void
{
$this->getLog()->debug('clearCacheForDataType: /widget/' . $dataType);
$this->pool->deleteItem('/widget/' . $dataType);
}
/**
* @return \Xibo\Entity\Module[]
*/
public function getKeyedArrayOfModules(): array
{
$this->getLog()->debug('ModuleFactory: getKeyedArrayOfModules');
$modules = [];
foreach ($this->load() as $module) {
$modules[$module->type] = $module;
}
return $modules;
}
/**
* @return Module[]
*/
public function getAssignableModules(): array
{
$this->getLog()->debug('ModuleFactory: getAssignableModules');
$modules = [];
foreach ($this->load() as $module) {
if ($module->enabled === 1 && $module->assignable === 1) {
$modules[] = $module;
}
}
return $modules;
}
/**
* @return Module[]
*/
public function getLibraryModules(): array
{
$this->getLog()->debug('ModuleFactory: getLibraryModules');
$modules = [];
foreach ($this->load() as $module) {
if ($module->enabled == 1 && $module->regionSpecific === 0) {
$modules[] = $module;
}
}
return $modules;
}
/**
* Get module by Id
* @param string $moduleId
* @return Module
* @throws NotFoundException
*/
public function getById($moduleId): Module
{
$this->getLog()->debug('ModuleFactory: getById');
foreach ($this->load() as $module) {
if ($module->moduleId === $moduleId) {
return $module;
}
}
throw new NotFoundException();
}
/**
* Get an array of all modules
* @return Module[]
*/
public function getAll(): array
{
$this->getLog()->debug('ModuleFactory: getAll');
return $this->load();
}
/**
* Get an array of all modules except canvas
* @param array $filter
* @return Module[]
*/
public function getAllExceptCanvas(array $filter = []): array
{
$sanitizedFilter = $this->getSanitizer($filter);
$this->getLog()->debug('ModuleFactory: getAllButCanvas');
$modules = [];
foreach ($this->load() as $module) {
// Hide the canvas module from the module list
if ($module->moduleId != 'core-canvas') {
// do we have a name filter?
if (!empty($sanitizedFilter->getString('name'))) {
if (str_contains(strtolower($module->name), strtolower($sanitizedFilter->getString('name')))) {
$modules[] = $module;
}
} else {
$modules[] = $module;
}
}
}
return $modules;
}
/**
* Get an array of all enabled modules
* @return Module[]
*/
public function getEnabled(): array
{
$this->getLog()->debug('ModuleFactory: getEnabled');
$modules = [];
foreach ($this->load() as $module) {
if ($module->enabled == 1) {
$modules[] = $module;
}
}
return $modules;
}
/**
* Get module by Type
* this should return the first module enabled by the type specified.
* @param string $type
* @param array $conditions Conditions that are created based on the widget's option and value, e.g, templateId==worldclock1
* @return Module
* @throws \Xibo\Support\Exception\NotFoundException
*/
public function getByType(string $type, array $conditions = []): Module
{
$this->getLog()->debug('ModuleFactory: getByType ' . $type);
$modules = $this->load();
usort($modules, function ($a, $b) {
/** @var Module $a */
/** @var Module $b */
return $a->enabled - $b->enabled;
});
foreach ($modules as $module) {
if ($module->type === $type) {
return $module;
}
}
// Match on legacy type
foreach ($modules as $module) {
// get the name of the legacytypes
$legacyTypes = [];
$legacyConditions = [];
if (count($module->legacyTypes) > 0) {
$legacyTypes = array_column($module->legacyTypes, 'name');
$legacyConditions = array_column($module->legacyTypes, 'condition');
}
if (in_array($type, $legacyTypes)) {
foreach ($conditions as $value) {
if (in_array($value, $legacyConditions)) {
return $module;
}
}
return $module;
}
}
throw new NotFoundException();
}
/**
* Get module by extension
* @param string $extension
* @return Module
* @throws NotFoundException
*/
public function getByExtension(string $extension): Module
{
$this->getLog()->debug('ModuleFactory: getByExtension');
foreach ($this->load() as $module) {
$validExtensions = $module->getSetting('validExtensions');
if (!empty($validExtensions) && Str::contains($validExtensions, $extension)) {
return $module;
}
}
throw new NotFoundException(sprintf(__('Extension %s does not match any enabled Module'), $extension));
}
/**
* Get Valid Extensions
* @param array $filterBy
* @return string[]
*/
public function getValidExtensions($filterBy = []): array
{
$this->getLog()->debug('ModuleFactory: getValidExtensions');
$filterBy = $this->getSanitizer($filterBy);
$typeFilter = $filterBy->getString('type');
$extensions = [];
foreach ($this->load() as $module) {
if ($typeFilter !== null && $module->type !== $typeFilter) {
continue;
}
if (!empty($module->getSetting('validExtensions'))) {
foreach (explode(',', $module->getSetting('validExtensions')) as $extension) {
$extensions[] = $extension;
}
}
}
return $extensions;
}
/**
* @param string $dataTypeId
* @return \Xibo\Widget\Definition\DataType
* @throws \Xibo\Support\Exception\NotFoundException
*/
public function getDataTypeById(string $dataTypeId): DataType
{
// Rely on a class if we have one.
$className = '\\Xibo\\Widget\\DataType\\' . ucfirst($dataTypeId);
if (class_exists($className)) {
$class = new $className();
if ($class instanceof DataTypeInterface) {
return ($class->getDefinition());
}
}
// Otherwise look in our XML definitions
foreach ($this->loadDataTypes() as $dataType) {
if ($dataType->id === $dataTypeId) {
return $dataType;
}
}
throw new NotFoundException(__('DataType not found'));
}
/**
* @param string $assetId
* @return \Xibo\Widget\Definition\Asset
* @throws \Xibo\Support\Exception\NotFoundException
*/
public function getAssetById(string $assetId): Asset
{
$this->getLog()->debug('getAssetById: ' . $assetId);
foreach ($this->getEnabled() as $module) {
foreach ($module->getAssets() as $asset) {
if ($asset->id === $assetId) {
return $asset;
}
}
}
throw new NotFoundException(__('Asset not found'));
}
/**
* @param string $alias
* @return \Xibo\Widget\Definition\Asset
* @throws \Xibo\Support\Exception\NotFoundException
*/
public function getAssetByAlias(string $alias): Asset
{
$this->getLog()->debug('getAssetByAlias: ' . $alias);
foreach ($this->getEnabled() as $module) {
foreach ($module->getAssets() as $asset) {
if ($asset->alias === $alias) {
return $asset;
}
}
}
throw new NotFoundException(__('Asset not found'));
}
/**
* @param ModuleTemplate[] $templates
* @return Asset[]
*/
public function getAssetsFromTemplates(array $templates): array
{
$assets = [];
foreach ($this->getEnabled() as $module) {
foreach ($module->getAssets() as $asset) {
$assets[$asset->id] = $asset;
}
foreach ($templates as $template) {
foreach ($template->getAssets() as $asset) {
$assets[$asset->id] = $asset;
}
}
}
return $assets;
}
/**
* Get all assets
* @return Asset[]
*/
public function getAllAssets(): array
{
$assets = [];
foreach ($this->getEnabled() as $module) {
foreach ($module->getAssets() as $asset) {
$assets[$asset->id] = $asset;
}
}
return $assets;
}
/**
* Get an asset from anywhere by its ID
* @param string $assetId
* @param ModuleTemplateFactory $moduleTemplateFactory
* @param bool $isAlias
* @return Asset
* @throws NotFoundException
*/
public function getAssetsFromAnywhereById(
string $assetId,
ModuleTemplateFactory $moduleTemplateFactory,
bool $isAlias = false,
): Asset {
$asset = null;
try {
$asset = $isAlias
? $this->getAssetByAlias($assetId)
: $this->getAssetById($assetId);
} catch (NotFoundException) {
// Not a module asset.
}
// Try a template instead
try {
$asset = $isAlias
? $moduleTemplateFactory->getAssetByAlias($assetId)
: $moduleTemplateFactory->getAssetById($assetId);
} catch (NotFoundException) {
// Not a module template asset.
}
if ($asset !== null) {
return $asset;
} else {
throw new NotFoundException(__('Asset not found'));
}
}
/**
* Load all modules into an array for use throughout this request
* @return \Xibo\Entity\Module[]
*/
private function load(): array
{
if ($this->modules === null) {
// TODO: these are the only fields we require in the settings table
$sql = '
SELECT `moduleId`, `enabled`, `previewEnabled`, `defaultDuration`, `settings`
FROM `module`
';
$modulesWithSettings = [];
foreach ($this->getStore()->select($sql, []) as $row) {
// Make a keyed array of these settings
$modulesWithSettings[$row['moduleId']] = $this->getSanitizer($row);
}
// Load in our file system modules.
// we consider modules in the module folder, and also custom modules
$files = array_merge(
glob(PROJECT_ROOT . '/modules/*.xml'),
glob(PROJECT_ROOT . '/custom/modules/*.xml')
);
foreach ($files as $file) {
// Create our module entity from this file
try {
$module = $this->createFromXml($file, $modulesWithSettings);
// Create a widget provider if necessary
// Take our module and see if it has a class associated with it
if (!empty($module->class)) {
// We create a module specific provider
if (!class_exists($module->class)) {
$module->errors[] = 'Module class not found: ' . $module->class;
} else {
$class = $module->class;
$module->setWidgetProvider(new $class());
}
}
// Create a widget compatibility if necessary
if (!empty($module->compatibilityClass)) {
// We create a module specific provider
if (!class_exists($module->compatibilityClass)) {
$module->errors[] = 'Module compatibilityClass not found: ' . $module->compatibilityClass;
} else {
$compatibilityClass = $module->compatibilityClass;
$module->setWidgetCompatibility(new $compatibilityClass());
}
}
// Create a widget validator if necessary
foreach ($module->validatorClass as $validatorClass) {
// We create a module specific provider
if (!class_exists($validatorClass)) {
$module->errors[] = 'Module validatorClass not found: ' . $validatorClass;
} else {
$module->addWidgetValidator(
(new $validatorClass())
->setLog($this->getLog()->getLoggerInterface())
);
}
}
// Set error state
$module->isError = $module->errors !== null && count($module->errors) > 0;
// Register
$this->modules[] = $module;
} catch (\Exception $exception) {
$this->getLog()->error('Unable to create module from '
. basename($file) . ', skipping. e = ' . $exception->getMessage());
}
}
}
return $this->modules;
}
/**
* Load all data types into an array for use throughout this request
* @return \Xibo\Widget\Definition\DataType[]
*/
private function loadDataTypes(): array
{
if ($this->dataTypes === null) {
$files = array_merge(
glob(PROJECT_ROOT . '/modules/datatypes/*.xml'),
glob(PROJECT_ROOT . '/custom/modules/datatypes/*.xml')
);
foreach ($files as $file) {
$this->dataTypes[] = $this->createDataTypeFromXml($file);
}
}
return $this->dataTypes ?? [];
}
/**
* Create a module from its XML definition
* @param string $file the path to the module definition
* @param array $modulesWithSettings
* @return \Xibo\Entity\Module
*/
private function createFromXml(string $file, array $modulesWithSettings): Module
{
// TODO: cache this into Stash
$xml = new \DOMDocument();
$xml->load($file);
$module = new Module($this->getStore(), $this->getLog(), $this->getDispatcher(), $this);
$module->moduleId = $this->getFirstValueOrDefaultFromXmlNode($xml, 'id');
$module->name = __($this->getFirstValueOrDefaultFromXmlNode($xml, 'name'));
$module->author = $this->getFirstValueOrDefaultFromXmlNode($xml, 'author');
$module->description = __($this->getFirstValueOrDefaultFromXmlNode($xml, 'description'));
$module->icon = $this->getFirstValueOrDefaultFromXmlNode($xml, 'icon');
$module->class = $this->getFirstValueOrDefaultFromXmlNode($xml, 'class');
$module->type = $this->getFirstValueOrDefaultFromXmlNode($xml, 'type');
$module->thumbnail = $this->getFirstValueOrDefaultFromXmlNode($xml, 'thumbnail');
$module->startWidth = intval($this->getFirstValueOrDefaultFromXmlNode($xml, 'startWidth'));
$module->startHeight = intval($this->getFirstValueOrDefaultFromXmlNode($xml, 'startHeight'));
$module->dataType = $this->getFirstValueOrDefaultFromXmlNode($xml, 'dataType');
$module->dataCacheKey = $this->getFirstValueOrDefaultFromXmlNode($xml, 'dataCacheKey');
$module->schemaVersion = intval($this->getFirstValueOrDefaultFromXmlNode($xml, 'schemaVersion'));
$module->compatibilityClass = $this->getFirstValueOrDefaultFromXmlNode($xml, 'compatibilityClass');
$module->showIn = $this->getFirstValueOrDefaultFromXmlNode($xml, 'showIn') ?? 'both';
$module->assignable = intval($this->getFirstValueOrDefaultFromXmlNode($xml, 'assignable'));
$module->regionSpecific = intval($this->getFirstValueOrDefaultFromXmlNode($xml, 'regionSpecific'));
$module->renderAs = $this->getFirstValueOrDefaultFromXmlNode($xml, 'renderAs');
$module->defaultDuration = intval($this->getFirstValueOrDefaultFromXmlNode($xml, 'defaultDuration'));
$module->hasThumbnail = intval($this->getFirstValueOrDefaultFromXmlNode($xml, 'hasThumbnail', 0));
// Validator classes
foreach ($xml->getElementsByTagName('validatorClass') as $node) {
/** @var \DOMNode $node */
if ($node instanceof \DOMElement) {
$module->validatorClass[] = trim($node->textContent);
}
}
// Event listeners
$module->onInitialize = $this->getFirstValueOrDefaultFromXmlNode($xml, 'onInitialize');
if (!empty($module->onInitialize)) {
$module->onInitialize = trim($module->onInitialize);
}
$module->onParseData = $this->getFirstValueOrDefaultFromXmlNode($xml, 'onParseData');
if (!empty($module->onParseData)) {
$module->onParseData = trim($module->onParseData);
}
$module->onDataLoad = $this->getFirstValueOrDefaultFromXmlNode($xml, 'onDataLoad');
if (!empty($module->onDataLoad)) {
$module->onDataLoad = trim($module->onDataLoad);
}
$module->onRender = $this->getFirstValueOrDefaultFromXmlNode($xml, 'onRender');
if (!empty($module->onRender)) {
$module->onRender = trim($module->onRender);
}
$module->onVisible = $this->getFirstValueOrDefaultFromXmlNode($xml, 'onVisible');
if (!empty($module->onVisible)) {
$module->onVisible = trim($module->onVisible);
}
// We might have sample data (usually only if there is a dataType)
$sampleData = $this->getFirstValueOrDefaultFromXmlNode($xml, 'sampleData');
if (!empty($sampleData)) {
$module->sampleData = json_decode(trim($sampleData), true);
}
// Legacy types.
try {
$module->legacyTypes = $this->parseLegacyTypes($xml->getElementsByTagName('legacyType'));
} catch (\Exception $e) {
$module->errors[] = __('Invalid legacyType');
$this->getLog()->error('Module ' . $module->moduleId . ' has invalid legacyType. e: ' . $e->getMessage());
}
// Group for non datatype modules
$module->group = [];
$groupNodes = $xml->getElementsByTagName('group');
foreach ($groupNodes as $groupNode) {
if ($groupNode instanceof \DOMElement) {
$module->group['id'] = $groupNode->getAttribute('id');
$module->group['icon'] = $groupNode->getAttribute('icon');
$module->group['name'] = $groupNode->textContent;
}
}
// Parse assets
try {
$module->assets = $this->parseAssets($xml->getElementsByTagName('assets'));
} catch (\Exception $e) {
$module->errors[] = __('Invalid assets');
$this->getLog()->error('Module ' . $module->moduleId
. ' has invalid assets. e: ' . $e->getMessage());
}
// Default values for remaining expected properties
$module->isInstalled = false;
$module->isError = false;
$module->errors = [];
$module->enabled = 0;
$module->previewEnabled = 0;
// Parse settings/property definitions.
try {
$module->settings = $this->parseProperties($xml->getElementsByTagName('settings'));
} catch (\Exception $e) {
$module->errors[] = __('Invalid settings');
$this->getLog()->error('Module ' . $module->moduleId . ' has invalid settings. e: ' . $e->getMessage());
}
// Add in any settings we already have
if (array_key_exists($module->moduleId, $modulesWithSettings)) {
$moduleSettings = $modulesWithSettings[$module->moduleId];
$module->isInstalled = true;
// make sure canvas is always enabled
if ($module->moduleId === 'core-canvas') {
$module->enabled = 1;
// update the table
if ($moduleSettings->getInt('enabled', ['default' => 0]) === 0) {
$this->getStore()->update(
'UPDATE `module` SET enabled = 1 WHERE `module`.moduleId = \'core-canvas\' ',
[]
);
}
} else {
$module->enabled = $moduleSettings->getInt('enabled', ['default' => 0]);
}
$module->previewEnabled = $moduleSettings->getInt('previewEnabled', ['default' => 0]);
$module->defaultDuration = $moduleSettings->getInt('defaultDuration', ['default' => 10]);
$settings = $moduleSettings->getString('settings');
if ($settings !== null) {
$settings = json_decode($settings, true);
foreach ($module->settings as $property) {
foreach ($settings as $settingId => $setting) {
if ($settingId === $property->id) {
$property->value = $setting;
break;
}
}
}
}
}
try {
$module->properties = $this->parseProperties($xml->getElementsByTagName('properties'), $module);
} catch (\Exception $e) {
$module->errors[] = __('Invalid properties');
$this->getLog()->error('Module ' . $module->moduleId . ' has invalid properties. e: ' . $e->getMessage());
}
// Parse group property definitions.
try {
$module->propertyGroups = $this->parsePropertyGroups($xml->getElementsByTagName('propertyGroups'));
} catch (\Exception $e) {
$module->errors[] = __('Invalid property groups');
$this->getLog()->error('Module ' . $module->moduleId . ' has invalid property groups. e: '
. $e->getMessage());
}
// Parse required elements.
$requiredElements = $this->getFirstValueOrDefaultFromXmlNode($xml, 'requiredElements');
if (!empty($requiredElements)) {
$module->requiredElements = explode(',', $requiredElements);
}
// Parse stencils
try {
$module->preview = $this->getStencils($xml->getElementsByTagName('preview'))[0] ?? null;
$module->stencil = $this->getStencils($xml->getElementsByTagName('stencil'))[0] ?? null;
} catch (\Exception $e) {
$module->errors[] = __('Invalid stencils');
$this->getLog()->error('Module ' . $module->moduleId . ' has invalid stencils. e: ' . $e->getMessage());
}
return $module;
}
/**
* Create DataType from XML
* @param string $file
* @return \Xibo\Widget\Definition\DataType
*/
private function createDataTypeFromXml(string $file): DataType
{
$xml = new \DOMDocument();
$xml->load($file);
$dataType = new DataType();
$dataType->id = $this->getFirstValueOrDefaultFromXmlNode($xml, 'id');
$dataType->name = $this->getFirstValueOrDefaultFromXmlNode($xml, 'name');
// Fields.
foreach ($xml->getElementsByTagName('field') as $field) {
if ($field instanceof \DOMElement) {
$dataType->addField(
$field->getAttribute('id'),
trim($field->textContent),
$field->getAttribute('type')
);
}
}
return $dataType;
}
}