~xibo-maintainers/xibo/tempel

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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
<?php
/*
 * Xibo - Digital Signage - http://www.xibo.org.uk
 * Copyright (C) 2006-2014 Daniel Garner
 *
 * 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\Controller;
use baseDAO;
use Config;
use database;
use DisplayGroup;
use DOMDocument;
use DOMXPath;
use finfo;
use FormManager;
use Session;
use Xibo\Helper\ApplicationState;
use Xibo\Helper\Date;
use Xibo\Helper\Help;
use Xibo\Helper\Log;
use Xibo\Helper\Theme;

defined('XIBO') or die("Sorry, you are not allowed to directly access this page.<br /> Please press the back button in your browser.");

class Display extends Base
{

    /**
     * Include display page template page based on sub page selected
     * @return
     */
    function displayPage()
    {
        // Configure the theme
        $id = uniqid();
        Theme::Set('id', $id);
        Theme::Set('form_meta', '<input type="hidden" name="p" value="display"><input type="hidden" name="q" value="DisplayGrid">');
        Theme::Set('filter_id', 'XiboFilterPinned' . uniqid('filter'));
        Theme::Set('pager', ApplicationState::Pager($id));

        // Default options
        if (\Kit::IsFilterPinned('display', 'DisplayFilter')) {
            $filter_pinned = 1;
            $filter_displaygroup = Session::Get('display', 'filter_displaygroup');
            $filter_display = Session::Get('display', 'filter_display');
            $filterMacAddress = Session::Get('display', 'filterMacAddress');
            $filter_showView = Session::Get('display', 'filter_showView');
            $filter_autoRefresh = Session::Get('display', 'filter_autoRefresh');
        } else {
            $filter_pinned = 0;
            $filter_displaygroup = NULL;
            $filter_display = NULL;
            $filterMacAddress = NULL;
            $filter_showView = 0;
            $filter_autoRefresh = 0;
        }

        $formFields = array();

        $formFields[] = FormManager::AddCombo(
            'filter_showView',
            __('View'),
            $filter_showView,
            array(
                array('key' => 0, 'value' => __('Default')),
                array('key' => 1, 'value' => __('Screen shot thumbnails')),
                array('key' => 2, 'value' => __('Screen shot thumbnails when Logged In')),
                array('key' => 3, 'value' => __('Extended Display Status')),
            ),
            'key',
            'value',
            NULL,
            't');

        $formFields[] = FormManager::AddText('filter_display', __('Name'), $filter_display, NULL, 'n');
        $formFields[] = FormManager::AddText('filterMacAddress', __('Mac Address'), $filterMacAddress, NULL, 'm');

        $displayGroups = $this->user->DisplayGroupList(0);
        array_unshift($displayGroups, array('displaygroupid' => '0', 'displaygroup' => 'All'));
        $formFields[] = FormManager::AddCombo(
            'filter_displaygroup',
            __('Display Group'),
            $filter_displaygroup,
            $displayGroups,
            'displaygroupid',
            'displaygroup',
            NULL,
            'd');

        $formFields[] = FormManager::AddNumber('filter_autoRefresh', __('Auto Refresh'), $filter_autoRefresh,
            NULL, 'r');

        $formFields[] = FormManager::AddCheckbox('XiboFilterPinned', __('Keep Open'),
            $filter_pinned, NULL,
            'k');

        // Call to render the template
        Theme::Set('header_text', __('Displays'));
        Theme::Set('form_fields', $formFields);
        $this->getState()->html .= Theme::RenderReturn('grid_render');
    }

    function actionMenu()
    {

        return array(
            array('title' => __('Filter'),
                'class' => '',
                'selected' => false,
                'link' => '#',
                'help' => __('Open the filter form'),
                'onclick' => 'ToggleFilterView(\'Filter\')'
            )
        );
    }

    /**
     * Modifies the selected display record
     * @return
     */
    function modify()
    {


        $response = $this->getState();

        $displayObject = new Display();
        $displayObject->displayId = \Xibo\Helper\Sanitize::getInt('displayid');

        $auth = $this->user->DisplayGroupAuth($this->GetDisplayGroupId($displayObject->displayId), true);
        if (!$auth->edit)
            trigger_error(__('You do not have permission to edit this display'), E_USER_ERROR);

        if (!$displayObject->Load())
            trigger_error($displayObject->GetErrorMessage(), E_USER_ERROR);

        // Update properties
        $displayObject->display = \Xibo\Helper\Sanitize::getString('display');
        $displayObject->description = \Xibo\Helper\Sanitize::getString('description');
        $displayObject->isAuditing = \Xibo\Helper\Sanitize::getInt('auditing');
        $displayObject->defaultLayoutId = \Xibo\Helper\Sanitize::getInt('defaultlayoutid');
        $displayObject->licensed = \Xibo\Helper\Sanitize::getInt('licensed');
        $displayObject->incSchedule = \Xibo\Helper\Sanitize::getInt('inc_schedule');
        $displayObject->emailAlert = \Xibo\Helper\Sanitize::getInt('email_alert');
        $displayObject->alertTimeout = \Xibo\Helper\Sanitize::getCheckbox('alert_timeout');
        $displayObject->wakeOnLanEnabled = \Xibo\Helper\Sanitize::getCheckbox('wakeOnLanEnabled');
        $displayObject->wakeOnLanTime = \Xibo\Helper\Sanitize::getString('wakeOnLanTime');
        $displayObject->broadCastAddress = \Xibo\Helper\Sanitize::getString('broadCastAddress');
        $displayObject->secureOn = \Xibo\Helper\Sanitize::getString('secureOn');
        $displayObject->cidr = \Xibo\Helper\Sanitize::getString('cidr');
        $displayObject->latitude = \Kit::GetParam('latitude', _POST, _DOUBLE);
        $displayObject->longitude = \Kit::GetParam('longitude', _POST, _DOUBLE);
        $displayObject->displayProfileId = \Xibo\Helper\Sanitize::getInt('displayprofileid');

        if (!$displayObject->Edit())
            trigger_error($displayObject->GetErrorMessage(), E_USER_ERROR);

        $response->SetFormSubmitResponse(__('Display Saved.'));

    }

    /**
     * Modify Display form
     */
    function displayForm()
    {
        $response = $this->getState();

        // Get the display Id
        $displayObject = new Display();
        $displayObject->displayId = \Xibo\Helper\Sanitize::getInt('displayid');

        $auth = $this->user->DisplayGroupAuth($this->GetDisplayGroupId($displayObject->displayId), true);
        if (!$auth->edit)
            trigger_error(__('You do not have permission to edit this display'), E_USER_ERROR);

        // Load this display
        if (!$displayObject->Load())
            trigger_error($displayObject->GetErrorMessage(), E_USER_ERROR);

        // Set some information about the form
        Theme::Set('form_id', 'DisplayEditForm');
        Theme::Set('form_action', 'index.php?p=display&q=modify');
        Theme::Set('form_meta', '<input type="hidden" name="displayid" value="' . $displayObject->displayId . '" />');

        // Column 1
        $formFields = array();
        $formFields[] = FormManager::AddText('display', __('Display'), $displayObject->display,
            __('The Name of the Display - (1 - 50 characters).'), 'd', 'required');

        $formFields[] = FormManager::AddText('hardwareKey', __('Display\'s Hardware Key'), $displayObject->license,
            __('A unique identifier for this display.'), 'h', 'required', NULL, false);

        $formFields[] = FormManager::AddText('description', __('Description'), $displayObject->description,
            __('A description - (1 - 254 characters).'), 'p', 'maxlength="50"');

        $formFields[] = FormManager::AddCombo(
            'licensed',
            __('Licence Display?'),
            $displayObject->licensed,
            array(array('licensedid' => '1', 'licensed' => 'Yes'), array('licensedid' => '0', 'licensed' => 'No')),
            'licensedid',
            'licensed',
            __('Use one of the available licenses for this display?'),
            'l');

        $formFields[] = FormManager::AddCombo(
            'defaultlayoutid',
            __('Default Layout'),
            $displayObject->defaultLayoutId,
            $this->user->LayoutList(),
            'layoutid',
            'layout',
            __('The Default Layout to Display where there is no other content.'),
            't');

        Theme::Set('form_fields_general', $formFields);

        // Maintenance
        $formFields = array();
        $formFields[] = FormManager::AddCombo(
            'email_alert',
            __('Email Alerts'),
            $displayObject->emailAlert,
            array(array('id' => '1', 'value' => 'Yes'), array('id' => '0', 'value' => 'No')),
            'id',
            'value',
            __('Do you want to be notified by email if there is a problem with this display?'),
            'a');

        $formFields[] = FormManager::AddCheckbox('alert_timeout', __('Use the Global Timeout?'), $displayObject->alertTimeout,
            __('Should this display be tested against the global time out or the client collection interval?'),
            'o');

        Theme::Set('form_fields_maintenance', $formFields);

        // Location
        $formFields = array();

        $formFields[] = FormManager::AddNumber('latitude', __('Latitude'), $displayObject->latitude,
            __('The Latitude of this display'), 'g');

        $formFields[] = FormManager::AddNumber('longitude', __('Longitude'), $displayObject->longitude,
            __('The Longitude of this Display'), 'g');

        Theme::Set('form_fields_location', $formFields);

        // Wake on LAN
        $formFields = array();

        $formFields[] = FormManager::AddCheckbox('wakeOnLanEnabled', __('Enable Wake on LAN'),
            $displayObject->wakeOnLanEnabled, __('Wake on Lan requires the correct network configuration to route the magic packet to the display PC'),
            'w');

        $formFields[] = FormManager::AddText('broadCastAddress', __('BroadCast Address'), (($displayObject->broadCastAddress == '') ? $displayObject->clientAddress : $displayObject->broadCastAddress),
            __('The IP address of the remote host\'s broadcast address (or gateway)'), 'b');

        $formFields[] = FormManager::AddText('secureOn', __('Wake on LAN SecureOn'), $displayObject->secureOn,
            __('Enter a hexadecimal password of a SecureOn enabled Network Interface Card (NIC) of the remote host. Enter a value in this pattern: \'xx-xx-xx-xx-xx-xx\'. Leave the following field empty, if SecureOn is not used (for example, because the NIC of the remote host does not support SecureOn).'), 's');

        $formFields[] = FormManager::AddText('wakeOnLanTime', __('Wake on LAN Time'), $displayObject->wakeOnLanTime,
            __('The time this display should receive the WOL command, using the 24hr clock - e.g. 19:00. Maintenance must be enabled.'), 't');

        $formFields[] = FormManager::AddText('cidr', __('Wake on LAN CIDR'), $displayObject->cidr,
            __('Enter a number within the range of 0 to 32 in the following field. Leave the following field empty, if no subnet mask should be used (CIDR = 0). If the remote host\'s broadcast address is unknown: Enter the host name or IP address of the remote host in Broad Cast Address and enter the CIDR subnet mask of the remote host in this field.'), 'c');

        Theme::Set('form_fields_wol', $formFields);

        // Advanced
        $formFields = array();

        $displayProfileList = $this->user->DisplayProfileList(NULL, array('type' => $displayObject->clientType));
        array_unshift($displayProfileList, array('displayprofileid' => 0, 'name' => ''));

        $formFields[] = FormManager::AddCombo(
            'displayprofileid',
            __('Settings Profile?'),
            $displayObject->displayProfileId,
            $displayProfileList,
            'displayprofileid',
            'name',
            __('What display profile should this display use?'),
            'p');

        $formFields[] = FormManager::AddCombo(
            'inc_schedule',
            __('Interleave Default'),
            $displayObject->incSchedule,
            array(array('id' => '1', 'value' => 'Yes'), array('id' => '0', 'value' => 'No')),
            'id',
            'value',
            __('Whether to always put the default layout into the cycle.'),
            'i');

        $formFields[] = FormManager::AddCombo(
            'auditing',
            __('Auditing'),
            $displayObject->isAuditing,
            array(array('id' => '1', 'value' => 'Yes'), array('id' => '0', 'value' => 'No')),
            'id',
            'value',
            __('Collect auditing from this client. Should only be used if there is a problem with the display.'),
            'a');

        // Show the resolved settings for this display.
        $formFields[] = FormManager::AddMessage(__('The settings for this display are shown below. They are taken from the active Display Profile for this Display, which can be changed in Display Settings. If you have altered the Settings Profile above, you will need to save and re-show the form.'));

        // Build a table for the settings to be shown in
        $cols = array(
            array('name' => 'title', 'title' => __('Setting')),
            array('name' => 'valueString', 'title' => __('Value'))
        );

        // Get the settings from the profile
        $profile = $displayObject->getSettingsProfile();

        // Go through each one, and see if it is a drop down
        for ($i = 0; $i < count($profile); $i++) {
            // Always update the value string with the source value
            $profile[$i]['valueString'] = $profile[$i]['value'];

            // Overwrite the value string when we are dealing with dropdowns
            if ($profile[$i]['fieldType'] == 'dropdown') {
                // Update our value
                foreach ($profile[$i]['options'] as $option) {
                    if ($option['id'] == $profile[$i]['value'])
                        $profile[$i]['valueString'] = $option['value'];
                }
            } else if ($profile[$i]['fieldType'] == 'timePicker') {
                $profile[$i]['valueString'] = Date::getSystemDate($profile[$i]['value'] / 1000, 'H:i');
            }
        }

        Theme::Set('table_cols', $cols);
        Theme::Set('table_rows', $profile);
        $formFields[] = FormManager::AddRaw(Theme::RenderReturn('table_render'));

        Theme::Set('form_fields_advanced', $formFields);

        // Two tabs
        $tabs = array();
        $tabs[] = FormManager::AddTab('general', __('General'));
        $tabs[] = FormManager::AddTab('location', __('Location'));
        $tabs[] = FormManager::AddTab('maintenance', __('Maintenance'));
        $tabs[] = FormManager::AddTab('wol', __('Wake on LAN'));
        $tabs[] = FormManager::AddTab('advanced', __('Advanced'));

        Theme::Set('form_tabs', $tabs);

        $response->SetFormRequestResponse(NULL, __('Edit a Display'), '650px', '350px');
        $response->AddButton(__('Help'), 'XiboHelpRender("' . Help::Link('Display', 'Edit') . '")');
        $response->AddButton(__('Cancel'), 'XiboDialogClose()');
        $response->AddButton(__('Save'), '$("#DisplayEditForm").submit()');

    }

    /**
     * Grid of Displays
     * @return
     */
    function DisplayGrid()
    {
        // validate displays so we get a realistic view of the table
        Display::ValidateDisplays();


        $user =& $this->user;
        $response = new ApplicationState();

        // Filter by Name
        $filter_display = \Xibo\Helper\Sanitize::getString('filter_display');
        \Session::Set('display', 'filter_display', $filter_display);

        // Filter by Name
        $filterMacAddress = \Xibo\Helper\Sanitize::getString('filterMacAddress');
        \Session::Set('display', 'filterMacAddress', $filterMacAddress);

        // Display Group
        $filter_displaygroupid = \Xibo\Helper\Sanitize::getInt('filter_displaygroup');
        \Session::Set('display', 'filter_displaygroup', $filter_displaygroupid);

        // Thumbnail?
        $filter_showView = \Xibo\Helper\Sanitize::getInt('filter_showView');
        \Session::Set('display', 'filter_showView', $filter_showView);

        // filter_autoRefresh?
        $filter_autoRefresh = \Kit::GetParam('filter_autoRefresh', _REQUEST, _INT, 0);
        \Session::Set('display', 'filter_autoRefresh', $filter_autoRefresh);

        // Pinned option?
        \Session::Set('display', 'DisplayFilter', \Kit::GetParam('XiboFilterPinned', _REQUEST, _CHECKBOX, 'off'));

        $displays = $user->DisplayList(array('displayid'), array('displaygroupid' => $filter_displaygroupid, 'display' => $filter_display, 'macAddress' => $filterMacAddress));

        if (!is_array($displays)) {
            trigger_error($db->error());
            trigger_error(__('Unable to get list of displays'), E_USER_ERROR);
        }

        // Do we want to make a VNC link out of the display name?
        $vncTemplate = Config::GetSetting('SHOW_DISPLAY_AS_VNCLINK');
        $linkTarget = \Xibo\Helper\Sanitize::string(Config::GetSetting('SHOW_DISPLAY_AS_VNC_TGT'));

        $cols = array(
            array('name' => 'displayid', 'title' => __('ID')),
            array('name' => 'displayWithLink', 'title' => __('Display')),
            array('name' => 'status', 'title' => __('Status'), 'icons' => true, 'iconDescription' => 'statusDescription'),
            array('name' => 'licensed', 'title' => __('License'), 'icons' => true),
            array('name' => 'currentLayout', 'title' => __('Current Layout'), 'hidden' => ($filter_showView != 3)),
            array('name' => 'storageAvailableSpaceFormatted', 'title' => __('Storage Available'), 'hidden' => ($filter_showView != 3)),
            array('name' => 'storageTotalSpaceFormatted', 'title' => __('Storage Total'), 'hidden' => ($filter_showView != 3)),
            array('name' => 'storagePercentage', 'title' => __('Storage Free %'), 'hidden' => ($filter_showView != 3)),
            array('name' => 'description', 'title' => __('Description'), 'hidden' => ($filter_showView != 0)),
            array('name' => 'layout', 'title' => __('Default Layout'), 'hidden' => ($filter_showView == 1 || $filter_showView == 2)),
            array('name' => 'inc_schedule', 'title' => __('Interleave Default'), 'icons' => true, 'hidden' => ($filter_showView == 1 || $filter_showView == 2)),
            array('name' => 'email_alert', 'title' => __('Email Alert'), 'icons' => true, 'hidden' => ($filter_showView != 0)),
            array('name' => 'loggedin', 'title' => __('Logged In'), 'icons' => true),
            array('name' => 'lastaccessed', 'title' => __('Last Accessed')),
            array('name' => 'clientaddress', 'title' => __('IP Address'), 'hidden' => ($filter_showView == 1)),
            array('name' => 'macaddress', 'title' => __('Mac Address'), 'hidden' => ($filter_showView == 1)),
            array('name' => 'screenShotRequested', 'title' => __('Screen shot?'), 'icons' => true, 'hidden' => ($filter_showView != 1 && $filter_showView != 2)),
            array('name' => 'thumbnail', 'title' => __('Thumbnail'), 'hidden' => ($filter_showView != 1 && $filter_showView != 2))
        );

        Theme::Set('table_cols', $cols);
        Theme::Set('rowClass', 'rowColor');

        $rows = array();

        foreach ($displays as $row) {
            // VNC Template as display name?
            if ($vncTemplate != '' && $row['clientaddress'] != '') {
                if ($linkTarget == '')
                    $linkTarget = '_top';

                $row['displayWithLink'] = sprintf('<a href="' . $vncTemplate . '" title="VNC to ' . $row['display'] . '" target="' . $linkTarget . '">' . Theme::Prepare($row['display']) . '</a>', $row['clientaddress']);
            } else {
                $row['displayWithLink'] = $row['display'];
            }

            // Format last accessed
            $row['lastaccessed'] = Date::getLocalDate($row['lastaccessed']);

            // Create some login lights
            $row['rowColor'] = ($row['mediainventorystatus'] == 1) ? 'success' : (($row['mediainventorystatus'] == 2) ? 'danger' : 'warning');
            $row['status'] = ($row['mediainventorystatus'] == 1) ? 1 : (($row['mediainventorystatus'] == 2) ? 0 : -1);

            // Set some text for the display status
            switch ($row['status']) {
                case 1:
                    $row['statusDescription'] = __('Display is up to date');
                    break;

                case 2:
                    $row['statusDescription'] = __('Display is downloading new files');
                    break;

                case 3:
                    $row['statusDescription'] = __('Display is out of date but has not yet checked in with the server');
                    break;

                default:
                    $row['statusDescription'] = __('Unknown Display Status');
            }

            // Thumbnail
            $row['thumbnail'] = '';
            // If we aren't logged in, and we are showThumbnail == 2, then show a circle
            if ($filter_showView == 2 && $row['loggedin'] == 0) {
                $row['thumbnail'] = '<i class="fa fa-times-circle"></i>';
            } else if ($filter_showView <> 0 && file_exists(Config::GetSetting('LIBRARY_LOCATION') . 'screenshots/' . $row['displayid'] . '_screenshot.jpg')) {
                $row['thumbnail'] = '<a data-toggle="lightbox" data-type="image" href="index.php?p=display&q=ScreenShot&DisplayId=' . $row['displayid'] . '"><img class="display-screenshot" src="index.php?p=display&q=ScreenShot&DisplayId=' . $row['displayid'] . '&' . \Kit::uniqueId() . '" /></a>';
            }

            // Format the storage available / total space
            $row['storageAvailableSpaceFormatted'] = \Kit::formatBytes($row['storageAvailableSpace']);
            $row['storageTotalSpaceFormatted'] = \Kit::formatBytes($row['storageTotalSpace']);
            $row['storagePercentage'] = ($row['storageTotalSpace'] == 0) ? 100 : round($row['storageAvailableSpace'] / $row['storageTotalSpace'] * 100.0, 2);

            // Edit and Delete buttons first
            if ($row['edit'] == 1) {
                // Edit
                $row['buttons'][] = array(
                    'id' => 'display_button_edit',
                    'url' => 'index.php?p=display&q=displayForm&displayid=' . $row['displayid'],
                    'text' => __('Edit')
                );
            }

            // Delete
            if ($row['del'] == 1) {
                $row['buttons'][] = array(
                    'id' => 'display_button_delete',
                    'url' => 'index.php?p=display&q=DeleteForm&displayid=' . $row['displayid'],
                    'text' => __('Delete')
                );
            }

            if ($row['edit'] == 1 || $row['del'] == 1) {
                $row['buttons'][] = array('linkType' => 'divider');
            }

            // Schedule Now
            if ($row['edit'] == 1 || Config::GetSetting('SCHEDULE_WITH_VIEW_PERMISSION') == 'Yes') {
                $row['buttons'][] = array(
                    'id' => 'display_button_schedulenow',
                    'url' => 'index.php?p=schedule&q=ScheduleNowForm&displayGroupId=' . $row['displaygroupid'],
                    'text' => __('Schedule Now')
                );
            }

            if ($row['edit'] == 1) {

                // Default Layout
                $row['buttons'][] = array(
                    'id' => 'display_button_defaultlayout',
                    'url' => 'index.php?p=display&q=DefaultLayoutForm&DisplayId=' . $row['displayid'],
                    'text' => __('Default Layout')
                );

                // File Associations
                $row['buttons'][] = array(
                    'id' => 'displaygroup_button_fileassociations',
                    'url' => 'index.php?p=displaygroup&q=FileAssociations&DisplayGroupID=' . $row['displaygroupid'],
                    'text' => __('Assign Files')
                );

                // Screen Shot
                $row['buttons'][] = array(
                    'id' => 'display_button_requestScreenShot',
                    'url' => 'index.php?p=display&q=RequestScreenShotForm&displayId=' . $row['displayid'],
                    'text' => __('Request Screen Shot'),
                    'multi-select' => true,
                    'dataAttributes' => array(
                        array('name' => 'multiselectlink', 'value' => 'index.php?p=display&q=RequestScreenShot'),
                        array('name' => 'rowtitle', 'value' => $row['display']),
                        array('name' => 'displayId', 'value' => $row['displayid'])
                    )
                );

                $row['buttons'][] = array('linkType' => 'divider');
            }

            // Media Inventory
            $row['buttons'][] = array(
                'id' => 'display_button_mediainventory',
                'url' => 'index.php?p=display&q=MediaInventory&DisplayId=' . $row['displayid'],
                'text' => __('Media Inventory')
            );

            if ($row['edit'] == 1) {

                // Logs
                $row['buttons'][] = array(
                    'id' => 'displaygroup_button_logs',
                    'url' => 'index.php?p=log&q=LastHundredForDisplay&displayid=' . $row['displayid'],
                    'text' => __('Recent Log')
                );

                $row['buttons'][] = array('linkType' => 'divider');
            }

            if ($row['modifypermissions'] == 1) {

                // Display Groups
                $row['buttons'][] = array(
                    'id' => 'display_button_group_membership',
                    'url' => 'index.php?p=display&q=MemberOfForm&DisplayID=' . $row['displayid'],
                    'text' => __('Display Groups')
                );

                // Permissions
                $row['buttons'][] = array(
                    'id' => 'display_button_group_membership',
                    'url' => 'index.php?p=displaygroup&q=PermissionsForm&DisplayGroupID=' . $row['displaygroupid'],
                    'text' => __('Permissions')
                );

                // Version Information
                $row['buttons'][] = array(
                    'id' => 'display_button_version_instructions',
                    'url' => 'index.php?p=displaygroup&q=VersionInstructionsForm&displaygroupid=' . $row['displaygroupid'] . '&displayid=' . $row['displayid'],
                    'text' => __('Version Information')
                );

                $row['buttons'][] = array('linkType' => 'divider');
            }

            if ($row['edit'] == 1) {
                // Wake On LAN
                $row['buttons'][] = array(
                    'id' => 'display_button_wol',
                    'url' => 'index.php?p=display&q=WakeOnLanForm&DisplayId=' . $row['displayid'],
                    'text' => __('Wake on LAN')
                );
            }

            // Assign this to the table row
            $rows[] = $row;
        }

        Theme::Set('table_rows', $rows);

        $output = Theme::RenderReturn('table_render');

        $response->SetGridResponse($output);
        $response->refresh = \Kit::GetParam('filter_autoRefresh', _REQUEST, _INT, 0);

    }

    /**
     * Delete form
     */
    function DeleteForm()
    {

        $user = $this->getUser();
        $response = $this->getState();
        $displayid = \Xibo\Helper\Sanitize::getInt('displayid');

        // Auth
        $auth = $this->user->DisplayGroupAuth($this->GetDisplayGroupId($displayid), true);
        if (!$auth->del)
            trigger_error(__('You do not have permission to edit this display'), E_USER_ERROR);

        Theme::Set('form_id', 'DisplayDeleteForm');
        Theme::Set('form_action', 'index.php?p=display&q=Delete');
        Theme::Set('form_meta', '<input type="hidden" name="displayid" value="' . $displayid . '">');

        Theme::Set('form_fields', array(FormManager::AddMessage(__('Are you sure you want to delete this display? This cannot be undone.'))));

        $response->SetFormRequestResponse(NULL, __('Delete this Display?'), '350px', '210');
        $response->AddButton(__('Help'), 'XiboHelpRender("' . Help::Link('Display', 'Delete') . '")');
        $response->AddButton(__('No'), 'XiboDialogClose()');
        $response->AddButton(__('Yes'), '$("#DisplayDeleteForm").submit()');

    }

    /**
     * Delete a display
     */
    function Delete()
    {



        $response = $this->getState();
        $displayid = \Kit::GetParam('displayid', _POST, _INT, 0);

        $auth = $this->user->DisplayGroupAuth($this->GetDisplayGroupId($displayid), true);
        if (!$auth->del)
            trigger_error(__('You do not have permission to edit this display'), E_USER_ERROR);

        if ($displayid == 0)
            trigger_error(__("No Display selected for Deletion."));

        $displayObject = new Display($db);

        if (!$displayObject->Delete($displayid))
            trigger_error($displayObject->GetErrorMessage(), E_USER_ERROR);

        $response->SetFormSubmitResponse(__("The Display has been Deleted"));

    }

    /**
     * Form for editing the default layout of a display
     */
    public function DefaultLayoutForm()
    {

        $response = $this->getState();

        $displayId = \Xibo\Helper\Sanitize::getInt('DisplayId');

        $auth = $this->user->DisplayGroupAuth($this->GetDisplayGroupId($displayId), true);
        if (!$auth->edit)
            trigger_error(__('You do not have permission to edit this display'), E_USER_ERROR);

        if (!$defaultLayoutId = $this->db->GetSingleValue(sprintf("SELECT defaultlayoutid FROM display WHERE displayid = %d", $displayId), 'defaultlayoutid', _INT)) {
            trigger_error($db->error());
            trigger_error(__('Unable to get the default layout'), E_USER_ERROR);
        }

        Theme::Set('form_id', 'DefaultLayoutForm');
        Theme::Set('form_action', 'index.php?p=display&q=DefaultLayout');
        Theme::Set('form_meta', '<input type="hidden" name="DisplayId" value="' . $displayId . '">');

        $formFields = array();
        $formFields[] = FormManager::AddCombo(
            'defaultlayoutid',
            __('Default Layout'),
            $defaultLayoutId,
            $this->user->LayoutList(),
            'layoutid',
            'layout',
            __('The Default Layout will be shown there are no other scheduled Layouts. It is usually a full screen logo or holding image.'),
            'd');

        Theme::Set('form_fields', $formFields);

        $response->SetFormRequestResponse(NULL, __('Edit Default Layout'), '300px', '150px');
        $response->AddButton(__('Help'), 'XiboHelpRender("' . Help::Link('Display', 'DefaultLayout') . '")');
        $response->AddButton(__('Cancel'), 'XiboDialogClose()');
        $response->AddButton(__('Save'), '$("#DefaultLayoutForm").submit()');

    }

    /**
     * Edit the default layout for a display
     */
    public function DefaultLayout()
    {



        $response = $this->getState();
        $displayObject = new Display($db);

        $displayId = \Xibo\Helper\Sanitize::getInt('DisplayId');
        $defaultLayoutId = \Xibo\Helper\Sanitize::getInt('defaultlayoutid');

        $auth = $this->user->DisplayGroupAuth($this->GetDisplayGroupId($displayId), true);
        if (!$auth->edit)
            trigger_error(__('You do not have permission to edit this display'), E_USER_ERROR);

        if (!$displayObject->EditDefaultLayout($displayId, $defaultLayoutId))
            trigger_error(__('Cannot Edit this Display'), E_USER_ERROR);

        $response->SetFormSubmitResponse(__('Display Saved.'));

    }

    /**
     * Shows the inventory XML for the display
     */
    public function MediaInventory()
    {

        $response = $this->getState();
        $displayId = \Xibo\Helper\Sanitize::getInt('DisplayId');

        $auth = $this->user->DisplayGroupAuth($this->GetDisplayGroupId($displayId), true);
        if (!$auth->view)
            trigger_error(__('You do not have permission to view this display'), E_USER_ERROR);

        if ($displayId == 0)
            trigger_error(__('No DisplayId Given'));

        // Get the media inventory xml for this display
        $SQL = "SELECT IFNULL(MediaInventoryXml, '<xml></xml>') AS MediaInventoryXml FROM display WHERE DisplayId = %d";
        $SQL = sprintf($SQL, $displayId);

        if (!$mediaInventoryXml = $db->GetSingleValue($SQL, 'MediaInventoryXml', _HTMLSTRING)) {
            trigger_error($db->error());
            trigger_error(__('Unable to get the Inventory for this Display'), E_USER_ERROR);
        }

        // Load the XML into a DOMDocument
        $document = new DOMDocument("1.0");

        if (!$document->loadXML($mediaInventoryXml))
            trigger_error(__('Invalid Media Inventory'), E_USER_ERROR);

        $cols = array(
            array('name' => 'id', 'title' => __('ID')),
            array('name' => 'type', 'title' => __('Type')),
            array('name' => 'complete', 'title' => __('Complete')),
            array('name' => 'last_checked', 'title' => __('Last Checked'))
        );
        Theme::Set('table_cols', $cols);

        // Need to parse the XML and return a set of rows
        $xpath = new DOMXPath($document);
        $fileNodes = $xpath->query("//file");

        $rows = array();

        foreach ($fileNodes as $node) {
            $row = array();
            $row['type'] = $node->getAttribute('type');
            $row['id'] = $node->getAttribute('id');
            $row['complete'] = ($node->getAttribute('complete') == 0) ? __('No') : __('Yes');
            $row['last_checked'] = $node->getAttribute('lastChecked');
            $row['md5'] = $node->getAttribute('md5');

            $rows[] = $row;
        }

        // Store the table rows
        Theme::Set('table_rows', $rows);

        $response->SetFormRequestResponse(Theme::RenderReturn('table_render'), __('Media Inventory'), '550px', '350px');
        $response->AddButton(__('Help'), 'XiboHelpRender("' . Help::Link('Display', 'MediaInventory') . '")');
        $response->AddButton(__('Close'), 'XiboDialogClose()');

    }

    /**
     * Get DisplayGroupID
     * @param <type> $displayId
     */
    private function GetDisplayGroupId($displayId)
    {
        $sql = "SELECT displaygroup.DisplayGroupID ";
        $sql .= "  FROM `displaygroup` ";
        $sql .= "   INNER JOIN `lkdisplaydg` ON lkdisplaydg.DisplayGroupID = displaygroup.DisplayGroupID ";
        $sql .= " WHERE displaygroup.IsDisplaySpecific = 1 AND lkdisplaydg.DisplayID = %d";

        if (!$id = $this->db->GetSingleValue(sprintf($sql, $displayId), 'DisplayGroupID', _INT)) {
            trigger_error($this->db->error());
            trigger_error(__('Unable to determine permissions'), E_USER_ERROR);
        }

        return $id;
    }

    /**
     * Member of Display Groups Form
     */
    public function MemberOfForm()
    {

        $response = $this->getState();
        $displayID = \Xibo\Helper\Sanitize::getInt('DisplayID');

        // Auth
        $auth = $this->user->DisplayGroupAuth($this->GetDisplayGroupId($displayID), true);
        if (!$auth->modifyPermissions)
            trigger_error(__('You do not have permission to change Display Groups on this display'), E_USER_ERROR);

        // There needs to be two lists here.
        //  - DisplayGroups this Display is already assigned to
        //  - DisplayGroups this Display could be assigned to

        // Set some information about the form
        Theme::Set('displaygroups_assigned_id', 'displaysIn');
        Theme::Set('displaygroups_available_id', 'displaysOut');
        Theme::Set('displaygroups_assigned_url', 'index.php?p=display&q=SetMemberOf&DisplayID=' . $displayID);

        // Display Groups Assigned
        $SQL = "";
        $SQL .= "SELECT displaygroup.DisplayGroupID, ";
        $SQL .= "       displaygroup.DisplayGroup, ";
        $SQL .= "       CONCAT('DisplayGroupID_', displaygroup.DisplayGroupID) AS list_id ";
        $SQL .= "FROM   displaygroup ";
        $SQL .= "   INNER JOIN lkdisplaydg ON lkdisplaydg.DisplayGroupID = displaygroup.DisplayGroupID ";
        $SQL .= sprintf("WHERE  lkdisplaydg.DisplayID   = %d ", $displayID);
        $SQL .= " AND displaygroup.IsDisplaySpecific = 0 ";
        $SQL .= " ORDER BY displaygroup.DisplayGroup ";

        $displaygroupsAssigned = $db->GetArray($SQL);

        if (!is_array($displaygroupsAssigned)) {
            trigger_error($db->error());
            trigger_error(__('Error getting Display Groups'), E_USER_ERROR);
        }

        Theme::Set('displaygroups_assigned', $displaygroupsAssigned);

        // Display Groups not assigned
        $SQL = "";
        $SQL .= "SELECT displaygroup.DisplayGroupID, ";
        $SQL .= "       displaygroup.DisplayGroup, ";
        $SQL .= "       CONCAT('DisplayGroupID_', displaygroup.DisplayGroupID) AS list_id ";
        $SQL .= "  FROM displaygroup ";
        $SQL .= " WHERE displaygroup.IsDisplaySpecific = 0 ";
        $SQL .= " AND displaygroup.DisplayGroupID NOT IN ";
        $SQL .= "       (SELECT lkdisplaydg.DisplayGroupID ";
        $SQL .= "          FROM lkdisplaydg ";
        $SQL .= sprintf(" WHERE  lkdisplaydg.DisplayID   = %d ", $displayID);
        $SQL .= "       )";
        $SQL .= " ORDER BY displaygroup.DisplayGroup ";

        Log::notice($SQL);

        $displaygroups_available = $db->GetArray($SQL);

        if (!is_array($displaygroups_available)) {
            trigger_error($db->error());
            trigger_error(__('Error getting Display Groups'), E_USER_ERROR);
        }

        Theme::Set('displaygroups_available', $displaygroups_available);

        // Render the theme
        $form = Theme::RenderReturn('display_form_group_assign');

        $response->SetFormRequestResponse($form, __('Manage Membership'), '400', '375', 'DisplayGroupManageMembersCallBack');
        $response->AddButton(__('Help'), 'XiboHelpRender("' . Help::Link('DisplayGroup', 'Members') . '")');
        $response->AddButton(__('Cancel'), 'XiboDialogClose()');
        $response->AddButton(__('Save'), 'DisplayGroupMembersSubmit()');

    }

    /**
     * Sets the Members of a group
     * @return
     */
    public function SetMemberOf()
    {

        $response = $this->getState();


        $displayGroupObject = new DisplayGroup($db);

        $displayID = \Xibo\Helper\Sanitize::getInt('DisplayID');
        $displayGroups = \Kit::GetParam('DisplayGroupID', _POST, _ARRAY, array());
        $members = array();

        // Get a list of current members
        $SQL = "";
        $SQL .= "SELECT displaygroup.DisplayGroupID ";
        $SQL .= "FROM   displaygroup ";
        $SQL .= "   INNER JOIN lkdisplaydg ON lkdisplaydg.DisplayGroupID = displaygroup.DisplayGroupID ";
        $SQL .= sprintf("WHERE  lkdisplaydg.DisplayID   = %d ", $displayID);
        $SQL .= " AND displaygroup.IsDisplaySpecific = 0 ";

        if (!$resultIn = $db->query($SQL)) {
            trigger_error($db->error());
            trigger_error(__('Error getting Display Groups'), E_USER_ERROR);
        }

        while ($row = $db->get_assoc_row($resultIn)) {
            // Test whether this ID is in the array or not
            $displayGroupID = \Xibo\Helper\Sanitize::int($row['DisplayGroupID']);

            if (!in_array($displayGroupID, $displayGroups)) {
                // Its currently assigned but not in the $displays array
                //  so we unassign
                if (!$displayGroupObject->Unlink($displayGroupID, $displayID)) {
                    trigger_error($displayGroupObject->GetErrorMessage(), E_USER_ERROR);
                }
            } else {
                $members[] = $displayGroupID;
            }
        }

        foreach ($displayGroups as $displayGroupID) {
            // Add any that are missing
            if (!in_array($displayGroupID, $members)) {
                if (!$displayGroupObject->Link($displayGroupID, $displayID)) {
                    trigger_error($displayGroupObject->GetErrorMessage(), E_USER_ERROR);
                }
            }
        }

        $response->SetFormSubmitResponse(__('Group membership set'), false);

    }

    /**
     * Form for wake on Lan
     */
    public function WakeOnLanForm()
    {

        $response = $this->getState();

        $displayId = \Xibo\Helper\Sanitize::getInt('DisplayId');

        // Get the MAC Address
        $macAddress = $db->GetSingleValue(sprintf("SELECT MacAddress FROM `display` WHERE DisplayID = %d", $displayId), 'MacAddress', _STRING);

        if (!$macAddress || $macAddress == '')
            trigger_error(__('This display has no mac address recorded against it yet. Make sure the display is running.'), E_USER_ERROR);

        // Set some information about the form
        Theme::Set('form_id', 'WakeOnLanForm');
        Theme::Set('form_action', 'index.php?p=display&q=WakeOnLan');
        Theme::Set('form_meta', '<input type="hidden" name="DisplayId" value="' . $displayId . '"><input type="hidden" name="MacAddress" value="' . $macAddress . '">');

        Theme::Set('form_fields', array(FormManager::AddMessage(__('Are you sure you want to send a Wake On Lan message to this display?'))));

        $response->SetFormRequestResponse(NULL, __('Wake On Lan'), '300px', '250px');
        $response->AddButton(__('Cancel'), 'XiboDialogClose()');
        $response->AddButton(__('Send'), '$("#WakeOnLanForm").submit()');

    }

    /**
     * Wake on LAN
     */
    public function WakeOnLan()
    {



        $response = $this->getState();
        $displayObject = new Display($db);

        $displayId = \Xibo\Helper\Sanitize::getInt('DisplayId');

        if (!$displayObject->WakeOnLan($displayId))
            trigger_error($displayObject->GetErrorMessage(), E_USER_ERROR);

        $response->SetFormSubmitResponse(__('Wake on Lan command sent.'));

    }

    public function ScreenShot()
    {
        $displayId = \Xibo\Helper\Sanitize::getInt('DisplayId');

        // Output an image if present, otherwise not found image.
        $file = 'screenshots/' . $displayId . '_screenshot.jpg';

        // File upload directory.. get this from the settings object
        $library = Config::GetSetting("LIBRARY_LOCATION");
        $fileName = $library . $file;

        if (!file_exists($fileName)) {
            $fileName = Theme::ImageUrl('forms/filenotfound.gif');
        }

        $size = filesize($fileName);

        $fi = new finfo(FILEINFO_MIME_TYPE);
        $mime = $fi->file($fileName);
        header("Content-Type: {$mime}");

        //Output a header
        header('Cache-Control: no-cache, must-revalidate');
        header('Content-Length: ' . $size);

        // Return the file with PHP
        // Disable any buffering to prevent OOM errors.
        @ob_end_clean();
        @ob_end_flush();
        readfile($fileName);
    }

    public function RequestScreenShotForm()
    {

        $response = $this->getState();

        $displayId = \Xibo\Helper\Sanitize::getInt('displayId');

        // Set some information about the form
        Theme::Set('form_id', 'RequestScreenShotForm');
        Theme::Set('form_action', 'index.php?p=display&q=RequestScreenShot');
        Theme::Set('form_meta', '<input type="hidden" name="displayId" value="' . $displayId . '">');

        Theme::Set('form_fields', array(FormManager::AddMessage(__('Are you sure you want to request a screen shot? The next time the client connects to the CMS the screen shot will be sent.'))));

        $response->SetFormRequestResponse(NULL, __('Request Screen Shot'), '300px', '250px');
        $response->AddButton(__('Cancel'), 'XiboDialogClose()');
        $response->AddButton(__('Request'), '$("#RequestScreenShotForm").submit()');

    }

    public function RequestScreenShot()
    {



        $response = $this->getState();
        $displayObject = new Display($db);

        $displayId = \Xibo\Helper\Sanitize::getInt('displayId');

        if (!$displayObject->RequestScreenShot($displayId))
            trigger_error($displayObject->GetErrorMessage(), E_USER_ERROR);

        $response->SetFormSubmitResponse(__('Request Sent.'));

    }
}

?>